Java reading multiple ints from a single line

2019-01-06 14:17发布

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

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.

14条回答
劳资没心,怎么记你
2楼-- · 2019-01-06 14:28

When we want to take Integer as inputs
For just 3 inputs as in your case:

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();    
}
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-06 14:29

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.

查看更多
劫难
4楼-- · 2019-01-06 14:29

Using BufferedReader -

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

while(st.hasMoreTokens())
{
  arr[i++] = Integer.parseInt(st.nextToken());
}
查看更多
够拽才男人
5楼-- · 2019-01-06 14:36

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

For example

Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
    integers[i] = sc.nextInt();
}
查看更多
【Aperson】
6楼-- · 2019-01-06 14:41

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 */ 

     '}
查看更多
霸刀☆藐视天下
7楼-- · 2019-01-06 14:44

This works fine ....

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

Or you can read them in a loop

查看更多
登录 后发表回答