Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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());
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading