import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CarReader2 {
String name, speed, acc;
public CarReader2(String carName, String carSpeed, String carAcc){
name = carName;
speed = carSpeed;
acc = carAcc;
}
public String toString(){
return "Name of car: " +name+ "\nSpeed of car: " +speed+"\nAcceleration of car: " +acc+"\n";
}
public static void main(String[] args) {
File file = new File("carlist.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String c1Name = sc.nextLine();
String c1Speed = sc.nextLine();
String c1Acc = sc.nextLine();
CarReader2 car1 = new CarReader2(c1Name,c1Speed,c1Acc);
car1.speed = c1Speed;
car1.acc = c1Acc;
String c2Name = sc.nextLine();
String c2Speed = sc.nextLine();
String c2Acc = sc.nextLine();
CarReader2 car2 = new CarReader2(c2Name,c1Speed,c1Acc);
car2.speed = c2Speed;
car2.acc = c2Acc;
System.out.println("Information on both cars");
System.out.println("First car:");
System.out.println(car1.toString());
System.out.println("Second car:");
System.out.println(car2.toString());
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
我的代码:
carlist.txt
它应该从名为carlist.txt的文件中读取2辆车的数据,然后以正确的格式打印两辆车的数据。
jonathan 3 7
dio 8 2
是一个包含以下内容的文本文件:
Information on both cars
First car:
Name of car: jonathan
Speed of car: 3
Acceleration of car: 7
Second car:
Name of car: dio
Speed of car: 8
Acceleration of car: 2
该程序应打印出来,
<div class="flexslider-controls">
<ol class="new-nav">
<li>
<div class="medium-3 columns">
<div class="row">
<div class="columns">
<a href="#"><img src="images/slider-thumb-1.jpg" /></a>
</div>
</div>
</div>
</li>
<li>
<div class="medium-3 columns">
<div class="row">
<div class="columns">
<a href="#"><img src="images/slider-thumb-1.jpg" /></a>
</div>
</div>
</div>
</li>
<li>
<div class="medium-3 columns">
<div class="row">
<div class="columns">
<a href="#"><img src="images/slider-thumb-2.jpg" /></a>
</div>
</div>
</div>
</li>
<li>
<div class="medium-3 columns">
<div class="row">
<div class="columns">
<a href="#"><img src="images/slider-thumb-3.jpg" /></a>
</div>
</div>
</div>
</li>
</ol>
</div>
程序编译但没有正确运行并显示我在最顶部发布的错误。
答案 0 :(得分:0)
您正在使用nextLine方法错误。名称,速度和加速度在同一行,但您使用3个nextLine方法来读取它们。当你试图从一个只有2行的文件中读取6行时会发生什么。使用sc.next()
代替sc.nextLine()
。
答案 1 :(得分:0)
你读的太多了。您的文件中只有两行,但您尝试阅读6.您可以将文本文件更改为:
jonathan
3
7
dio
8
2
或者您可以阅读一行并分割出您想要的信息。