0
我的主程序用菜刀補充資金
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小時。
每當你打電話給nextInt時 - 返回新號碼 –
另外,你不想在你的'toString()'方法中調用'getAmount()'。這會導致每次打印實例時不得不分析「線路」。調用'getAmount()'一次;將值存儲在成員變量中;在'toString()'中使用該成員變量。 –