public static void main(String[] args) throws Exception{
String fileLocation = System.getProperty("user.dir");
String dataPath = fileLocation + File.separator + "predators.txt";
java.io.File file = new java.io.File(dataPath);
Scanner input = new Scanner(file);
input.useDelimiter(":");
String predatorsName, latinName, weight, speed, stealth, risk, killer, interestingFact;
for (int i = 0; input.hasNext(); i++) {
predatorsName = input.next();
latinName = input.next();
weight = input.next();
speed = input.next();
stealth = input.next();
risk = input.next();
killer = input.next();
interestingFact = input.nextLine();
System.out.println(weight);
}
}
嗨,我这里有一个程序,它扫描一个文件,将多个关于动物的数据,然后使用 input.next() 将每个单词/数字分配给相应的字符串。现在,当我打印重量时,所有动物的重量都会打印在输出中。我想知道是否有办法...说例如在第三行打印动物的重量?谢谢你
为什么它不起作用
它打印出所有权重的原因是因为在循环中你有这个:
for (int i = 0; input.hasNext(); i++) {
...
weight = input.next();
...
System.out.println(weight);
}
这意味着在循环的每次迭代中,它会先存储权重,然后显示它。因此,每个重量都将在输出中打印出来。
解决方案
我将创建一个Predator
类,而不是在循环中显示权重(根据您当前的实现),我们将使用它来将数据填充到 Predators 列表中。我们只会在完成后显示它们。
创建 Predator 类:
class Predator{
String predatorName;
String latinName;
String weight;
..
//add your getters and setters as well
}
然后使用它:
public static void main(String[] args) throws Exception{
List<Predator> predatorList = new ArrayList();
String fileLocation = System.getProperty("user.dir");
String dataPath = fileLocation + File.separator + "predators.txt";
java.io.File file = new java.io.File(dataPath);
Scanner input = new Scanner(file);
input.useDelimiter(":");
List<Predator> predatorList = new ArrayList();
Predator predator = new Predator();
for (int i = 0; input.hasNext(); i++) {
predator.setPredatorName(input.next());
predator.setLatinName(input.next()));
...
predatorList.add(predator);
}
}
最后检索列表中的不同捕食者非常简单:
Predator myPredator = predatorList.get(0); //which returns you the first predator in the list.
System.out.println(myPredator.getWeight()); // this will only print out the weight of the first predator
在上面的例子中,我predator
在循环中重复使用了相同的变量。如果您愿意,您当然可以Predator
在循环的每次迭代中创建一个新实例,但这意味着您实际上是在每次迭代中创建一个新对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句