[英]How can I make an input read out multiple integers on a single line?
How can I make it so that I can prompt the user to input multiple integers on one line that are seperated by spaces. 如何做到这一点,以便提示用户在一行上输入多个整数,并用空格分隔。 And if the first integer is 0 or less than 0 it will print out "Bad Input" when all the integers are inputted and the user presses enter.
如果第一个整数为0或小于0,则在输入所有整数并且用户按Enter键时,它将打印出“错误输入”。 Also how can I make it so that when the user enters a negative number at the end of the line, it will stop entering numbers and make multiply all of them together.
另外,我如何才能做到这一点,以便当用户在行尾输入负数时,它将停止输入数字并将所有数字相乘。
This is what I have so far but i'm not sure I am doing this right. 到目前为止,这是我所拥有的,但是我不确定我是否做对了。
import java.util.Scanner;
public class tempprime {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int count = 1;
String inputnumbers;
System.out.print("Enter integers: ");
inputnumbers = input.nextLine();
for (int i = 0; i < inputnumbers.length(); i++){
if (inputnumbers.charAt(i) == ' ')
count++;
}
int[] numbers = new int[count];
}
}
You already have it so the user can enter in values until they hit enter. 您已经有了它,以便用户可以输入值,直到他们按Enter键为止。 Now you can do is use a split operation to break the string up into an array of values.
现在,您可以做的是使用拆分操作将字符串拆分为一组值。
String[] values = inputnumbers.split('\s');
Then you could replace charAt with access to the array. 然后,您可以将charAt替换为对数组的访问。
Alternatively, Scanner already allows the user to enter in as many integers as they need on the same line. 另外,Scanner已经允许用户在同一行上输入所需数量的整数。 nextLine() finds the first occurance of a new line, but you can use input.nextInt(), grabs the next int stopping at a space, multiple times and read them in one at a time.
nextLine()查找新行的第一个匹配项,但是您可以使用input.nextInt(),获取在一个空格处停止的下一个int,多次并一次读取它们。 You can also check if there are any more values remaining using the scanners hasNext methods.
您还可以使用扫描仪的hasNext方法检查是否还有剩余的值。
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You can see an example of reading multiple ints below. 您可以在下面看到读取多个整数的示例。 The user can enter them in one at a time, or 3 at a time and should still work the same.
用户可以一次输入一个,也可以一次输入3个,但仍应使用相同的功能。
Scanner in = new Scanner(System.in);
System.out.print("Enter 3 ints:");
int a,b,c;
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
System.out.printf("A: %d B: %d C: %d", a, b ,c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.