【问题标题】:arraylist y/n to enter values in javaarraylist y/n 在java中输入值
【发布时间】:2016-02-16 18:31:04
【问题描述】:

我需要创建一个包含 3 个字段(每个字段)的数组列表,此代码不起作用,需要帮助修复它。这项任务似乎很简单,但我无法弄清楚出了什么问题。我正在运行 netbeans

这是我目前所拥有的

import java.util.Scanner;
import java.util.ArrayList;
public class scientist1
{
    public static void main (String[] args)
    {
    Scanner kbd1 = new Scanner(System.in);
    ArrayList<Document> someStuff = new ArrayList<Document>();
    char quit = 'Y';
    String scientist, field, greatIdea;

        while (quit == 'Y')
        {
            System.out.print("\n Scientists name: ");
            scientist = scan.next();
            System.out.print(" scientists field: ");
            field = scan.next();
            System.out.print(" Scientists great Ideas: ");
            greatIdea = scan.nextInt();
            someStuff.add (new Document(field, scientist, greatIdea));
            System.out.print(" Enter Another Scientist? (Y/N)");
            String word = scan.next();
            word = word.toUpperCase();
            quit= word.charAt(0);
        }
        for(Document stuff : someStuff)
        System.out.println(stuff);
}
}



public class Document
{
public static String scientist, field;
private int greatIdea;
public Document (String Last, String First,String Idea)
{
    scientist = First;
    field = Last;
    greatIdea = Idea;
}
public String toString ()
{
    return "\n\n Name: " + field + ", " + scientist + "\n Document Code: " + greatIdea + "\n";
}
public boolean equals (Object other)
{
    return (field.equals(((Document)other).getLast())&&
    scientist.equals(((Document)other).getFirst()));
}
public int compareTo (Object other)
{
    int result;
    String otherFirst = ((Document)other).getFirst();
    String otherLast = ((Document)other).getLast();
    if (field.equals(otherLast))
        result = scientist.compareTo(otherFirst);
    else
        result = field.compareTo(otherLast);
    return result;
}
public String getFirst ()
{
    return scientist;
}
public String getLast ()
{
    return field;
}
}

【问题讨论】:

  • 我想你不应该在这里有static -> public static String scientist, field;
  • 是否很快必须成为冒泡排序?
  • 不,它不必是冒泡排序。我认为这是最简单的。
  • @Domisaur 好的。我可以澄清一下你想按科学家的名字提取文件的排序吗?
  • 是的,我想通过在程序中搜索科学家姓名来提取与科学家姓名相关的数据。我的主要问题是现在虽然@Dan 得到了包含 3 个部分的数组列表

标签: java arraylist


【解决方案1】:

如果您使用的是 Java 8,则可以使用 List.sort 执行此操作,如下所示:

someStuff.sort(Comparator.comparing(Document::getScientist));

如果您使用低于 Java 8 的版本,则需要通过实现 Comparator 接口来执行此操作,然后使用 Collections.sort 对对象进行排序。

【讨论】:

    【解决方案2】:

    好的,向您展示如何做到这一点,并让您有机会解决代码中的问题,我举了一个例子。像 nerdlyist 一样,为了简单起见,我将 a 类嵌套在主类中。我还使用了比较器类中 hagmic 建议的内置排序功能。这意味着它可以节省时间和精力,因为您不必编写自己的比较器。

    import java.util.Scanner;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Comparator;
    
    public class Test {
        private Scanner scan = new Scanner(System.in);
        private List<LayoutOfScientist> scientistsNames = new ArrayList<LayoutOfScientist>();
        private String name, field, idea;
        private boolean continueLoop = true;
        private int countTo3 = 0;
    
        private void run() {
            while(countTo3<3&&continueLoop) {
                if(countTo3>0) {
                    System.out.println("Would you like to add another scientist? (Y/N)");
                }
    
                if(countTo3 == 0 || scan.nextLine().equalsIgnoreCase("y")) {
                    System.out.println("Please enter the scientist's name:");
                    name = scan.nextLine();
                    System.out.println("Please enter the scientist's field:");
                    field = scan.nextLine();
                    System.out.println("Please enter the scientist's idea:");
                    idea = scan.nextLine();
                    scientistsNames.add(new LayoutOfScientist(name, field, idea));
                } else {
                    continueLoop = false;
                }
                countTo3++;
            }
    
            scientistsNames.sort(Comparator.comparing(LayoutOfScientist::getScientistName));
            for(LayoutOfScientist lOS : scientistsNames) {
                System.out.println(lOS.getScientistName() + ", " + lOS.getScientistField() + ", " + lOS.getScientistIdea());
            }
        }
    
        private class LayoutOfScientist {
            private String scientistName, scientistField, scientistIdea;
    
            private LayoutOfScientist(String scientistName, String scientistField, String scientistIdea) {
                this.scientistName = scientistName;
                this.scientistField = scientistField;
                this.scientistIdea = scientistIdea;
            }
    
            public String getScientistName() {
                return scientistName;
            }
    
            public String getScientistField() {
                return scientistField;
            }
    
            public String getScientistIdea() {
                return scientistIdea;
            }
        }
    
        public static void main(String[] args) {
            new Test().run();
        }
    }
    

    示例输入

    Dan
    Space
    2
    Y
    Tom
    Earth
    3
    Y
    Bob
    Space
    6
    

    输出

    Bob, Space, 6
    Dan, Space, 2
    Tom, Earth, 3
    

    【讨论】:

    • 我的意思不是听起来很失落,但我就是那个失落的人哈哈
    • 我也从未打算将第三个代码的代码设为 int,但谢谢。
    • @Domisaur 没问题。如果这有助于解决您的问题,您是否可以单击答案旁边的勾号,让其他人知道您的问题已解决?谢谢
    • 谢谢,我很感激 :)
    【解决方案3】:

    处理这个问题的一种方法是声明一个字符串数组的arraylist。 所以像:

    ArrayList<String[]> someStuff = new ArrayList<String[]>;
    

    此方法的一个问题是,每次将新元素附加到 someStuff 时,都需要初始化该单独的 String 数组: 例如:

    someStuff.add(new String[] {"Scientist", "Field", "Idea"});
    

    或者:

    someStuff.add(new String[3]);
    

    此时我建议使用 2 个字符串函数中的任何一个:

    compareTo(String str)
    

    或者:

    compareToIgnoreCase(String str)
    

    在按科学家姓名组织 ArrayList 的排序函数中。

    【讨论】:

      【解决方案4】:

      只有 3 个小错误..

      1. Scanner 的实例名为 kbd1,但用作 scan

        Scanner kbd1 = new Scanner(System.in);

      //使用like科学家=scan.next();

      //用作

      Scanner kbd1 = new Scanner(System.in);
      scientist = kbd1.next();
      
      1. String greatIdea;//字符串变量 //输入为int

        greatIdea = kbd1.nextInt();//错误

      2. 在 Document 类中

      private int greatIdea;//必须是String

      就是这样,你可以走了。

      PS: 格式不当见谅

      【讨论】:

      • 好的,我没有彻底检查你的代码,所以可能存在逻辑错误(在排序期间)......检查出来
      【解决方案5】:

      似乎问题是让您的文档进入列表而不是排序。为此,您应该解决被吐出的 8 个错误。下面的代码用一些注释进行了清理。主要的变化是为了便于编译,我将 Document 做成了一个嵌套类(您可以将其取出并导入)。

      import java.util.Scanner;
      import java.util.ArrayList;
      public class scientist1 {
          static class Document  {
              private String scientist, field, greatIdea; //Stay consistent with private and removed static.
      
              public Document  (String last, String first, String idea)
              {
                  scientist = first;
                  field = last;
                  greatIdea = idea;
              }
              public String toString ()
              {
                  return "\n\n Name: " + field + ", " + scientist + "\n Document  Code: " + greatIdea + "\n";
              }
              public boolean equals (Object other)
              {
                  return (field.equals(((Document )other).getLast())&&
                  scientist.equals(((Document )other).getFirst()));
              }
              public int compareTo (Object other)
              {
                  int result;
                  String otherFirst = ((Document )other).getFirst();
                  String otherLast = ((Document )other).getLast();
                  if (field.equals(otherLast))
                      result = scientist.compareTo(otherFirst);
                  else
                      result = field.compareTo(otherLast);
                  return result;
              }
              public String getFirst ()
              {
                  return scientist;
              }
              public String getLast ()
              {
                  return field;
              }
          }
          public static void main (String[] args) {
              Scanner scan = new Scanner(System.in);
              ArrayList<Document > someStuff = new ArrayList<Document >();
              char quit = 'Y';
              String scientist, field, greatIdea;
      
              while (quit == 'Y')
              {
                  System.out.print("\n Scientists name: ");
                  scientist = scan.next();
                  System.out.print(" scientists field: ");
                  field = scan.next();
                  System.out.print(" Scientists great Ideas: ");
                  greatIdea = scan.next();
                  someStuff.add(new Document (field, scientist, greatIdea));
                  System.out.print(" Enter Another Scientist? (Y/N)");
                  String word = scan.next();
                  word = word.toUpperCase();
                  quit= word.charAt(0);
              }
              for(Document  stuff : someStuff){
                  System.out.println(stuff);
              }
          }
      }
      

      【讨论】:

      • 我可以输入初始信息,但我无法选择循环播放它
      • 您是否进行了更改?我重新运行了这个循环并且输出工作正常。
      • 我正在使用 netbeans,如果那样的话。但是在我输入信息后,我得到了一个错误。我也从来没有打算让它成为一个 int 它也应该是一个字符串的好主意
      • @Domisaur 在运行此程序时,您是否在为 greatIdeas 做字符串以外的事情?那将导致错误。对代码进行了编辑以允许使用字符串。
      猜你喜欢
      • 2018-04-08
      • 2010-09-12
      • 2020-02-23
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      相关资源
      最近更新 更多