0
How do use scanner.nextLine () and scanner.nextInt ()
4 ответов
+ 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)
+ 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.
0
ohh so line can only be used for String?
0
Don't really know what's catch but i kinda get the idea thank you for the informations.