我試圖將一個整數作為用戶輸入并將其存盤在串列中,直到用戶點擊“q”。在用戶輸入“q”的那一刻,回圈終止。
代碼顯示InputMismatch錯誤:
import java.util.*;
public class SampleArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
int n;
List<Integer> array = new ArrayList();
while (true) {
n = sc.nextInt();
s = sc.nextLine();
if (s.equals("q")) {
break;
} else {
array.add(n);
}
}
Collections.sort(array);
System.out.println(array);
}
}
uj5u.com熱心網友回復:
您是否嘗試像下面的示例一樣實作它?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
List<Integer> array = new ArrayList();
while (true) {
s = sc.nextLine();
if (s.equalsIgnoreCase("q")) {
break;
}
int num = Integer.parseInt(s);
array.add(num);
}
Collections.sort(array);
System.out.println(array);
}
}
uj5u.com熱心網友回復:
看起來q正在嘗試存盤為int,所以這應該有效:
所有存盤為 a 的數字String都可以int使用該parseInt()方法決議為 an 。
s = sc.nextLine();
if (!s.equals("q"))
{
array.add(Integer.parseInt(s));
}
else
{
break;
}
uj5u.com熱心網友回復:
試試這個,
在你的 while 回圈中獲取字串使用的輸入,
s = sc.next();
而不是sc.nextLine();.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/393392.html
下一篇:解碼字串變數中的單個八進制字符
