读取扫描仪输入java



使用扫描仪功能读取输入时出现问题。到目前为止,我的代码如下:

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int total_weight = 0;

do{
int n_elements = sc.nextInt();
if (n_elements == 0) {
break;
}

for (int i = 0; i < n_elements; i++) {
int [] item_weights = new int[n_elements];
item_weights[i] = sc.nextInt();
total_weight += item_weights[i];
System.out.println(item_weights[i]);
}
System.out.println(total_weight);
System.out.println(n_elements);
sc.nextLine();

}while(sc.nextInt() != 0);

输入格式是这样的,逐行读取。(0表示数据结束(

8 529 382 130 462 223 167 235 52912 528 129 376 504 543 363 213 138 206 440 504 4180

我的代码读起来是这样的,

52938213046222316723552926578.1293765045433632131382064405044180

更改线路时缺少一些数字

您只读取int值。删除sc.nextLine();

while(sc.nextInt() != 0);

也在消耗价值。您正在检查之前输入的值是否为0break。所以类似的东西

do {
int n_elements = sc.nextInt();
if (n_elements == 0) {
break;
}
for (int i = 0; i < n_elements; i++) {
int[] item_weights = new int[n_elements];
item_weights[i] = sc.nextInt();
total_weight += item_weights[i];
System.out.println(item_weights[i]);
}
System.out.println(total_weight);
System.out.println(n_elements);
} while (sc.hasNextInt());

应该解决这个问题。

最新更新