我正在与两个班级一起工作。一种称为Validator,一种称为LineItemApp。
这是 Validator 类的代码。
import java.util.Scanner;
public class Validator
{
public String getString(Scanner sc, String prompt)
{
System.out.print(prompt);
String s = sc.next(); // read user entry
sc.nextLine(); // discard any other data entered on the line
return s;
}
public int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public int getInt(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
public double getDouble(Scanner sc, String prompt)
{
double d = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid decimal value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public double getDouble(Scanner sc, String prompt,
double min, double max)
{
double d = 0;
boolean isValid = false;
while (isValid == false)
{
d = getDouble(sc, prompt);
if (d <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (d >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return d;
}
}
这是我的 LineItemApp 类
import java.util.Scanner;
public class LineItemApp
{
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Line Item Calculator");
System.out.println();
// create 1 or more line items
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the input from the user
String productCode = Validator.getString(sc,
"Enter product code: ");
int quantity = Validator.getInt(sc,
"Enter quantity: ", 0, 1000);
// get the Product object
Product product = ProductDB.getProduct(productCode);
// create the LineItem object
LineItem lineItem = new LineItem(product, quantity);
// display the output
System.out.println();
System.out.println("LINE ITEM");
System.out.println("Code: " + product.getCode());
System.out.println("Description: " + product.getDescription());
System.out.println("Price: " + product.getFormattedPrice());
System.out.println("Quantity: " + lineItem.getQuantity());
System.out.println("Total: " +
lineItem.getFormattedTotal() + "\n");
// see if the user wants to continue
choice = Validator.getString(sc, "Continue? (y/n): ");
System.out.println();
}
}
}
任何帮助将不胜感激。
谢谢,大卫