我有以下代码,显示每个客户的停车票。
我需要创建一个for或while循环,显示停车票9次,允许用户输入不同的客户名称,每个循环中停放的rego号码和小时数。我不确定该怎么做。
package week3;
import java.util.Scanner;
public class Week3
{
static final double costPerHour = 4.25;
public static void main(String[] args)
{
String customerName;
String customerNumberPlate;
int hoursParked;
double parkingFee;
Scanner inText = new Scanner(System.in); //Create scanner object
Scanner inNumber = new Scanner(System.in); //Create scanner object
System.out.print("Please enter name of customer >>> "); //Prompt asking user for name
customerName = inText.nextLine(); //Declare string object
System.out.print("Please enter number plate of " + customerName +"'s vehicle >>> "); //Prompt asking for user number plate
customerNumberPlate = inText.nextLine();
System.out.print("Please enter hours customer parked >>> ");
hoursParked = inNumber.nextInt();
if(hoursParked > 0 && hoursParked <=1) //Set boundaries
parkingFee = 4.25;
else
if (hoursParked > 1 && hoursParked <= 6)
parkingFee = (3.50 * hoursParked);
else
parkingFee = (2.75 * hoursParked);
System.out.println("\n" + "--------Receipt--------" + "\n"
+ "Customer: " + customerName + "\n"
+ "Number Plate >>> " + customerNumberPlate + "\n"
+ "Hours Parked >>> " + hoursParked + "\n"
+ "Parking Fee >>> " + parkingFee);
}
}
答案 0 :(得分:0)
for
,while
或do ... while
来获取结果。在下面的例子中,我使用循环for
。可能是你可以改变循环的类型。Scanner
个对象。一个目标是充足和实际的。在这里,我将其命名为Scanner input = new Scanner(System.in)
,在每个循环结束时,您需要使用此代码input.nextLine()
清理实际输入行(请参阅下面的代码)。try ... catch
块来处理此错误。在循环的情况下:
int counter = 0;
while (counter < 9) {
/* your actual code */
counter++;
}
在循环的情况下执行... while:
int counter = 0;
do {
/* your actual code */
counter++;
} while (counter < 9);
对于循环的情况: (此处代码更完整)
package week3;
import java.util.Scanner;
public class Week3
{
static final double costPerHour = 4.25;
public static void main(String[] args)
{
String customerName;
String customerNumberPlate;
int hoursParked;
double parkingFee;
Scanner input = new Scanner(System.in);
for (int i = 0; i < 9; i++) {
System.out.print("Please enter name of customer >>> "); //Prompt asking user for name
customerName = input.nextLine(); //Declare string object
System.out.print("Please enter number plate of " + customerName +"'s vehicle >>> "); //Prompt asking for user number plate
customerNumberPlate = input.nextLine();
System.out.print("Please enter hours customer parked >>> ");
hoursParked = input.nextInt();
if(hoursParked > 0 && hoursParked <=1) //Set boundaries
parkingFee = 4.25;
else
if (hoursParked > 1 && hoursParked <= 6)
parkingFee = (3.50 * hoursParked);
else
parkingFee = (2.75 * hoursParked);
System.out.println("\n" + "--------Receipt--------" + "\n"
+ "Customer: " + customerName + "\n"
+ "Number Plate >>> " + customerNumberPlate + "\n"
+ "Hours Parked >>> " + hoursParked + "\n"
+ "Parking Fee >>> " + parkingFee);
System.out.println("");
input.nextLine(); // important: to clean the actual line
}
}
}