2016-09-13 2 views
0

나는 자바의 초보자이며,이 변수를 한 메소드에서 다른 메소드로 사용하는 방법을 알아야 할 필요가있다. 도와주세요. 코드에서하나의 메소드에서 다른 메소드로 double 접근하기

public class parking { 
public static void input(String args[]) { 

    int hoursParked = IO.getInt("(\\(\\ \n(-,-)  How many hours were you parked?\no_(\")(\")"); 
    double bill = hoursParked * 0.5 + 2; 
} 

public static void output(String args[]) { 
    System.out.println("   Parking"); 
    System.out.println("$2 Fee plus $0.50 every hour!"); 
    System.out.println("\nYour amount owed is $" + bill + "0"); 

} 

}

+0

메소드 입력시 bill을 선언 했으므로 SOUT의 출력 메소드에 넣어야합니다. –

+0

변수의 범위를 이해해야합니다. https://www.cs.umd.edu/~clin/MoreJava/Objects/local.html – kosa

+0

이것들은 단지'input' 메소드 내부의 지역 변수입니다. 그것들은 클래스 변수가 아닙니다. 메소드간에 사용하려는 경우에는 선언 할 필요가 있습니다. –

답변

1

billinput에서 지역 변수입니다. 외부 변수 input에서 해당 변수를 참조 할 수 없습니다. inputoutput 별도의 방법이 될 경우

후 보통 일이 그 예를 방법을 확인하고 방법을 사용하는 parking 인스턴스를 생성하는 것입니다. 이를 통해 bill인스턴스 변수 (별칭 "인스턴스 필드")로 저장할 수 있습니다. (일반적으로 클래스는 처음에, 예를 들어 Parking 출장, 그래서 내가 여기에 있다고 할 수 있습니다.)

public class Parking { 
    private double bill; 

    public Parking() { 
     this.bill = 0.0; 
    } 

    public void input() { 
     int hoursParked = IO.getInt("(\\(\\ \n(-,-)  How many hours were you parked?\no_(\")(\")"); 
     this.bill = hoursParked * 0.5 + 2; // Or perhaps `+=` 
    } 

    public void output() { 
     System.out.println("   Parking"); 
     System.out.println("$2 Fee plus $0.50 every hour!"); 
     System.out.println("\nYour amount owed is $" + this.bill + "0"); 
    } 
} 

는 (자바는 선택 인스턴스 멤버를 참조 할 때 this.를 사용한다. 나는 항상 만들기 위해, 위와 같이, 그것을 사용 옹호 그것은 분명 우리는 지역 변수를 사용하지 않는 것입니다. 다른 의견이 불필요하고 자세한의 말 다릅니다. 그것은 스타일의 문제입니다.)

사용

Parking p = new Parking(); 
p.input(args); 
p.output(); 

또는, 반환 다음 input과에서 bill의 값은 output에 전달할 :

public class Parking { 

    public static double input() { 
     int hoursParked = IO.getInt("(\\(\\ \n(-,-)  How many hours were you parked?\no_(\")(\")"); 
     return hoursParked * 0.5 + 2; 
    } 

    public static void output(double bill) { 
     System.out.println("   Parking"); 
     System.out.println("$2 Fee plus $0.50 every hour!"); 
     System.out.println("\nYour amount owed is $" + bill + "0"); 
    } 
} 

사용법 :

double bill = parking.input(args); 
parking.output(bill); 

는 사이드 참고 : inputoutput도 있기 때문에 args 아무것도, 나는 그것을 제거했습니다 않았다 위.

+0

설명 주셔서 감사합니다! –

0

클래스 변수로 선언 한 다음 액세스 할 수 있습니다.

public class parking { 

private double bill; 

public void input(String args[]) { 
int hoursParked = IO.getInt("(\\(\\ \n(-,-)  How many hours were you parked?\no_(\")(\")"); 
bill = hoursParked * 0.5 + 2; 
} 

public void output(String args[]) { 
System.out.println("   Parking"); 
System.out.println("$2 Fee plus $0.50 every hour!"); 
System.out.println("\nYour amount owed is $" + bill + "0"); 
} 
+0

도움을 주셔서 감사합니다! –

관련 문제