2013-02-17 2 views
0

Я искал, но не понял, как включить предыдущие ответы с моим собственным кодом. У меня есть желание создать проект программы для школы «банк/стипендия» - система. Здесь нам нужно создать множество разных методов, которые следует называть вместо того, чтобы просто делать изменения напрямую.(нестатический метод Change (String, String, String) не может ссылаться на статический контекст

Дело в том, что я продолжаю получать сообщение об ошибке в теме вместе с несколькими другими, и я не знаю, как это исправить. Я был бы очень признателен, если бы кто-нибудь мог объяснить мне, как и почему изменить один из моих методов, тогда я предполагаю, что смогу переписать все остальные. Вот мой код:

класс Адрес

public class Address { 

public String street, zip, post; 

public Address (String street, String zip, String post) { 

    this.street = street; 
    this.zip = zip; 
    this.post = post; 
} 

// these are setters (mutators) 
public void setStreet (String street) { 
    this.street = street; } 

public void setZip (String zip) { 
    this.zip = zip; } 

public void setPost (String post) { 
    this.post = post; } 

// these are getters 
public String getStreet() { 
    return this.street; } 

public String getZip() { 
    return zip; } 

public String getPost() { 
    return post; } 

// methods 
//public Address Change(Address newAddress) { 
//return newAddress; 
//} 

// output 
public String toString() { 
    return (street + ", " + zip + ", "+ post); } 

} 

класс Customer

import java.text.DecimalFormat; 

public class Customer { 

DecimalFormat twoD = new DecimalFormat("0.00"); 
Address address = new Address("Vik ", "6393 ", "Tomrefjord"); 

public String name, campus, newCampus, newAddress; 
public double loan, increase,decrease,regMaster; 
public boolean finished; 

public Customer (String name,Address address, String campus, double loan, boolean finished) { 
    this.name = name; 
    this.campus = campus; 
    this.loan = loan; 
    this.address = address; 
    this.finished = finished; 
} 

// these are setters 
public void setName (String name) { 
    this.name = name; } 

public void setCampus (String campus) { 
    this.campus = campus; } 

public void setLoan (double loan) { 
    this.loan = loan; } 

public void setFinished (boolean finished) { 
    this.finished = finished; } 

// these are getters 
public String getName() { 
    return name; } 

public String getCampus() { 
    return campus; } 

public double getLoan() { 
    return loan; } 

// methods 
public void RegMaster() { 
this.loan = loan * 0.90;} 

//public void changeAddress (Address newAddress) { 
//Address.Change(newAddress); } 

public double decreaseLoan (double currentBalance, double decrease) { 
currentBalance = currentBalance - decrease; 
return currentBalance; } 

public double getNewLoan (double currentBalance, double newLoan) { 
    newLoan = currentBalance + newLoan; 
    return newLoan; } 

public String getNewCampus (String newCampus) { 
    campus = newCampus; 
    return campus; }  

public static boolean Ended() { 
    return true; } 

// output 
public String toString() { 
     return (name + "\t\n" + address + "\t\n" + campus + "\t\n" + twoD.format(loan) + "\t\n" + finished); } 






} 

класс TestCustomer

import java.util.Scanner; 

public class TestCustomer { 

public static void main (String[] args) { 

    String student, school, answer, street, zip, post; 
    double balance, master; 
    boolean finished = false; 
    double done = 0; //this is for the loop 

    Scanner scan = new Scanner(System.in); 

    // a new student receives a loan 
    System.out.println("Write your name"); 
    student = scan.nextLine(); 
    System.out.println("Enter your street name and number"); 
    street = scan.nextLine(); 
    System.out.println("What is your zip code?"); 
    zip = scan.nextLine(); 
    System.out.println("What is your post area?"); 
    post = scan.nextLine(); 
    System.out.println("Where do you study?"); 
    school = scan.nextLine(); 
    System.out.println("Input your current loan"); 
    balance = scan.nextDouble(); 

    Address residence = new Address(street, zip, post); 
    Customer customer = new Customer(student, residence, school, balance, finished); 
    while(done < 1) { //the variable done will have the value 0 until you are finished. 
    // change address 
    System.out.println("Do you wish to change your address? (yes/no)"); 
    answer = scan.nextLine(); 
    if (answer.equalsIgnoreCase("yes")) { //this made it case-insensitive, and now it is not skipping anymore... 
     System.out.println("Write your street name and house number"); 
       street = scan.nextLine(); 
       System.out.println("Write your zip code"); 
       zip = scan.nextLine(); 
       System.out.println("Write your post area"); 
       post = scan.nextLine(); 
       //Address newAddress = new Address(street, zip, post); 
       //residence = Customer.changeAddress(newAddress); 
    } 

    // increase the loan 
    System.out.println("Do you want to increase your loan? (yes/no)"); 
    answer = scan.nextLine(); 
       if (answer.equalsIgnoreCase("yes")) { 
       System.out.println("How much do you need?"); 
       double increaseLoan = scan.nextDouble(); 
       //customer.balance = getNewLoan(customer.balance, moreLoan); 
      } 

    // decrease the loan 
    System.out.println("Do you want to make a downpayment on your loan?"); 
    answer = scan.nextLine(); 
       if (answer.equalsIgnoreCase("yes")) { 
        System.out.println("How much do you intend to pay?"); 
        double downpayment = scan.nextDouble(); 
        //customer.balance = decreaseLoan(customer.balance, downpayment); 
       } 


    // change school 
    System.out.println("Do you study at the same school? (yes/no"); 
    answer = scan.nextLine(); 
       if (answer.equalsIgnoreCase("no")) { 
       System.out.println("Write the name of the new school"); 
       school = scan.nextLine(); } 
       //school.getNewCampus(customer.campus); 

    // master check 
    System.out.println("Have you finished your master? (yes/no)"); 
    answer = scan.nextLine(); 
       if (answer.equalsIgnoreCase("yes")) { 
       customer.finished = Customer.Ended() ; //this will set finished to true, using the method like intended 
       //customer.balance = Customer.RegMaster();  // dont know how to invoke it... me neither -_- 
       } 
      System.out.println("Are you done? yes/no"); 
      answer = scan.nextLine(); 
         if (answer.equalsIgnoreCase("yes")) { 
        done = 1; } // this adds 1 to the variable done, thus ending the loop. 
      } 
      // output 
      System.out.println(""); 
      System.out.println("The data we have so far is:"); 
      System.out.println(customer); 

}} 

Здесь все три из моих классов. Некоторые из функций прокомментированы, другие просто не работают должным образом (код также немного лишний беспорядок, я менялся назад и вперед, чтобы попытаться заставить его работать вчера). Любая помощь будет оценена! :)

+1

какие ошибки вы получаете и где? – Abubakkar

+0

Судя по вашему названию вопроса [это] (http://www.geom.uiuc.edu/~daeron/docs/javaguide/java/anatomy/static.html), может помочь. –

+0

Где находится функция «изменения», на которой вы получаете ошибку? – BobTheBuilder

ответ

0

Хорошо, от Вас комментария, то ваша проблема исходит от (услужливо) закомментированных линий

//public void changeAddress (Address newAddress) { 
//Address.Change(newAddress); } 

Это потому, что Customer не сделали «иметь» Address, вам нужен экземпляр адреса и не String:

private Address address; 

public Customer (final Address address) { 
    this.address = address; 
} 

Я отредактированное другие переменные для ясности. Кстати, я бы использовал builder pattern ратен, чем один огромный конструктор.
Теперь, когда у вас есть Address в вашем Customer:

public void changeAddress (Some parameters to change) { 
    address.setStuff(); 
} 

Я рекомендовал бы прочитать this link о разнице между static и instance переменных.

+0

Спасибо, это было поучительно! После некоторой работы я сделал так, как предполагалось! :) –

+0

Если бы это было полезно, вы могли бы принять ответ, пожалуйста. Благодарю. –

Смежные вопросы