该程序将输出用户可能输入的特定点之间的距离。但是,我在设置扫描仪时遇到了麻烦,因为它从另一个文本文件读取输入。这是我的代码:
public class junior
{
public static void main(String[] args)throws IOException
{
double avgMPG;
double pricePer;
double speed;
String letter1;
String letter2;
int start = 0;
int end=0;
int distance;
Scanner inData = new Scanner(new File("input.txt"));
boolean repeat=false;
while (inData.hasNext())
{
letter1.inData.next();
letter2.inData.next();
while (!repeat)
{
System.out.print("1.");
letter1=inData.next();
if(letter1.equals("A"))
{
start=0;
repeat=true;
}
else if (letter1.equals("B"))
{
start=450;
repeat=true;
}
else if (letter1.equals("C"))
{
start=590;
repeat=true;
}
else if (letter1.equals("D"))
{
start=710;
repeat=true;
}
else if(letter1.equals("E"))
{
start=1030;
repeat=true;
}
else if (letter1.equals("F"))
{
start=1280;
repeat=true;
}
else if (letter1.equals("G"))
{
start=1360;
repeat=true;
}
else
{
System.out.println("ERROR: You didn't enter a valid character. Please try again");
repeat=false;
}
}
repeat=false;
while (!repeat)
{
if(letter2.equals("A"))
{
end=0;
repeat=true;
}
else if (letter2.equals("B"))
{
end=450;
repeat=true;
}
else if (letter2.equals("C"))
{
end=590;
repeat=true;
}
else if (letter2.equals("D"))
{
end=710;
repeat=true;
}
else if(letter2.equals("E"))
{
end=1030;
repeat=true;
}
else if (letter2.equals("F"))
{
end=1280;
repeat=true;
}
else if (letter2.equals("G"))
{
end=1360;
repeat=true;
}
else
{
System.out.println("ERROR: You didn't enter a valid character. Please try again");
repeat=false;
}
distance=end-start;
System.out.print("Total distance: "+distance);
}
}
}
}
那部分说“ inData.next”不断发送错误,指出该字段不存在或无法解析。如何解决此问题以正确读取测试文件?
最佳答案
好像在这里
letter1.inData.next();
letter2.inData.next();
您正在尝试从扫描仪读取数据并将结果放入您的
String
变量中。但是要做到这一点,你想要letter1 = inData.next();
letter2 = inData.next();
编译器抱怨是因为您试图访问
String
变量中称为inData
的字段(这就是letter1.inData
的意思),但是它们没有这样的字段。