0

How do use scanner.nextLine () and scanner.nextInt ()

21st Aug 2017, 4:07 PM
Zawe
Zawe - avatar
4 Answers
+ 3
@Zawe nextLine() returns a string. So, if you want to use it for an int, it will need to be casted. (And likely surrounded with try-catch). try { int input = Integer.parseInt(scanner.nextLine()); } catch (InputMisMatchException e){ System.out println("Error."); } There's really no point in doing this though. nextInt() already does this, without issues. (Such as spaces)
21st Aug 2017, 4:19 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
//importing Scanner// import java.util.Scanner; //Creating a scanner object// Scanner scn = new Scanner(System.in); //String and int declaration// String y; int i; //initializing String & int variable to scanner// y= scn.nextLine(); i = scn.nextInt(); //print// System.out.println(y); System.out.println(i); if you ran this code you will get an input screen the first line will be for String variable "y" and the next line will be int variable "i" . remeber a String uses nextLine() method whilst int uses nextInt() method.
21st Aug 2017, 6:21 PM
Special
0
ohh so line can only be used for String?
21st Aug 2017, 4:14 PM
Zawe
Zawe - avatar
0
Don't really know what's catch but i kinda get the idea thank you for the informations.
21st Aug 2017, 4:34 PM
Zawe
Zawe - avatar