你好,我正在尝试写代码,以关键字搜索parralele数组,我有2个数组
String[] beerNames = new String[10]; //define berrNames array
Double[] beerStrengths = new Double[10]; //define beerStrengths array
beerNames[0] = "Heineken"; //fill the arrays
beerNames[1] = "Bud Light";
beerNames[2] = "Coors Light";
beerNames[3] = "Leffe Blonde";
beerNames[4] = "Budweiser";
beerNames[5] = "Erdinger Non-Alcoholic";
beerNames[6] = "Bud Premier Select";
beerNames[7] = "Corona";
beerNames[8] = "Barefoot Bohemian";
beerNames[9] = "3 Monts";
beerStrengths[0] = 4.0;
beerStrengths[1] = 4.2;
beerStrengths[2] = 4.3;
beerStrengths[3] = 6.6;
beerStrengths[4] = 5.0;
beerStrengths[5] = 0.0;
beerStrengths[6] = 7.4;
beerStrengths[7] = 4.6;
beerStrengths[8] = 4.0;
beerStrengths[9] = 8.5; //fill the arrays我希望能够通过关键字进行搜索,因此如果我输入bud,我将返回以下结果
百威啤酒的酒精含量为5.0%
遗憾的是,我不知道该怎么做,我一直在看我在搜索文件时获得的一些代码扫描仪控制台=新扫描仪(System.in);System.out.print(“搜索短语:");字符串搜索= console.nextLine().toLowerCase();
Scanner input = new Scanner(new File("imdb.txt"));
// 1 9.1 243153 The Godfather (1972)
while (input.hasNextLine()) {
String line = input.nextLine();
if (line.toLowerCase().contains(search)) {
//System.out.println(line);
displayMovieInfo(line);
}
}
}
public static void displayMovieInfo(String line) {
Scanner lineScan = new Scanner(line);
int rank = lineScan.nextInt();
double rating = lineScan.nextDouble();
lineScan.nextInt();
String title = "";
while (lineScan.hasNext()) {
title = title + lineScan.next() + " ";
}
System.out.println(rank + "\t" + rating + "\t" + title);
}但是我不知道如何转换这段代码,如果有任何帮助,我将不胜感激
发布于 2014-03-31 06:33:55
如果你知道第一个数组的数组索引,你就知道第二个数组的索引。这听起来也像是创建一个具有两个属性的对象的候选者:
public class BeerStrength {
private final String name;
private final int strengthNum;
public BeerStrength(String name, int strength_num) {
this.name = name;
strengthNum = strength_num;
}
public String getName() {
return name;
}
public int getStrength() {
return strengthNum;
}
}然后您有一个BeerStrength数组,这将使您的并行数组问题变得毫无意义。
发布于 2014-03-31 06:34:49
不用两个数组,只需使用HashMap即可。使用字符串作为键,使用双精度作为值。这样你就可以遍历这些键并返回值。您将极大地减少代码,并且只使用一种数据结构。
发布于 2014-03-31 06:36:45
我要做的第一件事,就是改变你的方法。如果您发现自己在处理多个数组,那么通常有一种不同的方法可以采用。例如,您可以创建一个值为name和volume的Beer类。
public class Beer
{
private String name;
private double volume;
public Beer(String name, double volume)
{
this.name = name;
this.volume = volume;
}
public boolean equals(Object o) {
if(o instanceof Beer) {
Beer beer = (Beer)o;
if(this.name.equals(beer.getName())) {
return true;
}
}
return false;
}
public String getName() {return this.name; }
public double getVolume() {return this.volume; }
}然后,您可以通过将它们放在List中来创建一组Beer对象。
private List<Beer> beers;在填充时,您需要做一些类似于..
beers = new ArrayList<Beer>();
beers.add(new Beer("Budweiser", 5));
// Etc..现在,您可以自由地接受输入,并研究如何进行搜索:)
https://stackoverflow.com/questions/22750735
复制相似问题