arraylist y / n在java中输入值

时间:2016-02-16 18:31:04

标签: java arraylist

我需要创建一个包含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;
}
}

5 个答案:

答案 0 :(得分:1)

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

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

如果您使用的内容少于Java 8,则需要执行Comparator界面,然后使用Collections.sort对对象进行排序。

答案 1 :(得分:0)

解决这个问题的一种方法是声明String数组的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的sort函数中。

答案 2 :(得分:0)

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

while

答案 3 :(得分:0)

好的向您展示如何做到并让您有机会解决代码中的问题我做了一个例子。就像书呆子一样,为了简单起见,我在主类中嵌套了一个类。我还使用了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

答案 4 :(得分:0)

只有3个小错误..

  1. using Moq; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test { [TestFixture] class TestWareHouse { private WareHouse warehouse = new WareHouse(); private static String TALISKER = "Talisker"; private static String HIGHLAND_PARK = "Highland Park"; [SetUp] public void SetUp() { //reset warehouse = new WareHouse(); warehouse.Add(TALISKER, 50); warehouse.Add(HIGHLAND_PARK, 25); } //regular testing [Test] public void testOrderIsFilledIfEnoughInWarehouse() { Order order = new Order(TALISKER, 50); order.Fill(warehouse); Assert.True(order.isFilled()); Assert.AreEqual(0, warehouse.GetInventory(TALISKER)); } [Test] public void testOrderDoesNotRemoveIfNotEnough() { Order order = new Order(TALISKER, 51); order.Fill(warehouse); Assert.False(order.isFilled()); Assert.AreEqual(50, warehouse.GetInventory(TALISKER)); } //Now I am trying to do the things with Mock [Test] public void testOrderIsFilledIfEnoughInWarehouseMock() { Order order = new Order(TALISKER, 50); //-- Creating a fake ICustomerRepository object var warehouseMock = new Mock<WareHouse>(); //warehouseMock warehouseMock .Setup(m => m.FillIt(TALISKER, 50)) .Returns(true); order.Fill(warehouseMock.Object); //-- Assert ---------------------- Assert.IsTrue(order.isFilled()); warehouseMock.Verify(x => x.FillIt(It.IsAny<string>(), It.IsAny<int>()), Times.Exactly(1)); } [Test] public void testFillingDoesNotRemoveIfNotEnoughInStock() { Order order = new Order(TALISKER, 51); //-- Creating a fake ICustomerRepository object var warehouseMock = new Mock<WareHouse>(); warehouseMock .Setup(m => m.FillIt(It.IsAny<string>(), It.IsAny<int>())) .Returns(false); order.Fill(warehouseMock.Object); //-- Assert ---------------------- Assert.IsFalse(order.isFilled()); warehouseMock.Verify(x => x.FillIt(It.IsAny<string>(), It.IsAny<int>()), Times.Exactly(1)); } } } 的实例名为Scanner,但用作kbd1

    扫描仪kbd1 =新扫描仪(System.in);

  2. //使用like scientist = scan.next();

    //使用

    scan
    1. String greatIdea; //字符串变量 //输入为int

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

    2. 在Document类

    3. private int greatIdea; //必须是String

      多数,你很高兴。

      PS:抱歉格式不正确