gpt4 book ai didi

java - 尝试读取用户输入时出现 NumberFormatException

转载 作者:行者123 更新时间:2023-12-01 22:32:45 24 4
gpt4 key购买 nike

我是 Java 新手,正在编写一个程序来显示姓名、地址、电话号码和生日,其中姓名和电话号码是公开,生日是私有(private),并且其他信息 protected

这是我的核心类(class):

public class newd {

public int Name;
public int Phone_no;
protected String Address;
protected int Age;
private int Birth_day;

void GetData() throws IOException
{
InputStreamReader IN = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(IN);

System.out.print("Enter Name : ");
String S1 = BR.readLine();
Name = Integer.parseInt(S1);

System.out.print("Enter Phone_no : ");
String S2 = BR.readLine();
Phone_no = Integer.parseInt(S2);

System.out.print("Enter Address : ");
String S3 = BR.readLine();
Age = Integer.parseInt(S3);

System.out.print("Enter Age : ");
String S4 = BR.readLine();
Age = Integer.parseInt(S4);

System.out.print("Enter Birth_day : ");
String S5 = BR.readLine();
Birth_day = Integer.parseInt(S5);

}

void Display()
{
System.out.println("Name : " + Name);
System.out.println("Phone No : " + Phone_no);
System.out.println("Address : " + Address);
System.out.println("Age : " + Age);
System.out.println("Birth Day : " + Birth_day);
}

}

这是我的使用方法:

public class newdirectory {

public static void main(String[] args) throws IOException {

newd D = new newd();

D.GetData();
D.Display();

}

}

当我编译程序时,它显示这个对话框。

Enter Name : kamrul
Exception in thread "main" java.lang.NumberFormatException: For input string: "kamrul"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at newd.GetData(newd.java:21)
at newdirectory.main(newdirectory.java:9)

谁能帮助我理解我做错了什么?

最佳答案

System.out.print("Enter Name : ");
String S1 = BR.readLine();
Name = Integer.parseInt(S1);


parseInt(...) 仅当传入的字符串可以解析为整数时才有效,否则将抛出 NumberFormatException

引用this link here


对于你的情况,我想应该是:

public String Name;

你只需要这样做:

System.out.print("Enter Name : ");
Name = BR.readLine();


地址相同:

System.out.print("Enter Address : ");
Address = BR.readLine();

关于java - 尝试读取用户输入时出现 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27372447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com