HANDS-ON EXAMPLE 4.2.2 Asking for User Input In this exercise, you will ask the user for input and then output what the user entered. Before beginning this exercise, download the chapter files from the student companion website. The starter file InputSnippet.java is used in this exercise. 1. Launch jGRASP, and open the InputSnippet.java file. 2. Add your name to the header comment. 3. Examine the code. You will see three places where comments direct your activity. The work for comment 1 is completed for you. The variable booksRead has been defined, a prompt issued to request input from the user, and a message output to the user. /* Practice with input your name here */ import java.util.Scanner // this imports the Scanner class public class InputSnippet { public static void main( String [ ] args ) { Scanner input = new Scanner( System.in ) // create the input object /***** 1. Prompt the user for the number of books they have read this year, read the value into a variable of the appropriate type, and output the value in a message. */ System.out.print( "How many books have you read this year? " ) int booksRead = input.nextInt( ) System.out.println( booksRead + " is a lot of books!" ) // more code here } } 4. Compile and run the program to see the output. 5. Locate comment 2, and follow the instructions. The number of people in your family is an integer, so the data type should be int and the Scanner method should be nextInt( ). Enter the following code below the comment. Then, compile and run the program. /***** 2. Prompt the user for the number of people in their family, read the value into a variable of the appropriate type, and output the value in a message. */ System.out.print( "How many people are in your family? " ) int peopleInFamily = input.nextInt( ) System.out.println( "You have " + peopleInFamily + " people in your family." ) 6. Locate comment 3, and follow the instructions. The sum of two real numbers is a real number, so the data type should be a double and the Scanner method should be nextDouble( ). Enter the following code below the comment. Then, compile and run the program. /***** 3. Prompt the user for the sum of 1.55 and .20, read the value into a variable of the appropriate type, and output the value in a message. */ System.out.print( "What is 1.55 plus .20? " ) double sum = input.nextDouble( ) System.out.println( "1.55 plus .20 is " + sum + "." ) Copyright Goodheart-Willcox Co., Inc. 92 Introduction to Computer Science: Java Programming
Previous Page Next Page