Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading input delimited by spaces in java

im struggling with the below question.

Question: Input contains the number of blocks n (1 ≤ n ≤ 20) and weights of the blocks w1, …, wn (integers, 1 ≤ wi ≤ 100000) delimited by white spaces. the input should be taken from the user.

  1. how should i write the input with spaces? (lets say my input for no. of blocks is n =5 and the weights of the blocks be : 2 3 55 6 33 - because n=5)
  2. how should i read the input which are given with white spaces and store it in some list or array ? using what commands.

please find my code:

public static void main(String[] args) {
    int b1 = 0;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter no. of blocks: ");
    b1 = in.nextInt();
    if (b1<=20) {
        in.nextLine();
        int[] arr = new int[b1];
        for (int i=0; i<b1; i++) {
            System.out.println("Enter a weights of ths blocks: ");
            if (arr[i]<=100000) {
          arr[i] = in.nextInt();




            }
    }
        }

i dont think this is the right way coz the input should be delimited with spaces..

i was thinking about the ways to proceed but couldnt come up with any solution. can u please help me our on this guys. thanks.

like image 555
Dev Avatar asked Jul 15 '26 08:07

Dev


2 Answers

  1. The input can be given at command line as "input1 input2 input3" (Weights separated by spaces)

  2. You can use Scanner to read the input. Consider the sample code below:

Assuming the input is only integers.

 Scanner scanner = new Scanner(System.in);
 int numOfBlocks = scanner.nextInt();
 int weightArray[] = new weightArray[numOfBlocks];
 for(int i=0;i<numOfBlocks;i++)
       {
        weightArray[i] = scanner.nextInt();
       }
 scanner.close();
//your logic
like image 117
Mithun Avatar answered Jul 17 '26 21:07

Mithun


There's a very easy way to read input delineated by spaces: use string.split(delimit):

String input = "this is a test";
String[] tokens = input.split(" ");

That'll give you an array, tokens, of "this", "is", "a", and "test".

Then you can convert to an int array like this:

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

Just make sure that you are sure that you have numbers as an input.

like image 25
Alex K Avatar answered Jul 17 '26 20:07

Alex K