Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Use the API for the Scanner class (java.util.Scanner) to answer the following

ID: 3796420 • Letter: 1

Question

1. Use the API for the Scanner class (java.util.Scanner) to answer the following:

a. What two lines of codes would you write to read a number from keyboard input using a Scanner object with the identifier keyIn and store in the int variable num?

b. What Scanner method would you use to get a String value from the input source and store it into a String variable called string1 ?

c. What is the difference betwen the Scanner methods next() and nextLine() ?

d. How can you determine if there is another token to be read? In other words, which Scanner method would you call to get a true/false response to tell you if there was any more input?

Explanation / Answer

a)

Scanner keyin= new Scanner(System.in); //keyin is an identifier which is an object of Scanner class to take input

int num= keyIn.nextInt(); //integer value will be stored in a variable name num.

b)

Scanner keyin= new Scanner(System.in);

String string1= keyIn.nexLine(); // the string which is inserted will be stored in string1

c)

Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.

d)

java.util.Scanner has many hasNextxyz methods that can be used to validate input. some of them are given below: