简体   繁体   English

Java-如何从同一行读取多个值

[英]Java - How to read multiple values from the same line

I'm working on a java assignment and was stuck on this part. 我正在处理Java作业,并且停留在这一部分。 Basically we are to get the user to input three positive non-zero integers using the scanner. 基本上,我们要使用户使用扫描仪输入三个正非零整数。

It's supposed to look something like this 应该看起来像这样

Enter three integer values: 2 2 10 输入三个整数值:2 2 10

The numbers (2, 2, 10) cannot form a triangle. 数字(2、2、10)不能形成三角形。

I was wondering how can I code it so that entering the "2 2 10" could be read as three different integers that are separated by a comma. 我想知道如何编码,以便将输入的“ 2 2 10”读为三个不同的整数,并用逗号分隔。 Thank you very much in advance. 提前非常感谢您。

Read the input with java.util.Scanner and a for loop: 使用java.util.Scanner和for循环读取输入:

Scanner sc = new Scanner(System.in);
int[] values = new int[3];

for (int i = 0; sc.hasNextInt() && i < 3; i++) {
    values[i] = sc.nextInt();
}

Try this: 尝试这个:

Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
String[] inValues = line.split(" ");
int[] values = new int[inValues.length];
for(int i = 0; i < inValues.length; i++){
    values[i] = Integer.parseInt(inValues[i]);
}

You can make it as follows: 您可以按如下方式进行:

String sentence = scanner.nextLine();

And you can make: 您可以:

String[] splittedByComma = sentence.split(","); 

Or by space: 或按空间:

String[] splittedBySpace = sentence.split(" ");

Or an array list like the following example: 或类似以下示例的数组列表:

How to split a comma-separated string? 如何分割逗号分隔的字符串?

Then parse each of them to integers. 然后将它们每个解析为整数。

scanner.nextInt is your answer Scanner.nextInt是您的答案

final BufferedReader input = new BufferedReader(
    new InputStreamReader(System.in));

// enter yours 2 2 10 and press Enter
final String line = input.readLine();

final Scanner s = new Scanner(line);
int a = s.nextInt(); // reads 2
int b = s.nextInt(); // reads 2
int c = s.nextInt(); // reads 10

if (a + b > c || a + c > b || b + c > a ) {
    System.out.println(
        "No triangle can be composed from " + a + ", " + b + ", " + c );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM