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

后端 未结 17 1324
天涯浪人
天涯浪人 2020-11-27 03:16

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 intege

相关标签:
17条回答
  • 2020-11-27 03:21

    I use it all the time on 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]);
        }
    
    0 讨论(0)
  • 2020-11-27 03:22

    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 
     */ 
    
    
    0 讨论(0)
  • 2020-11-27 03:24

    Scanner has a method called hasNext():

        Scanner scanner = new Scanner(System.in);
    
        while(scanner.hasNext())
        {
            System.out.println(scanner.nextInt());
        }
    
    0 讨论(0)
  • 2020-11-27 03:27

    Java 8

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
    
    0 讨论(0)
  • 2020-11-27 03:30

    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.

    0 讨论(0)
  • 2020-11-27 03:30

    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();
    
    0 讨论(0)
提交回复
热议问题