這將通過讀取空間或換行符分隔號碼。只需換行符或按回車鍵即可終止掃描。
Scanner sc = new Scanner(System.in);
Pattern newlineOrSpace = Pattern.compile(System
.getProperty("line.separator") + "|\\s");
sc.useDelimiter(newLineOrSpace);
List<Double> numbers = new ArrayList<Double>();
System.out.println("Enter numbers:");
while (sc.hasNextDouble()) {
numbers.add(sc.nextDouble());
}
for (Double number : numbers) {
System.out.println(number);
}
樣品試驗
Enter numbers:
1 2 3
5.5 7.2
.1
1.0
2.0
3.0
5.5
7.2
0.1
編輯
,你可以輸入數字到單獨的變量:
Scanner sc = new Scanner(System.in);
Pattern newlineOrSpace = Pattern.compile(System
.getProperty("line.separator") + "|\\s");
sc.useDelimiter(newlineOrSpace);
System.out.print("Enter a, b, c: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
System.out.format("a = %f, b = %f, c = %f", a, b, c);
樣品試驗
Enter a, b, c: 1.0 5 9
a = 1.000000, b = 5.000000, c = 9.000000
這不壞:)。但是,當我想要使用這種格式: '\t \t'掃描儀sc =新掃描儀(System.in); \t \t Pattern newlineOrSpace = Pattern.compile(System.getProperty(「line.separator」)+「| \\ s」); \t \t sc.useDelimiter(newlineOrSpace); \t \t double a = sc.nextDouble(); \t \t double b = sc.nextDouble(); \t \t double c = sc.nextDouble();' 它不工作...拋出異常。 我想使用這種格式,因爲在這之後我必須計算一個二次方程。 – blaces
我已經添加了一個輸入保存到離散變量的例子。它應該工作正常。 –
謝謝你的回答! – blaces