0

I have written a code to take string inputs and store in a string array in java. My problem is that when I declare size of string array as 3 it has to take three strings into string array but it only takes two string into the string array and doesn't accept the third one. Can anyone help me to solve the problem?

Code

import java.util.Scanner;
public class leet14 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n;
        System.out.println("enter length of string");
        n=sc.nextInt();
        String a[]=new String[n];
        System.out.println("enter string values");
        for(int i=0;i<a.length;i++){
            a[i]=sc.nextLine();
        }
        for(int j=0;j<a.length;j++){
           System.out.println(a[j]); 
        }
        }
}

output

enter length of string
3
enter string values
one
two

one
two
3
  • @Tzvi2 I already tried that. It was showing array out of bounds exception Commented Sep 9, 2020 at 5:09
  • @Tzvi2 The for-loop is correct; for(int i=0; i < a.length; i++) loops three times, from 0 to 2, which is correct. Commented Sep 9, 2020 at 5:27
  • My suspicion is that you need an sc.nextLine() before the for-loop to consume the newline from your previous use of the scanner to read the integer. Commented Sep 9, 2020 at 5:29

4 Answers 4

2

You have to add sc.nextLine() before start reading input string from console.

import java.util.Scanner;
public class leet14 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n;
        System.out.println("enter length of string");
        n=sc.nextInt();
        String a[]=new String[n];
        sc.nextLine();
        System.out.println("enter string values");
        for(int i=0;i<a.length;i++){
            a[i]=sc.nextLine();
        }
        for(int j=0;j<a.length;j++){
           System.out.println(a[j]); 
        }
    }
}

This would give you the desired results.

input:

enter length of string
3
enter string values
one
two
three

output:

one
two
three
Sign up to request clarification or add additional context in comments.

Comments

1

When you read an int and the want to read a full String, then you have to move a pointer inside Scanner to the next line. P.S. It is easy to find if you debug you program.

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.print("enter length of string: ");
    String[] arr = new String[scan.nextInt()];
    scan.nextLine();    // <-- move to the next line to be ready to read a whole string

    System.out.println("enter string values:");

    for (int i = 0; i < arr.length; i++) {
        System.out.format("line %d: ", i + 1);
        arr[i] = scan.nextLine();
    }

    for (int j = 0; j < arr.length; j++)
        System.out.println(arr[j]);
}

Output:

enter length of string: 3
enter string values:
line 1: one one
line 2: two two
line 3: three three
one one
two two
three three

Comments

1

I would suggest to take a look at this code, also, try not to use value names such as n, it could really improve readability and help you to see the problem.

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
    
    Scanner sc=new Scanner(System.in);
    int inputCount=0;
    System.out.println("enter length of string");
    try{
        inputCount=sc.nextInt();
    }catch(Exception  e){
        System.out.println("int please");
        System.exit(1);
    }
    String a[]=new String[inputCount];
    System.out.println("enter string values");
    
    for(int i=0;i<a.length;i++){
        a[i]=sc.next();
    }
    for(int j=0;j<a.length;j++){
       System.out.println(a[j]); 
    }
  }
}

Comments

1

To get your desired process, please simply change a[i]=sc.nextLine(); to a[i]=sc.next(); .Unless your string input has spaces in them, this should work fine, else place sc.nextLine(); before your for loop

this is how I see the problem;

nextInt(); expects and stores the first word of input as int, else an error is thrown, however, it doesn't break out of the current line.

So when you run n=sc.nextInt(); and gave the input

enter length of string
3

3 was saved to n but the system cursor still stays behind it like so, 3|,

N.B: the output stream is different from the input stream, so it doesn't matter that,System.out.println("enter string values");is run, the cursor for the input stream still stays behind 3;

enter length of string
3|
enter string values

a[i]=sc.nextLine() expects and stores the sentence after the cursor, else it breaks to the next line. But if the cursor is already on a new line, it gives the chance to enter a new sentence (then stores it if you want) and moves over to a new line.

so as there is no sentence after the cursor 3|, it breaks to the next line and assigns the break line (newline) command "\n" to a[0] in the for loop when i = 0,

so, since the cursor is now on a new line, it gives the option to enter a new sentence and stores it to a[1] when enter is tapped for i = 1 and moves to the next line, the same process is executed for when i = 2

then the contents of String[] a is displayed as follows;

enter length of string
3|   //after, nextInt() when i=0, since the cursor is not the first, it breaks the line, a[0] = "n" 
enter string values
|one //when  i=1, since it's the firstit gives chance for input, and stores to a[1]
|two  //when  i=1, since it's the firstit gives chance for input, and stores to a[1]
     //a[0] is displayed
one  //a[1] is displayed
two  //a[2] is displayed

I had fun giving my opinion on this, Thank You.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.