0

I am trying to create a String Revert Program where I enter Strings and they are stored in an Array -When the array is complete it prints the contents Backwards -If the user enters Quit the program stops and prints backwards without storing quit in the array

However my code doesn't print the last entry Im not sure why?

import java.util.*;
import java.io.*;

class StringRevert {

    public static void main(String[] args) {

        String buffer[];
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter Size: ");
        int num = scan.nextInt();

        buffer = new String[num];

        String read = scan.nextLine();
        for(int i=0; i<buffer.length; i++) {
            if(read.equals("quit")) {
                break;
            } else {
                buffer[i] = read;
            }
            read = scan.nextLine();
        }

        for(int k=buffer.length -1; k>=0; k--) {
            System.out.println(buffer[k]);
        }
    }
}
RandomMath
  • 661
  • 10
  • 27
  • http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-next-nextint-or-other-nextfoo-methods – Reimeus May 09 '15 at 17:52
  • 1
    Consider using an `ArrayList` instead of the array, because in your example the user has to enter the number of `Strings` but afterwards is able to quit earlier - this makes no sense. With an `ArrayList` you can add new entries until the user types "quit" without asking for the number before. – tomse May 09 '15 at 17:52

2 Answers2

1

Replace your for loop with this:

String read = null;
for(int i=0; i<buffer.length; i++) {
    read = scan.nextLine();
    if(read.equals("quit")) {
        break;
    } else {
        buffer[i] = read;
    }
}

You want to read the new line at the beginning of the loop, not at the end.

Anubian Noob
  • 12,897
  • 5
  • 47
  • 69
1

The only problem I can find in your code is skipping the line after nextInt() .The nextInt() method doesnot consume the whole line it only consume the next token of the input as an int so you are on the same line(where you read the int) and you have to skip the line.By doing scan.nextLine(); after scan.nextInt();

String buffer[];
Scanner scan = new Scanner(System. in );
System.out.println("Enter Size: ");
int num = scan.nextInt();

buffer = new String[num];
scan.nextLine(); // skipping the line
String read = scan.nextLine();
for (int i = 0; i < buffer.length; i++) {
    if (read.equals("quit")) {
        break;
    } else {
        buffer[i] = read;
    }
    read = scan.nextLine();
}

for (int k = buffer.length - 1; k >= 0; k--) {
    System.out.println(buffer[k]);
}

Demo(Prints the array backwards)

singhakash
  • 7,613
  • 4
  • 25
  • 59