java 扫描多个姓名,打印姓名(数量==姓名数量),并向每个姓名打印Hello

nmpmafwu  于 2023-01-07  发布在  Java
关注(0)|答案(2)|浏览(129)

我是Java新手,有一项任务:扫描一些“陌生人”的名字,然后读取这些名字,并打印“Hello+name”到控制台。如果陌生人的数量为零,则打印“Looks empty”,如果数量为负,则打印“Looks negative to me”。因此,控制台的输入和输出应该如下所示:

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

所以我有这个代码编辑的人与一些相关的任务,但似乎我错过了一些东西,因为我是新的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());
}
8hhllhi2

8hhllhi21#

通过使用do while循环,你可以一次又一次地询问用户这个数字是否是负数。

import java.util.Scanner;
public class Main
  {
    public static void main(String[] args) {
    int num;
    String name;
    Scanner scan = new Scanner(System.in);
    
    //The loop asks a number till the number is nonnegative
    do{
        
    System.out.print("Please enter the number of strangers: ");
    num = scan.nextInt();
    
    if(num<0) {
        
        System.out.println("It cannot be a negative number try again.");
    }else if(num==0) {
        
        System.out.println("Oh, it looks like there is no one here");
        break;
    }else{
        
        String[] strangers = new String[num];
        //Takes the names and puts them to the strangers array
        for(int i=0;i<num;i++) {
            System.out.print("Name " + (i+1) + " : ");
            name = scan.next();
            strangers[i] = name;
        }
        
        //Printing the array
        for(int j=0; j<num; j++) {
            System.out.println("Hello, " + strangers[j]);
        }
        break;
        
    }
    }while(num<0);

}
}
ntjbwcob

ntjbwcob2#

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

这是你的代码的外观,你需要添加成员函数input。nextLine();读取换行符,所以输入时不会有问题

相关问题