当我尝试运行下面的代码时,它甚至不允许我输入输入并抛出 NumberFormatException。谁能帮我,我回顾了类似的问题,但没有得到正确的答案。
public static String takeFieldName() {
String fullfield = "";
//Scanner sc = new Scanner(System.in);
System.out.println("Enter number of fields: ");
//int nofields = sc.nextInt();
int nofields = Integer.parseInt(sc.nextLine());
String[] fname = new String[nofields];
//sc.skip("/n");
System.out.println("Specify fields with names");
for(int i=0;i<fname.length;i++) {
System.out.println("Enter field :"+(i+1));
fname[i] = sc.nextLine();
}
System.out.println("Fields are:");
for(String s:fname) {
System.out.println(s);
}
return UserDAO.toCSV(fname);
}
异常(exception)是:
Enter tablename:
manikanta
table already exists
Enter tablename:
salamankhan
Enter number of fields:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at connections.UserDAO.takeFieldName(UserDAO.java:53)
at connections.Application.main(Application.java:11)
当我使用 nextInt() 获取数组的大小时,我得到的输出是:
Enter tablename:
salmankhan
Enter number of fields:
2
Specify fields with names
Enter field :1
Enter field :2
我需要分别获取字段 1 和字段 2。
takeTableName() 是该方法中的另一个函数,我调用 takeFieldName() 如果数据库中不存在该表,它将调用 takeFieldName() 方法来获取字段名称。因为我使用 next() 方法来获取表名
最佳答案
修改
int nofields = Integer.parseInt(sc.nextLine());
进入
int nofields = sc.nextInt());
关于java - 尝试获取数据时出现数字格式异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59406298/