在Java中如何从一行输入中读取多个整数值?

40

我正在开发一个程序,我想要允许用户在提示输入时输入多个整数。我尝试使用Scanner,但我发现它只能存储用户输入的第一个整数。例如:

输入多个整数:1 3 5

Scanner只会获取第一个整数1。是否有可能从一行中获取所有3个不同的整数,并且以后能够使用它们?这些整数是链表中需要基于用户输入操作数据的位置。我无法发布我的源代码,但我想知道是否有可能实现。


1
我需要要求用户在一行内输入1到5之间的整数。例如,用户可以输入1 3或1 3 4等。 - Steven
1
@S.M.AlMamun 那对我的问题不起作用...用户输入必须在一行上。 - Steven
21个回答

45

我经常在hackerrank/leetcode上使用它。

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String  lines = br.readLine();    
        
    String[] strs = lines.trim().split("\\s+");
            
    for (int i = 0; i < strs.length; i++) {
    a[i] = Integer.parseInt(strs[i]);
    }

我刚刚制作了一个包含这段代码的文本文件...为了在在线挑战中使用它 -_- - Ashish sah

15

试试这个

public static void main(String[] args) {
    Scanner in = new Scanner(System.in); 
    while (in.hasNext()) {
        if (in.hasNextInt())
            System.out.println(in.nextInt());
        else 
            in.next();
    }
}

默认情况下,Scanner使用定界符模式"\p{javaWhitespace}+"作为定界符,该模式至少匹配一个空白字符。您无需进行任何特殊处理。

如果您想匹配空格(1个或多个)或逗号,请将Scanner调用替换为以下内容

Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");

13
你想将数字作为字符串输入,然后使用String.split(" ")获取这3个数字。
String input = scanner.nextLine();    // get the entire line after the prompt 
String[] numbers = input.split(" "); // split by spaces
每个数组索引将保存可以通过 Integer.parseInt() 转换为 int 的数字的字符串表示形式。

7

Scanner有一个叫做hasNext()的方法:

    Scanner scanner = new Scanner(System.in);

    while(scanner.hasNext())
    {
        System.out.println(scanner.nextInt());
    }

3
它一直在要求输入。如何在行尾停止它? - Aravin
1
在你想要退出的地方添加 System.exit();。 - sendon1982

6

Java 8

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();

6

如果你知道你将要获取的整数数量,你可以使用 nextInt() 方法。

举个例子:

Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
    integers[i] = sc.nextInt();
}

4
这是如何使用Scanner处理用户输入的整数,并将所有值放入数组中。但是,仅在您不知道用户将输入多少整数时才应使用此功能。如果您知道,请使用 Scanner.nextInt() 获取所需整数的次数。
import java.util.Scanner; // imports class so we can use Scanner object

public class Test
{
    public static void main( String[] args )
    {
        Scanner keyboard = new Scanner( System.in );
        System.out.print("Enter numbers: ");

        // This inputs the numbers and stores as one whole string value
        // (e.g. if user entered 1 2 3, input = "1 2 3").
        String input = keyboard.nextLine();

        // This splits up the string every at every space and stores these
        // values in an array called numbersStr. (e.g. if the input variable is 
        // "1 2 3", numbersStr would be {"1", "2", "3"} )
        String[] numbersStr = input.split(" ");

        // This makes an int[] array the same length as our string array
        // called numbers. This is how we will store each number as an integer 
        // instead of a string when we have the values.
        int[] numbers = new int[ numbersStr.length ];

        // Starts a for loop which iterates through the whole array of the
        // numbers as strings.
        for ( int i = 0; i < numbersStr.length; i++ )
        {
            // Turns every value in the numbersStr array into an integer 
            // and puts it into the numbers array.
            numbers[i] = Integer.parseInt( numbersStr[i] );
            // OPTIONAL: Prints out each value in the numbers array.
            System.out.print( numbers[i] + ", " );
        }
        System.out.println();
    }
}

3

有多种方法可以实现,但简单的方法是使用 String.split(" ")。这是 String 类的一个方法,它通过特殊字符(如空格 " ")将单词分开。


我们需要做的就是将这个单词保存在一个字符串数组中。

注意: 你必须使用 scan.nextLine(); ,其他方式不起作用(不要使用 scan.next();)

String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");

现在我们需要将这些字符串转换为整数。创建一个for循环,并将stringArray的每个单独索引转换为整数:

for (int i = 0; i < stringsArray.length; i++) {
    int x = Integer.parseInt(stringsArray[i]);
    // Do what you want to do with these int value here
}

最好的方法是将整个stringArray转换为intArray:
 int[] intArray = new int[stringsArray.length];
 for (int i = 0; i < stringsArray.length; i++) {
    intArray[i] = Integer.parseInt(stringsArray[i]);
 }

现在你可以对intArray进行任何处理,比如输出或求和等等。


完整的代码如下:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String user_input = scan.nextLine();
        String[] stringsArray = user_input.split(" ");

        int[] intArray = new int[stringsArray.length];
        for (int i = 0; i < stringsArray.length; i++) {
            intArray[i] = Integer.parseInt(stringsArray[i]);
        }
    }
}

1
一个简单的解决方案是将输入视为数组。
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();          //declare number of integers you will take as input
int[] arr = new int[n];     //declare array
for(int i=0; i<arr.length; i++){
    arr[i] = sc.nextInt();   //take values
}

1

在许多编程网站上使用:

  • 情况1:已知每行整数的数量

假设您有3个测试用例,每行包含4个以空格分隔的整数输入:1 2 3 45 6 7 81 1 2 2

        int t=3,i;
        int a[]=new int[4];

        Scanner scanner = new Scanner(System.in);

        while(t>0)  
        {
            for(i=0; i<4; i++){
                a[i]=scanner.nextInt();
                System.out.println(a[i]);
            }   

        //USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
            t--;
        }
  • CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN

        Scanner scanner = new Scanner(System.in);
    
        String lines=scanner.nextLine();
    
        String[] strs = lines.trim().split("\\s+");
    

    Note that you need to trim() first: trim().split("\\s+") - otherwise, e.g. splitting a b c will emit two empty strings first

        int n=strs.length; //Calculating length gives number of integers
    
        int a[]=new int[n];
    
        for (int i=0; i<n; i++) 
        {
            a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer 
            System.out.println(a[i]);
        }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接