0
did not understand how scanner works
I didn't understand how the scanner object works, that is, I didn't understand the example code they have provided. can someone explain it to me in terms of c++?
2 Answers
+ 4
Thank you @PradeepSaini
In addition
Scanner class helps to simplify getting user inputs.
The class has methods based on the data type. For instance, you could use;
nextInt() to read integer.
next() read one word string
nextLine() read line of string
nextBoolean to read bookean
..ect.
Well, pay attention that entering wrong data type will couse an exception, so to clear/reset you should use nextLine()
ex:
try{
input = scanner.nextInt();
}catch(Exception e){
scanner.nextLine();
}
You can expand the use of next method when used with regular expressions.
Example of excluding user input in range from A to D.
Note that I have used the regular expression (?=[A-Da-d]). which means accept only one letter from A to d
try{
input = scanner.next(Pattern.compile("(?=[A-Da-d])."));
break;
}catch(Exception e){
scanner.nextLine();
continue;
}
}
In below a simple example of how to get user input:
Ex:
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println();
System.out.println("Your name is " + name);
}
}
+ 3
c++ provide us cin() method to take input from user,
and in java provide a Scanner class in util package,
we use Scanner class by make its object
Scanner s = new Scanner(System.in);
by this way we create an object of scanner class.
now java also provide different methods to take input for different datatypes.
if you want to take integer value from user
you have to type
s.nextInt();