這個程序提示商店所有者在一天的開始和結束時的現金數量以及文件的名稱。它應該檢查一天結束時的實際現金量是否等於預期值。掃描儀輸入未定義爲字符串? JAVA
我有一個txt文件,其中每行包含三個項目:發票號碼,現金金額和字母P如果支付金額或R如果收到。項目由空格分隔。
我有我的代碼
while (filename.hasNext()) {
invoice.add(filename.nextInt());
cash.add(filename.nextDouble());
PR.add(filename.next());
}
這片麻煩它是一個語法錯誤,說我不能使用.nextInt() .nextDouble() .next() hasNext()
下面是完整的源代碼:
import java.io.*;
import java.util.*;
/**
* Code for P11.11. This program takes in a list of baby names and outputs a list of boys and
* girls names.
*
* @Michael Goedken
*/
public class BalanceTransactions {
public static void main(String[] args) throws FileNotFoundException {
// The following lines ask the user to enter the file name and the balances at the beginning and the end
Scanner in = new Scanner(System.in);
System.out.print("Please enter the file name for input: ");
String filename = in.next();
System.out.print("Please enter the cash amount at the start: ");
double start = in.nextDouble();
System.out.print("Please enter the cash amount at the end: ");
double end = in.nextDouble();
ArrayList<Integer> invoice = new ArrayList<Integer>();
ArrayList<Double> cash = new ArrayList<Double>();
ArrayList<String> PR = new ArrayList<String>();
while (filename.hasNext()) {
invoice.add(filename.nextInt());
cash.add(filename.nextDouble());
PR.add(filename.next());
}
for (int i = 0; i < invoice.size(); i++) {
if (PR.get(i).equals("P")) {
start -= cash.get(i);
}
if (PR.get(i).equals("R")) {
start += cash.get(i);
}
}
if (start == end || (double) Math.round(start * 1000000000)/1000000000 == end) {
System.out.println("There is the correct amount in the register.");
} else {
Double difference = ((double) Math.round(start * 100000)/100000) - end;
System.out.println("You are off by: " + difference);
}
}
}
編輯:我現在增加了一個新的掃描儀,我得到這個錯誤
Scanner fileScanner = new Scanner("/Users/MichaelGoedken/Desktop/transactions.txt");
while (fileScanner.hasNext())
{
invoice.add(fileScanner.nextInt());
cash.add(fileScanner.nextDouble());
PR.add(fileScanner.next());
}
錯誤:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
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 BalanceTransactions.main(BalanceTransactions.java:34)
你認爲'filename.nextInt()'應該做什麼?你爲什麼這麼認爲? –
因爲''filename''是一個''String''變量。這些方法由一個''Scanner''實例提供,在你的代碼中這個變量被稱爲''in''。 – f1sh
@SotiriosDelimanolis我希望它會填充文本文件中的整數數組列表 –