Home > Software design >  Scan a number of names, print names (number==amount of names) and print Hello to each of them
Scan a number of names, print names (number==amount of names) and print Hello to each of them

Time:01-05

I am new to Java and have a task: Scanner a number of "strangers' " names, then read these names and print "Hello name" to the console. If number of strangers is zero, then print "Looks empty", if the number is negative, then print "Looks negative to me". So the input and output to console should look like this:

3
Den
Ken
Mel
Hello, Den
Hello, Ken
Hello, Mel

So I have this code edited from someone with some related task, but it seems I miss something as I am new to Java...

Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();

while (num==0) {
  System.out.println("Oh, it looks like there is no one here");
  break;

} while (num<0) {
  System.out.println("Seriously? Why so negative?");
  break;
}

String[] numbers = new String[num];
for (int i=0; i< numbers.length;i  ) {
  System.out.println("Hello, "  input.nextLine());
}

CodePudding user response:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the size of an Array");
        int num = input.nextInt();
        if(num==0) {
            System.out.println("Oh, it looks like there is no one here");
        }
        else if(num<0) {
            System.out.println("Seriously? Why so negative?");
        }
        else {
            String numbers[] = new String[num];
            input.nextLine();
            for (int i=0; i< num;i  ) {
              numbers[i]=input.nextLine();
            }
            for (int i=0; i< numbers.length;i  ) {
              System.out.println("Hello, "  numbers[i]);
            }
        }
    }
}

This is how your code will look and you'll need to add member function input.nextLine(); to read newline character, so there can't be problem regarding input

  • Related