【问题标题】:java String Array : getting information from the user and display the number in the arrayjava String Array : 从用户那里获取信息并显示数组中的数字
【发布时间】:2020-07-18 06:01:52
【问题描述】:

我为电话号码创建了一个名称字符串数组和 Int 数组,并要求用户从数组列表中选择名称,我们想要显示名称的确切数字

public class main {

public static void main(String[] args) {
    String[] names = {"Name one  ","Name two ","name three ","Four"};
    int[] num ={12345,56789,25622,21478};
    for (int i = 0;i < names.length;i++)
    {
        System.out.println(names[i]);

    }
    System.out.println("Enter the Name To get Numbers");
    Scanner scanner = new Scanner(System.in);
    String name=scanner.next();
    for (int i=0; i <names.length; i++)
    {
        if (name.equals(names[i]));
        {
            System.out.println(num[i]);
        }

    }
    

}

我得到的输出是

Name one  
Name two 
name three 
Four
Enter the Name To get Numbers
Four
12345
56789
25622
21478

Process finished with exit code 0

我输入的任何名称都会显示数组中的所有数字如何解决这个问题? 我需要的输出是

Name one  
    Name two 
    name three 
    Four
    Enter the Name To get Numbers
    Four
    21478

【问题讨论】:

  • if 条件的末尾有一个分号。

标签: java arrays


【解决方案1】:

if 条件的末尾有一个分号。删除它,你的代码就可以正常工作了。

if (name.equals(names[i])) {
        System.out.println(num[i]);
}

【讨论】:

  • 谢谢,为什么当我退出 Semicoln 时它会进入循环?你能解释一下吗?最好不要去了解
  • 解释见this post
  • 如果用户输入不在名称数组列表中,这意味着我们要告诉用户选择数组中的名称,因为我在 if 末尾使用 else 语句并运行它如果我输入错误的数组,则显示在循环中选择名称,即使我使用 break 它也不会停止如何解决这个问题
  • 将为每个if 执行一个else。将布尔标志设置为 false。在if 中将其设置为true。然后在 for 循环完成后,检查该布尔值是否仍然为 false。如果是,则打印出没有一个名称与用户输入的名称匹配。
猜你喜欢
  • 1970-01-01
  • 2019-04-06
  • 2018-10-07
  • 2016-02-08
  • 1970-01-01
  • 2019-08-19
  • 2014-09-16
  • 2019-03-29
  • 1970-01-01
相关资源
最近更新 更多