Home > OS >  How to print strings after inputting
How to print strings after inputting

Time:06-11

User inputs int number. Based on that number user can input the same number of strings. For example:

Input:

3
Dave
John
Ben

Output:

Hello, Dave
Hello, John
Hello, Ben

Currently it performs output immediately as only first string is being input:

3
Dave
Hello, Dave
John
Hello, John
Ben
Hello, Ben

What should I change? Can't get it right by myself

public class HelloStrangers {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        String stringNumber = scanner.nextLine();
        int number = Integer.parseInt(stringNumber);
        if (number < 0) {
            System.out.println("Seriously? Why so negative?");
        } else if (number == 0) {
            System.out.println("Oh, it looks like there is no one here");
        } else {
            int i = 0;
            for (i = 0; i < number; i  ) {
               String string = scanner.nextLine();
                System.out.println("Hello, "   string);
            }
        }
    }
}

CodePudding user response:

Store the input. Print it later.

  String[] list = new String[number];
  for (int i = 0; i < number; i  ) {
    String string = scanner.nextLine();
    list[i] = string;
  }
  for (int i = 0; i < number; i  ) {
    System.out.println("Hello, "   list[i]);
  }

CodePudding user response:

You'll need to store the strings in an array and then loop through another loop after saving each one:

String[] strings = new String[number];
for (int i = 0; i < number; i  ) {
  String string = scanner.nextLine();
  strings[i] = string;
}
for (int i = 0; i < number; i  ) {
  System.out.println("Hello, "   strings[i]);
}
  •  Tags:  
  • java
  • Related