我的主要节目
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
import java.lang.Math;
public class Lab13d
{
public static void main( String args[] ) throws IOException
{
Scanner file = new Scanner(new File("C:\\Users\\Will\\Documents\\NetBeansProjects\\CompSci\\src\\compsci\\Lab13d.dat"));
int num = file.nextInt();
file.nextLine();
for(int i = 0; i < num; i++)
{
String line = file.nextLine();
DogFood one = new DogFood(line);
out.println(one);
}
}
}
我的第二个程序与第一个程序相关联。
import java.util.Scanner;
import static java.lang.System.*;
import java.lang.Math;
public class DogFood
{
//Private instance variables
private double amount;
private String Line;
//Default constructor
public DogFood()
{
amount = 0;
Line = "";
}
//Initializer constructor
public DogFood(String line)
{
Line = line;
}
//Method to get the amount of dog food needed
public double getAmount()
{
Scanner chopper = new Scanner(Line);
double cups = 0.0;
while(chopper.hasNextInt())
{
if(chopper.nextInt() >= 2 && chopper.nextInt() <= 4)
{
cups += 3.5;
}
else if(chopper.nextInt() >= 5 && chopper.nextInt() <= 7)
{
cups += 7.0;
}
else if(chopper.nextInt() >= 8 && chopper.nextInt() <= 9)
{
cups += 10.5;
}
else if(chopper.nextInt() >= 10 && chopper.nextInt() <= 19)
{
cups += 14.0;
}
else if(chopper.nextInt() >= 20 && chopper.nextInt() <= 39)
{
cups += 24.5;
}
else if(chopper.nextInt() >= 40 && chopper.nextInt() <= 59)
{
cups += 31.5;
}
else if(chopper.nextInt() >= 60 && chopper.nextInt() <= 79)
{
cups += 42.0;
}
else if(chopper.nextInt() >= 80)
{
cups += 52.5;
}
}
return cups;
}
public String toString()
{
return getAmount() + " - 10 POUND BAGS";
}
}
最后,这是我的.dat文件
8
4 6 8 10 12 14
2 2 3 4 5 6
5 10 15 20 25 30
5 20 35 40 55 60
6 10 14 18 25 32
12 15 20 26 35 42
33 38 45 51 60 65
40 50 60 77 90 101
抱歉格式不佳,我从IDE中复制了这个。我想要做的是使用斩波器确定每个int的重量(从.dat文件的第一行开始,所以在4 6 8行)。我相信我已经失去了,然后根据重量添加一定数量的狗粮。我得到的错误是
run:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at compsci.DogFood.getAmount(DogFood.java:48)
at compsci.DogFood.toString(DogFood.java:74)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at compsci.Lab13d.main(Lab13d.java:26)
C:\Users\Will\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
非常感谢任何帮助!我已经坚持了大约3个小时。
答案 0 :(得分:0)
不是在条件中重复调用chopper.nextInt()
,而是将其分配给局部变量:
int i = chopper.nextInt();
if (i >= 2 && i <= 4) {
// ...
} else if (i >= 5 && i <= 7) {
// ...
}
// etc.
目前,每次进行比较时,您的代码都会从流中消耗int
。最终,它没有用于读取;如果没有恰好是流中可用的15个整数的倍数,它将抛出异常。