2013-09-16 3 views
-4
  • 두 번째 생성자는 두 개의 매개 변수 인 productName과 수량을받습니다. productName 매개 변수는 클래스의 productName 인스턴스 변수에 지정됩니다. 수량 매개 변수는 testQuantity 메소드로 전달됩니다. 다음에 getPrice 메소드를 호출하면 productName 매개 변수를 전달하여 을 작성해야합니다. 계산 방법은 주문이 유효한 경우에만 호출해야합니다.자바 프로젝트를 시작하는 초보자

  • 세 번째 생성자는 productName, 수량 및 할인의 세 가지 매개 변수를받습니다.
    productName 매개 변수는 클래스의 productName 인스턴스 변수에 지정됩니다. testQuantity, getPrice 및 testDiscount 메서드는 모두 필수 매개 변수를 전달하여 호출해야합니다. 주문이 유효한 경우에만 Calculate 메소드를 호출해야합니다.

이 질문에 대한 답변을 얻고이 코드를 작성했습니다. 내가 그렇게 여전히 많은 학습자도 생각하고 도움

public Order() { 
     isValidOrder = false; 
     message = "**ERROR** Order number cannot be totalled as no details have been supplied."; 
     orderNum++; 
    } 

    public Order(String productName, int quantity){ 
     this.productName = productName; 
     this.quantity = quantity; 
     getPrice(this.productName); 


     if(isValidOrder != false){ 
      calculate(); 
     } 
     orderNum++; 

    } 

public Order(String productName, int quantity, int discount){ 
    this.productName = productName; 
    testQuantity(quantity); 
    getPrice(productName); 

     if(isValidOrder != false){ 
      calculate(); 
     } 
       orderNum++; 
} 

private String getOrderDetails(){ 
    message = message; 
    if(isValidOrder == true && isDiscounted == false){ 

     message = "Order Number: " + quantity + "\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: " + quantity + "\n" + "Product Name; " + productName + "\n" + "Product Price: $" + price + "\n" + "Order Quantity: " + quantity + "\n" + "Total Price: $" + total; 
    } else { 
     return message; 
    } 
    return message; 
} 
+6

어떤 질문이든 잘 모르겠다. –

+0

새 개체를 생성하기 위해 생성자를 호출하는 방법을 알고 싶습니까? – JohnnyAW

+0

이봐, 정말로 당신은 생성자에 대한 자바 튜토리얼을 읽어야한다. 너무 근본적이므로 지금이 사실을 이해하는 것이 중요합니다. 코드에서 필요한 것이 모두 있습니다. 기본 지식 만 있으면됩니다. 누군가 코드 응답을 올리면 얻지 못할 수도 있습니다. 나 한테서 가져 가라, 나는 그 실수를 저질렀다. – RossC

답변

0

에 대한 감사는 당신도 완전히 당신에 대해 물어하는지 확실하지 않을 때 쉽게 묻는 질문 아니라고 주셔서 감사합니다.

귀하의 도전적인 설명에 기초하여 귀하가 구축 할 수있는 예제 프로그램을 작성하려고 시도했습니다. 제 의견을 읽으십시오. 이해하기 쉽도록 배우기 쉽도록 설명했습니다.

public class Order { 

//Constructor 2 
public Order(String productName, int quantity) { 
this.productName = productName;//Get the name 
this.quantity = testQuantity(quantity); //Get the total quantity 
this.orderPrice =getPrice(productName, quantity); //Get the price of the order 
this.discountPrice = 0; //Should be set to a value, even though it won't be used in this constructor 
orderNum++; //Another order in, up the count :) 
displayOrder(productName, quantity, this.orderPrice, this.discountPrice); //Show order details 
} 

//Constructor 3 
public Order(String productName, int quantity, int discount) { 
this.productName = productName; //Get the name 
this.quantity = testQuantity(quantity); //Get the total quantity 
this.orderPrice = getPrice(productName, quantity); //Get the price of the order 
this.discountPrice = testDiscount(discount, this.orderPrice); //Get the price if there is a discount 

orderNum++; //Another order in, up the count :) 
displayOrder(productName, quantity, this.orderPrice, this.discountPrice); //Show order details 
} 

나는 쉽게 내 예를하게 보여, 나는 당신이 당신의 방법 중 일부가 작동하는 방법에 매우 확실했기 때문에 클래스의 맨 아래에 몇 가지 추가 필드를 추가했습니다. 나는 이것을 당신의 생성자에 넣고 초기화했고, 왜 그런지에 대해 주석을 달았다.

위의 방법은 생성자에 의해 생성 된 순서의 모든 세부 정보를 표시하고 볼 세부 정보를 표시합니다.

private int testQuantity(int q){ 
//What you want to do in this method, 
//For example 
//System.out.println("You have ordered " + q + "Items"); 
return q; 
} 

이 방법으로 무엇을하고 싶은지 불확실합니다. 가장 좋은 방법과 비교하여 수량을 확인하기 위해 사용할 수있는 총 항목 수를 저장해야하는 경우 데이터베이스가되므로 전체 학습 집합이 필요합니다.

private int testDiscount(int discount, int orderPrice){ //Will return a discounted price and store it in 'discountPrice' field 
int reducedPrice = (orderPrice - discount); 
return reducedPrice; 
} 

사용자가 전체 주문 가격 외에 할인을받은 경우 할인 된 가격을 반환합니다. 둘 다 생성자를 사용하여 생성 한 Order 객체에 의해 유지됩니다.

private int getPrice(String productname, int quantity){ 
int price = 0; 
switch(productName){  //Switch so you can find what item ordered and allocate the correct price 
//Add cases for different items? 
case "Sweater": 
price = 10; 
break; 
default: 
price = 0; 
break; 
} 
    int totalPrice = price * quantity; //Work out price by multiplying quantity of item by price determined by switch 
return totalPrice; 
} 

위 스위치는 항목 가격을 확인하는 가장 좋은 방법 일 수 있습니다. 각각의 경우에는 항목의 이름과 가격이 들어 있습니다. 해당 가격에 수량을 곱하여 주문 가격을 생성합니다.

private String productName; //Name of product 
private int quantity;  //Quantity ordered 
private int orderPrice;  // The total order of the price 
private int discountPrice; //Somewhere to store the price of an order with a discount 
private static int orderNum; //This is static so that you it can be referenced even if no orders  have been made 


public static void main(String[] args){ //Test the ordering 
Order order1 = new Order("Sweater", 2); 
Order order2 = new Order("Sweater", 2, 5); 
} 

응용 프로그램을 테스트하기 위해 '기본'방법으로 두 가지 주문을 만드십시오.

팅커를 가지고 놀아보세요. 나는 이것이 당신의 질문에서 원했던 것이지 확신 할 수 없지만,이 도움이된다면 잘 알 수 있습니다.

+0

감사합니다 답장을 보내 주셔서 대단히 감사합니다. 저는 아침에 그것을 들여다 볼 것입니다. 그러나 그 모습으로 볼 때 예상했던 것보다 훨씬 더 많아서 여러분의 반응과 제공 한 작업량에 정말 감사드립니다. 그것을 빠르게 살펴봄으로써 나 자신을 위해 알아 낸 것보다 훨씬 많은 정보가있는 것처럼 보입니다. 정보가 너무 많아서 매우 유용합니다. 다시 한번 감사드립니다. : DI는 실제 많이 내 프로젝트를 게시하지는 않았지만 거의 대부분을 다루었습니다. 그 부분은 상당히 어렵고 다시 감사합니다 :) – ChokeOnThis

+0

실제로 어떤 여분의 기회가 있었습니까? 전체 프로젝트에서 수행 한 작업을 보여주고, 코드를 코드와 일치시키기 위해 몇 가지 변경된 사항에 코드를 넣었지만 실제로 파악할 수없는 몇 가지 실수가 있습니다. 당신은 꼭 할 필요는 없지만, 제게 제공 한 도움이 제 프로젝트를 마무리하는 데 도움이 될 수 있습니다. – ChokeOnThis

+0

프로젝트의 다른 섹션을보고 싶습니까? – Levenal

관련 문제