我下面有一个Java程序。当我在用Integer.parseInt(sc.nextLine())
获取整数值后用sc.nextInt((获取整数值时。我收到numberformat异常。请帮帮我。
public class User {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=Integer.parseInt(sc.nextLine());
int rank=sc.nextInt();
String arr[]=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLine();}
有人能解释一下我的代码出了什么问题吗。
int n=Integer.parseInt(sc.nextLine());
当输入6 2
时,这一行尝试将6 2
转换为整数,因为您使用了.nextLine()
。这就是为什么你得到Numberformat Exception
。您也可以使用n=sc.nextInt()
来获取n的输入。在循环中输入字符串之前,请注意换行。