【问题标题】:i want to put user input and store it in an array when user types Exit, it should print the names the user typed in, ascending.. any tips?我想在用户输入退出时将用户输入并将其存储在一个数组中,它应该打印用户输入的名称,升序..有什么提示吗?
【发布时间】:2020-05-07 15:52:47
【问题描述】:

这是我的代码。我没有设法使用升序..我希望用户输入无限数量的名称,然后输入 exit 以获得结果..

import java.util.Scanner;
import java.util.ArrayList;

public class Arr {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("enter some Names");
        ArrayList<String> names = new ArrayList<String>();

        while (scanner.hasNextLine()) {
            if (scanner.hasNextLine()) {
                names.add(scanner.next());
            } else {
                String s1 = scanner.next();
                if ("exit".equalsIgnoreCase(s1)) {
                    break;
                }
            }
        }

        String string = "the Names you wrote are : ";
        for (String x : names) {
            System.out.print(x);
        }
        scanner.close();

    }
}

【问题讨论】:

  • 您永远不会输入else 部分。由于您在 while 循环本身中检查 scanner.hasNextLine,因此 if 语句中的检查是多余的。

标签: java arrays if-statement input


【解决方案1】:

if(scanner.hasNextLine()) 永远不会进入else 块,因为scanner.hasNextLine() 永远不会是false

相反,请执行以下操作:

String input = scanner.next();

if("exit".equalsIgnoreCase(input)) {
    break;
} else {
    names.add(input);
}

【讨论】:

  • 我不认为这在技术上是必要,但最好与"literal".equalsIgnoreCase(variable)进行比较,以防万一变量为null
  • @jirassimok 我认为反过来它更具可读性,但你是对的 - 它确实有道理。
猜你喜欢
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多