【问题标题】:Array/ArrayList to make order with scanner inputArray/ArrayList 使用扫描仪输入进行排序
【发布时间】:2021-11-11 06:21:33
【问题描述】:

所以我的老师命令我制作一个程序

  1. 用扫描仪询问用户阵列的大小
  2. 程序需要了解是否存在带有单词“add”的扫描仪,它会将其后面的单词添加到数组中
  3. 需要存在的命令是 ADD、DELETE、VIEW 用于显示 index-n 和 DISPLAY 用于显示所有这些

这是我做的一个例子,但它仍然很不正确,请帮助我!!!

   public static void main(String[] args) {
    
    Scanner input = new Scanner(System.in);
    
    int a = input.nextInt();
    String arr[] = new String[a];
    for (int i = 0; i < a; i++) {
        for (int j=0;j<arr.length;j++){
        arr[i] = input.nextLine();
        }
    }
    for( String b : arr ){
        System.out.println(b);
    }
enter code here

扫描仪输入的一个例子是

7
ADD this
ADD IS
ADD not
ADD real
VIEW 2
DELETE not
DISPLAY

输出将是

not
this is real

【问题讨论】:

    标签: java arrays string arraylist


    【解决方案1】:

    没有理由问数组应该多长,因为我们使用的是动态数组 ArrayList。您可以使此代码更易于阅读,但这只是您要查找的示例:

    public final static void main(final String[] args)
        {
            final List<String> list = new ArrayList<String>();
    
            final Scanner scan = new Scanner(System.in);
    
            while (true)
            {
                final String command = scan.nextLine().toLowerCase();
    
                if (command.contains("add "))
                {
                    list.add(command.replace("add ", ""));
                } else if (command.contains("delete "))
                {
    
                    final String toDelete = command.replace("delete ", "");
                    if (!list.remove(toDelete))
                        System.out.format("\"%s\" didn't exist in the array!", toDelete);
    
                } else if (command.contains("view "))
                {
                    System.out.println(list.get(Integer.parseInt(command.replace("view ", ""))));
                } else if (command.equals("display"))
                {
                    for (final String str : list)
                    {
                        System.out.println(str);
                    }
                    break;
                } else
                {
                    System.out.println("Unknown command!");
                }
            }
            scan.close();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多