Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用唯一的用户输入填充数组_Java_Arrays_Duplicate Removal - Fatal编程技术网

Java 使用唯一的用户输入填充数组

Java 使用唯一的用户输入填充数组,java,arrays,duplicate-removal,Java,Arrays,Duplicate Removal,我有一个定义如下的类: 在这个类中,我有一个菜单,用户可以在其中添加新车。当他们选择此选项时,系统将提示他们以下内容: 公共级租车系统{ private static final Car[] carList = new Car[100]; private static int carCount = 0; System.out.print("Enter car ID: "); String carID = sc.nextLine(); System.out.print("E

我有一个定义如下的类: 在这个类中,我有一个菜单,用户可以在其中添加新车。当他们选择此选项时,系统将提示他们以下内容: 公共级租车系统{

  private static final Car[] carList = new Car[100];

  private static int carCount = 0;

  System.out.print("Enter car ID: ");
  String carID = sc.nextLine();
  System.out.print("Enter car description: ");
  String cardescription = sc.nextLine();
  System.out.print("Enter hire fee: $");
  Double hireFee = sc.nextDouble();
  sc.nextLine();
  carList[carCount] = new Car(carID,carDescription,hireFee);
  carCount++; 

我想要一种方法来验证输入到数组中的汽车ID是否尚未由用户输入,如果已输入,则打印一条错误消息并返回主菜单。数组最初是空的。如何使用布尔值或do-while循环进行此操作。

首先-依赖用户输入来获得唯一ID是一种糟糕的做法如果可能的话,你应该避免

如果您必须坚持从用户那里获取ID,我建议您切换用于存储汽车的结构。您可以使用地图。ID是钥匙,汽车是值。您可以很容易地检查是否已经有一辆具有此ID的汽车:
cars.get(ID)=null


正如建议的那样,您也可以使用
Set
。为此,您应该覆盖
Car
中检查两辆车是否具有相同id的
equals()
方法。然后,您应该相应地覆盖
hashCode()
方法。如果您这样做,
add()当您尝试添加具有现有id的汽车时,
将返回false。

而不是此行:
carList[carCount]=新车(carID、carDescription、hireFee);

您可以这样调用setter方法:
setCar(carCount、ID、desc、price);

现在,您的set方法可以处理验证:

public void setCar(int index, int id, String desc, doublefee )
{
    for(Car car : carList)
    {
        if(car.getID() == id)
        {//error message
            return;
        }
    }
     carList[index] = new Car(id, desc, fee);
}

您需要做的是:将对象类的hashCode()和equals()重写到您的类中,以检查重复的对象

  • 使用常规过程重写hashCode(),即将Hirefee变量转换为字符串类型,并从该引用调用hashCode(),并将其存储为整数类型。类似地,对其余两个属性执行此操作,但不需要转换为字符串类型。将三个属性相加并返回该和
  • 现在,按属性定义equals(),即在您的示例中,您至少需要4次比较:3次比较属性,1次检查instanceOf运算符
  • 现在,在main()中,创建HashSet()的一个实例。call set.add(new car(carId,carDescription,Hirefee))。因为它是第一个实例,所以只有hashCode()可以将由HashSet隐式调用,HashSet返回哈希数并在集合中获取存储。类似地,添加另一个具有不同内容的实例。现在一个实例已存储在集合中,因此它将比较第二个实例与前一个实例的哈希数。如果数字相同,则将equals()作为hashCode()调用在检查对象内容时不是100%准确,因为它返回的是散列数之和。现在,equals()将检查每个属性,如果所有属性都匹配,则返回“true”,并且该实例未添加到集合中。同样,您可以选择任意数量的实例

惯用解决方案:
设置
列表
映射
都可以非常轻松地检查重复的对象。它们都有各自的优点和缺点,可以使其适用于不同的任务

原始数组极难使用,需要大量脆弱的代码,并且充满了
null
s,它们只是在所有地方添加了更多的噪声检查
!=null
,并且容易出现一次性错误,产生
索引自动边界概念
到已经有噪声的代码,以处理基于索引的数据访问原始数组

import com.google.common.base.Joiner;
导入javax.annotation.Nonnull;
导入java.io.PrintStream;
导入java.util.*;
导入静态java.lang.String.format;
公共类Q32106461
{
公共静态级轿车
{
私有最终字符串id;
私有最终字符串描述;
私人最终双倍收费;
公共汽车(@Nonnull final String id、@Nonnull final String description、@Nonnull final Double fee)
{
this.id=id;this.description=description;this.fee=fee;
}
@凌驾
公共布尔等于(最终对象o)
{
如果(this==o){return true;}
如果(o==null | | getClass()!=o.getClass()){return false;}
final Car=(Car)o;返回Objects.equals(this.id,Car.id);
}
@凌驾
公共字符串toString(){return format(“Car{id='%s',description='%s',fee=%s}”,id,description,fee);}
@凌驾
public int hashCode(){返回this.id.hashCode();}
}
公共静态void main(最终字符串[]args)
{
最终比较器carc=新比较器(){
@凌驾
public int compare(@Nonnull final Car o1,@Nonnull final Car o2){返回o1.id.compareTo(o2.id);}
};
最终集cars=新树集(carc);//排序集实现
最终列表卡尔=新阵列列表(100);
最终映射carm=新哈希映射(100);
最终汽车[]卡拉=新车[100];//不惜一切代价避免使用原始阵列
最终扫描仪ssi=新扫描仪(System.in);
最终打印流os=System.out;
while(true)
{
最终字符串id=getNextString(“输入车辆id:”,os,ssi);
最终字符串描述=getNextString(“输入汽车描述:”,os,ssi);
最终双倍费用=getNextDouble(“输入租用费$”,操作系统,ssi);
最终车辆c=新车(id、说明、费用);
如果(!cars.add(c)){os.println(格式(“%s已存在于集合中!”,c.id));}//重复项将被忽略
如果(carl.contains(c)){os.println(格式(“%s已存在于列表中!”,c.id));}
else{carl.add(c);}//随着列表的增长,查找会变得昂贵
if(carm.containsKey(c.id)){os.println(格式(“%s已存在于映射中!”,c.id));}
else{carm.put(c.id,c);}//键是未排序的集
///*unco
  /* --- Outline of hashCode() as explained above--- */



  public int hashCode()                                                         

{
String s1 = Double.toString(hireFee);
int hash = s1.hashCode();
hash += carID.hashCode();
hash += cardescription();
return hash;

}

     /* --- Outline of equals() as explained above --- */

 public boolean equals(Object obj) 
 {

  return (obj instanceOf CarHireSystem 
  &&((CarHireSystem)obj).carID == carID                       
  && ((CarHireSystem)obj).cardescription == cardescription
  &&((CarHireSystem)obj).hireFee == hireFee);   

 }
import com.google.common.base.Joiner;

import javax.annotation.Nonnull;
import java.io.PrintStream;
import java.util.*;

import static java.lang.String.format;

public class Q32106461
{
    public static class Car
    {
        private final String id;
        private final String description;
        private final Double fee;

        public Car(@Nonnull final String id, @Nonnull final String description, @Nonnull final Double fee)
        {
            this.id = id; this.description = description; this.fee = fee;
        }

        @Override
        public boolean equals(final Object o)
        {
            if (this == o) { return true; }
            if (o == null || getClass() != o.getClass()) { return false; }
            final Car car = (Car) o; return Objects.equals(this.id, car.id);
        }

        @Override
        public String toString() { return format("Car{id='%s', description='%s', fee=%s}", id, description, fee); }

        @Override
        public int hashCode() { return this.id.hashCode(); }
    }

    public static void main(final String[] args)
    {
        final Comparator<Car> carc = new Comparator<Car>() {
            @Override
            public int compare(@Nonnull final Car o1, @Nonnull final Car o2) { return o1.id.compareTo(o2.id); }
        };
        final Set<Car> cars = new TreeSet<Car>(carc); // sorted set implementation
        final List<Car> carl = new ArrayList<>(100);
        final Map<String,Car> carm = new HashMap<>(100);
        final Car[] cara = new Car[100]; // avoid raw arrays at all costs

        final Scanner ssi = new Scanner(System.in);
        final PrintStream os = System.out;

        while(true)
        {
            final String id = getNextString("Enter a car ID: ", os, ssi);
            final String description = getNextString("Enter a car description: ", os, ssi);
            final Double fee = getNextDouble("Enter hire fee $ ", os, ssi);
            final Car c = new Car(id, description, fee);
            if (!cars.add(c)) { os.println(format("%s already exists in the set!", c.id)); } // duplicates will be ignored
            if (carl.contains(c)) { os.println(format("%s already exists in the list!", c.id)); }
            else { carl.add(c); } // lookups get expensive as the list grows
            if (carm.containsKey(c.id)) { os.println(format("%s already exists in the map!", c.id)); }
            else { carm.put(c.id, c); } // keys are an unsorted set
            // /* uncomment out the following to see why raw arrays and nulls should be avoided always */
            //if (cara.length > 0) { Arrays.sort(cara, carc); }
            //final int pos = Arrays.binarySearch(cara,c);
            //if (pos == 0) { cara[0] = c; }
            os.print("Continue? [Y/N]");
            if ("n".equalsIgnoreCase(ssi.next())) { break; }
        }
        System.out.println("cars = " + Joiner.on(',').join(cars));
        System.out.println("carl = " + Joiner.on(',').join(carl));
        System.out.println("carm = " + Joiner.on(',').withKeyValueSeparator(":").join(carm));
    }

    private static String getNextString(@Nonnull final String prompt, @Nonnull final PrintStream ps, @Nonnull final Scanner scanner)
    {
        ps.print(prompt);
        if (scanner.hasNext()) { return scanner.next(); }
        else { return ""; }
    }

    private static Double getNextDouble(@Nonnull final String prompt, @Nonnull final PrintStream ps, @Nonnull final Scanner scanner)
    {
        ps.print(prompt);
        if (scanner.hasNext()) { return scanner.nextDouble(); }
        else { return Double.NaN; }
    }
}