我无法在一行中读取所有整数的程序而不必输入每个数字,并在终端窗口中的每个数字后按Enter键。
例如,终端窗口将显示为:
For the our text enter the first 9 digits: 013292373"
而不是
For the our text enter the first 9 digits: 0
1
2
3
... etc"
到目前为止,我的代码看起来像这样:
/**
* This program calculates the last number of a 10 digit ISBN number.
*/
import java.util.Scanner;
public class ISBNnum
{
public static void main(String[] args)
{
//Variables and Scanner
Scanner input = new Scanner(System.in);
int dOne;
int dTwo;
int dThree;
int dFour;
int dFive;
int dSix;
int dSeven;
int dEight;
int dNine;
int checksum;
//Input
System.out.print("For the our text enter the first 9 digits: ");
dOne = input.nextInt();
dTwo = input.nextInt();
dThree = input.nextInt();
dFour = input.nextInt();
dFive = input.nextInt();
dSix = input.nextInt();
dSeven = input.nextInt();
dEight = input.nextInt();
dNine = input.nextInt();
//Calculation
checksum = ((dOne * 1) + (dTwo * 2) + (dThree * 3) + (dFour * 4) + (dFive * 5) + (dSix * 6) +
(dSeven * 7) + (dEight * 8) + (dNine * 9)) % 11;
//Output
if (checksum == 10)
{
System.out.print("The whole ISBN is "+dOne+dTwo+dThree+dFour+dFive+dSix+dSeven+dEight+
dNine+"X");
}
else if (checksum < 10)
{
System.out.println("The whole ISBN is " + dOne + dTwo + dThree + dFour + dFive + dSix +
dSeven + dEight + dNine + " - " + checksum);
}
}
}
感谢您的帮助!
答案 0 :(得分:0)
Scanner s = new Scanner(System.in).useDelimiter("\\s*");
改编自:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
答案 1 :(得分:0)
尝试使用扫描仪并通过空格将String
拆分为String[]
import java.util.Scanner;
public class Foo {
public static void main(String[] args) {
Scanner s = new Scanner(System.in)
String input = s.nextLine();
String[] parts = input.split(" ");
for (String part : parts) {
System.out.println(part);
}
}
}
我用以下代码扩展了我的上述答案。当我编译并运行它时,它可以工作,用空格分隔九个数字。
public static void main(String[] args) {
//Variables and Scanner
Scanner input = new Scanner(System.in);
int[] numbers = new int[9];
int checksum = 0;
//Input
System.out.print("For the our text enter the first 9 digits, separated by spaces: ");
String numInput = input.nextLine();
String[] parts = numInput.split(" ");
for (int i = 0; i < parts.length; i++) {
numbers[i] = Integer.parseInt(parts[i]);
checksum += numbers[i] * (i + 1);
}
//Calculation
checksum %= 11;
}
遍历代码,首先创建一个Scanner input
对象,一个int[] numbers
,其中包含9个索引,并且int checksum
实例化为零。接下来,我提示用户输入九个以空格分隔的数字,然后使用input.nextLine()
接收整行,这会将stdin
返回到换行符。然后我用空格将numInput
拆分为String[] parts
,使第一个空间索引为零,第二个空间为索引1等。我遍历列表,更改每个{{1}将数字表示到String
个对象中,并将其放在索引int
的{{1}}数组中。然后,我使用numbers
(刚刚转换的数字)更新i
checksum
并乘以Integer
。在循环之后,我将numbers[i]
模数为11。
终端上的输入看起来像
i+1
如果您愿意,请将checksum
所在的行更改为For the our text enter the first 9 digits, separated by spaces: 1 4 6 2 8 7 2 4 10
,然后输入您的数字:
String[] parts = input.split(" ");