简体   繁体   English

如何从 Java 的单行输入中读取多个 Integer 值?

[英]How to read multiple Integer values from a single line of input in Java?

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.我曾尝试使用扫描仪,但我发现它只存储用户输入的第一个 integer。 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?扫描器只会得到第一个 integer 1. 是否可以从一行中得到所有 3 个不同的整数并在以后使用它们? 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.我无法发布我的源代码,但我想知道这是否可行。

I use it all the time on hackerrank/leetcode我一直在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]);
    }

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 int s by Integer.parseInt()数组的每个索引将保存数字的 String 表示,可以通过Integer.parseInt()将其设为int

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.默认情况下,Scanner 使用分隔符模式 "\\p{javaWhitespace}+" 匹配至少一个空格作为分隔符。 you don't have to do anything special.你不必做任何特别的事情。

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+]");

Scanner has a method called hasNext(): Scanner 有一个方法叫做 hasNext():

    Scanner scanner = new Scanner(System.in);

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

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

Java 8爪哇 8

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

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.以下是您将如何使用 Scanner 处理用户想要输入的尽可能多的整数并将所有值放入数组中。 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.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();
    }
}

There is more than one way to do that but simple one is using String.split(" ") this is a method of String class that separate words by a spacial character(s) like " " (space)有不止一种方法可以做到这一点,但最简单的方法是使用String.split(" ")这是 String 类的一种方法,它通过像“ "(空格)这样的空格字符来分隔单词


All we need to do is save this word in an Array of Strings.我们需要做的就是将这个词保存在一个字符串数组中。

Warning : you have to use scan.nextLine();警告:你必须使用scan.nextLine(); other ways its not going to work(Do not use scan.next();其他方式不起作用(不要使用scan.next();

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

now we need to convert these strings to Integers.现在我们需要将这些字符串转换为整数。 create a for loop and convert every single index of stringArray :创建一个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
}

Best way is converting the whole stringArray to an intArray :最好的方法是将整个 stringArray 转换为 intArray :

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

now do any proses you want like print or sum or... on intArray现在做任何你想要的散文,比如在 intArray 上打印或求和或...


The whole code will be like this :整个代码将是这样的:

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

This works fine ....这工作正常......

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

Or you can read them in a loop或者你可以循环阅读它们

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 4 , 5 6 7 8 , 1 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情况 2:当每行中的整数数未给出时

     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, eg splitting abc will emit two empty strings first请注意,您需要先进行 trim(): trim().split("\\\\s+") - 否则,例如拆分abc将首先发出两个空字符串

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

created this code specially for the Hacker earth exam专门为黑客地球考试创建了此代码


  Scanner values = new Scanner(System.in);  //initialize scanner
  int[] arr = new int[6]; //initialize array 
  for (int i = 0; i < arr.length; i++) {
      arr[i] = (values.hasNext() == true ? values.nextInt():null);
      // it will read the next input value
  }

 /* user enter =  1 2 3 4 5
    arr[1]= 1
    arr[2]= 2
    and soo on 
 */ 

It's working with this code:它正在使用此代码:

Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.next().toString();
System.out.println("Enter Phone # : ");
String phone = input.next().toString();

A simple solution can be to consider the input as an array.一个简单的解决方案是将输入视为数组。

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
}

You're probably looking for String.split(String regex).您可能正在寻找 String.split(String regex)。 Use " " for your regex.使用“”作为您的正则表达式。 This will give you an array of strings that you can parse individually into ints.这将为您提供一个字符串数组,您可以将其单独解析为整数。

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 .最好将整行作为字符串,然后使用 StringTokenizer 获取数字(使用空格作为分隔符),然后将它们解析为整数。 This will work for n number of integers in a line .这将适用于一行中的 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

    }

Using BufferedReader -使用 BufferedReader -

StringTokenizer st = new StringTokenizer(buf.readLine());

while(st.hasMoreTokens())
{
  arr[i++] = Integer.parseInt(st.nextToken());
}

When we want to take Integer as inputs当我们想将 Integer 作为输入时
For just 3 inputs as in your case:对于您的情况,只有 3 个输入:

import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();

For more number of inputs we can use a loop:对于更多数量的输入,我们可以使用循环:

import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
    a[i] = scan.nextInt();    
}

Use Java 8 Streams: 使用Java 8流:

 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        try{
          int num_of_arrays=Integer.parseInt(br.readLine());
          while(num_of_arrays>0){

              int[] num = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();

              num_of_arrays--;
            }

         }

for input: 用于输入:

1 1个

1 2 3 1 2 3

where num_of_arrays = 1 and array elements are in the next line. 其中num_of_arrays = 1,数组元素位于下一行。

This method only requires users to enter the "return" key once after they have finished entering numbers:这种方法只需要用户在输入完数字后输入一次“回车”键:

It also skips special characters so that the final array will only contains integers它还跳过特殊字符,因此最终数组将只包含整数

ArrayList<Integer> nums = new ArrayList<>();

    // User input
    Scanner sc = new Scanner(System.in);
    String n = sc.nextLine();

    if (!n.isEmpty()) {
        String[] str = n.split(" ");
        for (String s : str) {
            try {
                nums.add(Integer.valueOf(s));
            } catch (NumberFormatException e) {
                System.out.println(s + " cannot be converted to Integer, skipping...");
            }
        }
    }

//Get user input as a 1 2 3 4 5 6 .... and then some of the even or odd number like as 2+4 = 6 for even number //获取用户输入为 1 2 3 4 5 6 .... 然后是一些偶数或奇数,例如 2+4 = 6 表示偶数

Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int evenSum = 0;
        int oddSum = 0;

        while (n > 0) {
            int last = n % 10;
            if (last % 2 == 0) {
                evenSum += last;
            } else {
                oddSum += last;
            }

            n = n / 10;
        }

        System.out.println(evenSum + " " + oddSum);

    }
}

if ur getting nzec error, try this:如果你收到 nzec 错误,试试这个:

    try{
        //your code
    }
    catch(Exception e){
        return;
    }

i know it's old discuss :) i tested below code it's worked我知道这是旧的讨论:) 我测试了下面的代码,它有效

`String day = "";
 day = sc.next();
 days[i] = Integer.parseInt(day);`

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

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