2016-05-21 3 views
1

У меня есть метод getOrderDetails(), но когда я вхожу («Компас», 2000, 20), я не могу заставить его отображать сообщение об ошибке, которое должно пройти. * Количество ошибок должно быть меньше, чем 1000" Когда я запускаю программу, он будет рассчитывать на 2000 вместо отображения сообщения об ошибкеНе удается получить сообщение для отображения

public String getOrderDetails(){ 
 
     message = message; 
 
     if(isValidOrder == true && isDiscounted == false){ 
 
      message = "Order Number: " + orderNum + "\n" + "Product Name: " + productName + "\n" + "Product Price: $" + price + "\n" + "Order Quantity: " + quantity + "\n" + "Total Price: $" + total; 
 
     } 
 
     else if(isValidOrder == true && isDiscounted == true){ 
 
      message = "Order Number: " + orderNum + "\n" + "Product Name: " + productName + "\n" + "Product Price: $" + price + "\n" + "Order Quantity: " + quantity + "\n" +"Discount : " + discount + "%" + "\n" + "Total Price: $" + total; 
 
     } 
 
     else { 
 
      return message; 
 
     } 
 
    return message; 
 
}

Это код сообщения:..

public void testQuantity(int quantity){ 
 
      boolean isValidOrder = true; 
 
      if (this.quantity <= minQuantity) { 
 
       message = "**ERROR**: Invalid quantity. Quantity cannot be 0 or less"; 
 
       isValidOrder = false; 
 
      } 
 
      else if (this.quantity > maxQuantity) { 
 
       message = "**ERROR**: Invalid quantity. Quantity cannot be greater than 1000"; 
 
       isValidOrder = false; 
 
      } 
 
      else { 
 
       this.quantity = quantity; 
 
       this.isValidOrder = true; 
 
      } 
 
    } 
 

 
    public void testDiscount (int discount) { 
 
      boolean isDiscounted = false; 
 
      if (this.discount <= minDiscount) { 
 
       message = "**ERROR**: The discount rate cannot be lower than or equal to 0"; 
 
       } 
 
      else if (this.discount > maxDiscount) { 
 
       message = "**ERROR**: The discount rate cannot be greater than 50"; 
 
       } 
 
      else { 
 
       this.discount = discount; 
 
       this.isDiscounted = true; 
 
       } 
 
    }

Это остальная часть моего кода:

/* 
 
* To change this license header, choose License Headers in Project Properties. 
 
* To change this template file, choose Tools | Templates 
 
* and open the template in the editor. 
 
*/ 
 
package order; 
 
import java.util.Arrays; 
 
/** 
 
* 
 
* @author Alexander 
 
*/ 
 
public class Order { 
 
    private static String[] products = {"Compass", "Eraser", "Pen", "Pencil","Pencil Case", "Pencil Sharpener", "Ruler", "Scissors"}; 
 
    private static double[] prices = {4.5, 0.5, 0.3, 0.6, 10, 0.3, 1.2, 2.5}; 
 
    public static int orderNum = 0; // 
 
    private String productName ; 
 
    private double price = 0; 
 
    private int discount = 0; 
 
    private final int minDiscount = 0; 
 
    private final int maxDiscount = 50; 
 
    private int quantity = 0; 
 
    private final int minQuantity = 0; 
 
    private final int maxQuantity = 1000; 
 
    private double total; 
 
    private String message; 
 
    private boolean isDiscounted = false; 
 
    private boolean isValidOrder = true; 
 
    
 
    public void calculate(){ 
 
      if (isDiscounted == true){ 
 
       total = quantity * price - quantity * price * (discount/100.0); 
 
       System.out.println(total); 
 
      } 
 
     else { 
 
       total = quantity * price; 
 
       System.out.println(total); 
 
       } 
 
     } 
 
    
 
     
 
    public Order(){ 
 
     isValidOrder = false; 
 
     message = "**ERROR** : Order number cannot be totalled as no details have been supplied."; 
 
     orderNum++; 
 
     } 
 
    
 
    public Order (String productName, int quantity) { 
 
     orderNum++; 
 
     this.quantity = quantity; 
 
      this.productName = productName; 
 
      testQuantity(quantity); 
 
      getPrice(productName); 
 
      if (isValidOrder == true){ 
 
       calculate(); 
 
      } 
 
      } 
 
    
 
    public Order (String productName, int quantity, int discount) { 
 
     orderNum++; 
 
     this.productName = productName; 
 
     this.quantity = quantity; 
 
     this.discount = discount; 
 
     testQuantity(quantity); 
 
     testDiscount(discount); 
 
     getPrice(productName); 
 
     if (isValidOrder != false){ 
 
       calculate(); 
 
      } 
 
     } 
 

 

 

 
    private void getPrice(String pce) { 
 
      Arrays.sort(products); 
 
      int searchProductArray = Arrays.binarySearch(products, pce); 
 
      if (searchProductArray >= 0) { 
 
      price = prices[searchProductArray]; 
 
      productName = products [searchProductArray]; 
 
      isValidOrder = true; 
 
      } 
 
      else { 
 
      price = 0.0; 
 
      isValidOrder = false; 
 
      message = "**ERROR**: Invalid product name"; 
 
      } 
 
     } 
 
    
 
    
 
     
 
    
 
    public void testQuantity(int quantity){ 
 
      boolean isValidOrder = true; 
 
      if (this.quantity <= minQuantity) { 
 
       message = "**ERROR**: Invalid quantity. Quantity cannot be 0 or less"; 
 
       isValidOrder = false; 
 
      } 
 
      else if (this.quantity > maxQuantity) { 
 
       message = "**ERROR**: Invalid quantity. Quantity cannot be greater than 1000"; 
 
       isValidOrder = false; 
 
      } 
 
      else { 
 
       this.quantity = quantity; 
 
       this.isValidOrder = true; 
 
      } 
 
    } 
 

 
    public void testDiscount (int discount) { 
 
      boolean isDiscounted = false; 
 
      if (this.discount <= minDiscount) { 
 
       message = "**ERROR**: The discount rate cannot be lower than or equal to 0"; 
 
       } 
 
      else if (this.discount > maxDiscount) { 
 
       message = "**ERROR**: The discount rate cannot be greater than 50"; 
 
       } 
 
      else { 
 
       this.discount = discount; 
 
       this.isDiscounted = true; 
 
       } 
 
    } 
 
     
 
    public String getOrderDetails(){ 
 
     message = message; 
 
     if(isValidOrder == true && isDiscounted == false){ 
 
      message = "Order Number: " + orderNum + "\n" + "Product Name: " + productName + "\n" + "Product Price: $" + price + "\n" + "Order Quantity: " + quantity + "\n" + "Total Price: $" + total; 
 
     } 
 
     else if(isValidOrder == true && isDiscounted == true){ 
 
      message = "Order Number: " + orderNum + "\n" + "Product Name: " + productName + "\n" + "Product Price: $" + price + "\n" + "Order Quantity: " + quantity + "\n" +"Discount : " + discount + "%" + "\n" + "Total Price: $" + total; 
 
     } 
 
     else { 
 
      return message; 
 
     } 
 
    return message; 
 
} 
 
     
 
    /** 
 
    * @param args the command line arguments 
 
    */ 
 
    public static void main(String[] args) { 
 
     Order O1 = new Order("Compass" , 2000, 30); 
 
     System.out.println(O1.getOrderDetails()); 
 
     
 
     OrderLaunch frame = new OrderLaunch(); 
 
     frame.setVisible(true); 
 
    }  
 
} 
 

 

ответ

0

Ваш код имеет несколько вопросов:

1) Метод testQuantity создает локальную isValidOrder логическое и, таким образом, заслоняя член isValidOrder логическое значение.

Пример:

public void testQuantity(int quantity){ 
     // ---------------------- 
     // Remove this boolean here... 
     // boolean isValidOrder = true; 
     // ---------------------- 
     if (this.quantity <= minQuantity) { 
      message = "**ERROR**: Invalid quantity. Quantity cannot be 0 or less"; 
      isValidOrder = false; 
     } 
     else if (this.quantity > maxQuantity) { 
      message = "**ERROR**: Invalid quantity. Quantity cannot be greater than 1000"; 
      isValidOrder = false; 
     } 
     else { 
      this.quantity = quantity; 
      this.isValidOrder = true; 
     } 
} 

2) После установки члена isValidOrder логического значения лжи в testQuantity метода вы устанавливаете его обратно к истине в методе getPrice.

Пример:

private void getPrice(String pce) { 
     Arrays.sort(products); 
     int searchProductArray = Arrays.binarySearch(products, pce); 
     if (searchProductArray >= 0) { 
     price = prices[searchProductArray]; 
     productName = products [searchProductArray]; 

     // ---------------------- 
     // Comment this boolean here for now until you figure things out 
     // isValidOrder = true; 
     // ---------------------- 
     } 
     else { 
     price = 0.0; 
     isValidOrder = false; 
     message = "**ERROR**: Invalid product name"; 
     } 
    } 

Если исправить эти 2 вопроса, то эти вызовы будут давать вам требуемый выход

Order O1 = new Order("Compass" , 2000, 30); 
System.out.println(O1.getOrderDetails()); 

ОШИБКА: Invalid количество. Количество не может быть больше 1000

+0

Но мне нужно, чтобы получить сообщение для отображения при получении getOrderDetails() вместо того, чтобы его как отдельное сообщение –

+0

Я обновил свой ответ. Взгляни, пожалуйста. –

0

Вы используете переменную isValidOrder, чтобы проверить, не запускать ли расчет или нет. Причина, по которой все еще вычисляется с недопустимым значением количества, заключается в том, что ваш параметр isValidOrder равен true в вашем методе getPrice после того, как в вашем количественном тесте было установлено значение false.

0

в вашем коде метод private void getPrice (String pce), устанавливающий isValidOrder = true; что неправильно. Комментарий что линия & это будет ковшики отлично :)

private void getPrice(String pce) { 
     Arrays.sort(products); 
     int searchProductArray = Arrays.binarySearch(products, pce); 
     if (searchProductArray >= 0) { 
     price = prices[searchProductArray]; 
     productName = products [searchProductArray]; 
     // isValidOrder = true; 
     } 
     else { 
     price = 0.0; 
     isValidOrder = false; 
     message = "**ERROR**: Invalid product name"; 
     } 
    } 
Смежные вопросы