简体   繁体   中英

Array split not giving expected output

Sir i am trying to split array[i] and storing that into another array but it is not working. Here is my code

import java.util.Scanner;

public class prog1 {

  public static void main (String [] args){
      Scanner input = new Scanner(System.in);
      int a = input.nextInt();
      String arr1[] = new String [a];
      for (int i=0;i<a;i++) {
          arr1[i] = input.nextLine();
      }
      for (int i=0;i<a;i++) {
          String temp[] = arr1[i].split("\\+");
          System.out.println(temp.length);
          System.out.println(temp[0]);
      }
  }
}

Sample input :

 1
 arka + xyz

Expected Output :

2
arka 

But the output which i am getting

1
<blank>

I am new in java . would you please help me to solve this problem as well as tell me why i am facing this problem.

You only read an int with nextInt() and you didn't consume the end of the first line before reading additional lines in your for loop, so the first iteration of the for loop reads the end of the first line, not the second line.

Chomp the end of the first line before starting your for loop:

String chomp = input.nextLine();
for(int i=0;i<a;i++){
    // Then read the following lines here.

The problem is when you hit enter after entering a number it is read as the next line.

One way to solve this is to add input.next() ; right after int a = input.nextInt(); which will read the return character. I think then the application will behave as you expect.

Alternatively you could read the number like this.

int a = Integer.parseInt(input.nextLine());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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