Java从一行读取多个整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23506429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:27:28  来源:igfitidea点击:

Java reading multiple ints from a single line

javainputjava.util.scanner

提问by Steven

I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:

我正在开发一个程序,我希望允许用户在出现提示时输入多个整数。我曾尝试使用扫描仪,但我发现它只存储用户输入的第一个整数。例如:

Enter multiple integers: 1 3 5

输入多个整数:1 3 5

The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.

扫描器只会得到第一个整数 1。是否有可能从一行中获取所有 3 个不同的整数,并在以后使用它们?这些整数是我需要根据用户输入操作的链表中数据的位置。我不能发布我的源代码,但我想知道这是否可能。

回答by adv12

You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.

您可能正在寻找 String.split(String regex)。使用“”作为您的正则表达式。这将为您提供一个字符串数组,您可以将其单独解析为整数。

回答by Sk1X1

If you know how much integers you will get, then you can use nextInt()method

如果你知道你会得到多少整数,那么你可以使用nextInt()方法

For example

例如

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

回答by BitNinja

You want to take the numbers in as a String and then use String.split(" ")to get the 3 numbers.

您想将数字作为字符串输入,然后使用它String.split(" ")来获取 3 个数字。

String input = scanner.nextLine();    // get the entire line after the prompt 
String[] numbers = input.split(" "); // split by spaces

Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()

数组的每个索引都将保存数字的字符串表示形式,这些数字可以int通过Integer.parseInt()

回答by sendon1982

Scanner has a method called hasNext():

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

    Scanner scanner = new Scanner(System.in);

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

回答by E.A.

Try this

尝试这个

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();
    }
}

By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.

默认情况下,Scanner 使用分隔符模式 "\p{javaWhitespace}+" 匹配至少一个空格作为分隔符。你不必做任何特别的事情。

If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this

如果要匹配空格(1 个或多个)或逗号,请将 Scanner 调用替换为

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

回答by Prasanth Louis

I use it all the time on hackerearth

我一直在hackerearth上使用它

    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]);
    }

回答by Mostafa

Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt()the number of times you would like to get an integer.

以下是您将如何使用 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();
    }
}

回答by 2rd_7

This works fine ....

这工作正常......

int a = nextInt();int b = nextInt();int c = nextInt();

int a = nextInt();int b = nextInt();int c = nextInt();

Or you can read them in a loop

或者你可以循环阅读它们

回答by rogue_leader

Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .

最好将整行作为字符串,然后使用 StringTokenizer 获取数字(使用空格作为分隔符),然后将它们解析为整数。这将适用于一行中的 n 个整数。

    Scanner sc = new Scanner(System.in);
    List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
    StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
    while(st.hasMoreTokens())  // iterate until no more tokens
    {
        l.add(Integer.parseInt(st.nextToken()));  // parse each token to integer and add to linkedlist

    }

回答by Abhimanyu Sharma

Using this on many coding sites:

在许多编码站点上使用它:

  • CASE 1:WHEN NUMBER OF INTEGERS IN EACH LINE IS GIVEN
  • 情况 1:当给定每行中的整数数时

Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4, 5 6 7 8, 1 1 2 2

假设您有 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 cwill 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]);
        }
    
  • 情况 2:当每行中的整数数未给出时

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

    请注意,您需要先修剪():trim().split("\\s+")- 否则,例如拆分a b c将首先发出两个空字符串

        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]);
        }