import java.util.Scanner;
class Tugas3 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String nama;
int umur,nomor;
System.out.println("Enter Your Full Name : ");
nama = input.nextLine();
System.out.println("Enter Your Age : ");
umur = input.nextInt();
input.nextLine();
System.out.println("Input Your Phone Number : ");
nomor = input.nextInt();
System.out.printf("Contact : "+nama+" "+umur+""+(char)48+""+nomor);
}
}
所以我只想输入0号,但我一直收到错误信息..任何解决方案?
答案 0 :(得分:0)
这将允许任何输入并避开InputMismatchException
,但原始代码没有任何问题。问题是您尝试使用不正确的输入来测试扫描仪。
package test;
import java.util.Scanner;
public class Tugas3 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String nama;
String line;
int umur = 0,nomor = 0;
System.out.println("Enter Your Full Name : ");
nama = input.nextLine();
System.out.println("Enter Your Age : ");
line = input.nextLine();
try{
umur = Integer.parseInt(line.trim());
}catch(NumberFormatException e){
System.out.println("Invalid number. Set to 0.");
}
System.out.println("Input Your Phone Number : ");
line = input.nextLine();
try{
nomor = Integer.parseInt(line.trim());
}catch(NumberFormatException e){
System.out.println("Invalid number. Set to 0.");
}
System.out.printf("Contact : "+nama+" "+umur+""+(char)48+""+nomor);
}
}