【发布时间】:2015-04-29 19:51:04
【问题描述】:
我正在创建一个室友账单拆分程序,但不知道我做错了什么。在询问室友的名字后,它被挂断了。输出在代码下方。
package roomBillSplit;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Roommate Bill Splitter!\n");
//Get Residence Name from User
System.out.print("Please Enter Name of Place or Address: ");
String place = input.nextLine();
roommates(place);
bills(place);
input.close();
}
public static void roommates(String place) {
int numRoom, i;
Scanner input = new Scanner(System.in);
//Get # of Roommates at Residence
System.out.print("How Many Total People Reside at " + place + ": ");
numRoom = input.nextInt();
String[] roommates = new String[numRoom];
//ArrayList<String> roommates = new ArrayList<String>(5);
//Get Names of Roommates
for(i = 0; i < roommates.length; i++) {
System.out.print("What is Person Number " + (i + 1) + "'s Name: ");
if(input.hasNext()) {
roommates[i] = input.nextLine();
input.next();
}
}
for(i = 0; i < roommates.length; i++) {
System.out.println(roommates[i]);
}
input.close();
}
}
public static void bills(String place) {
int numBills, i;
Scanner input = new Scanner(System.in);
//Get # of Bills Split Between Roommates
System.out.print("What is the Total Number of Bills to be Split at " + place + ": ");
numBills = input.nextInt();
String[] bills = new String[numBills];
//Get Names of Bills
for(i = 0; i < bills.length; i++) {
System.out.print("Please List Bill Number " + (i + 1) + ": ");
if(input.hasNext()) {
bills[i] = input.nextLine();
input.next();
}
}
for(i = 0; i < bills.length; i++) {
System.out.println(bills[i]);
}
int amount[] = new int[numBills];
//Get Amount of Each Bill
for(i = 0; i < bills.length; i++) {
System.out.print("What is the Total Amount of the " + bills[i] + " Bill: $");
if(input.hasNextInt()) {
amount[i] = input.nextInt();
input.next();
}
}
input.close();
for(i = 0; i < amount.length; i++) {
System.out.print(bills[i]);
System.out.print("\t$");
System.out.println(amount[i]);
}
}
}
输出:
欢迎来到室友 Bill Splitter!
请输入地名或地址:1212 Main
1212 Main 共有多少人居住:2
第 1 个人的名字是什么:a
第 2 个人的名字是什么:b
线程“主”java.util.NoSuchElementException 中的异常
在 java.util.Scanner.throwFor(Unknown Source)
在 java.util.Scanner.next(未知来源)
在 java.util.Scanner.nextInt(Unknown Source)
在 java.util.Scanner.nextInt(Unknown Source)
在 roomBillSplit.Main.bills(Main.java:62)
在 roomBillSplit.Main.main(Main.java:19)
在 1212 Main 要拆分的票据总数是多少:
【问题讨论】:
-
不要关闭
Scanner -
好的,我被告知我需要关闭扫描仪,但它现在似乎可以工作,直到我到达要求我输入账单金额的部分。然后它似乎经历了无限循环或其他东西。请输入地名或地址:1212 1212 的总人数:2 第 1 个人的姓名是什么:g 第 2 个人的姓名是什么:d 1212 要拆分的账单总数是多少:3 请列出帐单编号 1:租金 请列出帐单编号 2:ele 请列出帐单编号 3:电缆 帐单的总金额是多少:$200
-
此外,您正在检查一个字符串标记,然后拉出整行和另一个标记。我希望当您尝试未选中的
nextList()或next()时根本没有数据。
标签: java