我想首先从控制台获取输入,一个整数,然后是一个由逗号和空格分隔的整数数组。
输入如下:
5
55,24,32,22,89
我的代码是:
public static void main (String[] args) {
//code
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] array = new int[num];
String line = sc.nextLine();
line = line.replaceAll(" ","");
String[] temp = line.split(",");
for(String i :temp)
{
System.out.print(i+" ");
}
}
但是它显示InputMismatchException。
答案 0 :(得分:1)
尝试在sc.nextLine();
之前添加String line = sc.nextLine();
尝试此代码:-
import java.util.*;
public class Main {
public static void main(String[] args) {
// code
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] array = new int[num];
sc.nextLine(); // advance to new line
String line = sc.nextLine();
line = line.replaceAll(" ", "");
String[] temp = line.split(",");
for (String i : temp) {
System.out.print(i + " ");
}
}
}
输出:-
5
55, 24, 32, 22, 89
55 24 32 22 89