The hasNextXxx() method is often used to determine whether the next input content belongs to Xxx
and return a boolean value (true or false)
import java.util.Scanner;
public class pd {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
boolean b=sc.hasNextInt();
char c=sc.next().charAt(0);
System.out.print(b);
}
}
Enter j return value is false
Therefore, it is often used as a judgment condition in an if statement or a loop statement
import java.util.Scanner;
public class pd {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.print("请输入成绩:");
if(sc.hasNextInt()){
int a =sc.nextInt();
System.out.println("你的成绩是:"+a+"分");
}else {
System.out.println("输入错误,请输入数字!");
}
}
}
Initially enter the char type
There seems to be no nextChar() method in Scanner in java
It only provides the input method of String String class
But java provides a nice workaround
The charAt(n) method can return the character at the nth position of the string (n starts from 0)
So we can use this method to implement char type input
import java.util.Scanner;
public class pd {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
char a=sc.next().charAt(0);
System.out.print(a);
}
}