2012-11-12 3 views
1

나는 웹 사이트에 이미 주어진 다양한 제안을 시도했다. 그러나 솔직히 나는 그것을 고칠 무언가를 couldnt.다양한 기능에서 변수를 사용하려면 어떻게해야합니까? 자바

기본적으로 수락에서 만든 변수를 사용하려고하면 다른 기능에서 사용할 수 없습니다. 이 문제를 해결할 수있는 간단한 해결책이 있습니까? (주 코드를 변경하지 않고)

import java.util.Scanner; 
class x4Salary 
    { 
     Scanner input = new Scanner(System.in); 
     public void accept() 
     { 
      System.out.println("Please input the name of the teacher"); 
      String name = input.next(); 
      System.out.println("Please input the address "); 
      String adress = input.next(); 
      System.out.println("Please input the phone number"); 
      long num = input.nextLong(); 
      System.out.println("Please input the subject specialization"); 
      String subjectSpecialization = input.next(); 
      String subS = subjectSpecialization; 
      System.out.println("Please input the Monthly Salary"); 
      long sal = input.nextLong(); 
      if(sal>175000) 
      { 
       tax(); 
      } 
      display(); 
      double tax = 0.0; 
     } 
     public void tax() 
     { 
      System.out.println("Your current salary is : " + sal); 
      tax = sal + ((5/sal)*100); 
      System.out.println("The salary + Tax : " +tax); 
      display(); 
     } 
     public void display() 
      { 
       System.out.println("The name of the teacher : " + name); 
       System.out.println("The Address of the teacher :" +adress); 
       System.out.println("The Phone number of the Teacher: "+num); 
       System.out.println("The Subject Specialization of the Teacher" + subS); 
       System.out.println("The Monthly salary of the teacher" +sal + tax); 
      } 
     } 
+1

* "이미 웹 사이트에서 여러 가지 제안을 시도했습니다." 보았던 3 개의 쓰레드에 링크하십시오. –

답변

3

당신은() 대신 문자열 이름 = input.next의 다음 클래스 멤버

class x4Salary 
{ 
    protected String name, address; //and so on 

으로 그 변수를 만들 수 있습니다;

name = input.next(); 

이름은 그 변수가 혼자 방법에 범위된다 X4Salary

+0

고맙습니다. – sun

+0

@ user1817822,이 작업과 이것이 원하는 작업입니까? –

+0

이것은 완벽하고 놀랍게도 작동합니다! – sun

1

변수를 instance 변수로 만들어야합니다.

메소드에서 작성된 변수는 해당 메소드 범위에만 국한됩니다. 이 방법 밖에는 보이지 않습니다. 메소드가 호출 될 때 작성되고 메소드가 실행을 완료하면 해당 변수는 Garbage Collection에 적합하게됩니다.

이것은 모든 블록 범위에 해당됩니다. 한 블록에서 생성 된 변수는 해당 블록 외부에서 볼 수 없습니다. 예를 들어

: - : 당신이 볼 수 있듯이,

public class Demo { 
    private int num; // Instance variable declaration. Outside every method. 

    public void setNum(int num) { 
     this.num = num; 
    } 

    public int getNum() { 
     return this.num; 
    } 
} 

그래서 num 모두에 사용되는 변수 - 그래서

{ // A block 
    int num = 10; 
} 

System.out.println(num); // Error. num not visible here. 

는,로 선언, 모든 메소드에서 변수에 액세스 할 수 방법 : - setNumgetNum. 이 튜토리얼에


이동이 classes, objects를 시작하고, member declarations가 : -

1

당신이 지역 변수를 사용하지 못할 (변수는 메서드 내 정의) 그 방법 밖에. 해당 메서드는에만 국한됩니다. 인스턴스 변수으로 만들거나 변수을 반환해야합니다. 다른 방법으로 사용할 수 있습니다. 귀하의 경우에는 입니다. sal 외부 방법을 사용하려는 경우. 그것을 인스턴스 변수로 만드십시오.

Class classname { 
public long sal; 

public void accept(){ 
//can access sal here 
sal = input.nextLong(); 
} 

public void display(){ 
//cvan access sal here 
} 
} 
+0

스캐너로 시도 할 때 불법적 인 표현의 시작이라고합니다. – sun

+0

괜찮습니다. 해결책을 얻었습니다 .. 고마워요! – sun

1

의 모든 메소드에 표시 될 것입니다.입력 한 값을 그대로 유지하려면 다음 옵션을 사용하십시오.

  1. 포함하는 클래스에 멤버 변수를 만들고 채 웁니다. 그 값은 해당 클래스의 수명 동안 사용할 수 있습니다.
  2. 메서드에서 값을 반환합니다. 값이 여러 개인 경우이 값이 포함 된 객체를 반환하려는 경우
  3. 해당 메서드 내에서 다른 객체를 호출하고 그런 식으로 데이터를 전달하십시오.

옵션 2를 위해 당신은 따라서 반환 객체를 정의 할 수 있습니다 :

class Teacher { 
    private String name; 
    private String phone; 

    // add appropriate constructor 
} 

나는 Teacher 응용 프로그램의 주요 목적은 의심하고 당신은 가능성이 교사 클래스 자체에 방법 display()를 추가 할 것입니다. OO는 객체를 생성하고 객체를 사용자가 직접 처리하도록하는 것이고 이산 관련 변수는 직접 처리하지 말아야한다는 것을 기억하십시오..

+1

'display()'메서드를 사용하는 대신'toString()'을 오버라이드하는 것이 더 좋을 것입니다. 이것은'class'의 인스턴스를 출력 할 때 자동으로 호출됩니다. –

1

변수를 클래스의 멤버 변수로 정의하면 모든 멤버 메서드에서 변수에 액세스 할 수 있습니다.

import java.util.Scanner; 
class x4Salary 
    { 
     private double tax=0.0; 
     private string name, adress, subS; 
     private long num, sal; 
     Scanner input = new Scanner(System.in); 
     public void accept() 
     { 
      System.out.println("Please input the name of the teacher"); 
      name = input.next(); 
      System.out.println("Please input the address "); 
      adress = input.next(); 
      System.out.println("Please input the phone number"); 
      num = input.nextLong(); 
      System.out.println("Please input the subject specialization"); 
      subS = input.next(); 
      System.out.println("Please input the Monthly Salary"); 
      sal = input.nextLong(); 
      if(sal>175000) 
      { 
       tax(); 
      } 
      display(); 
     } 
     public void tax() 
     { 
      System.out.println("Your current salary is : " + sal); 
      tax = sal + ((5/sal)*100); 
      System.out.println("The salary + Tax : " +tax); 
      display(); 
     } 
     public void display() 
     { 
      System.out.println("The name of the teacher : " + name); 
      System.out.println("The Address of the teacher :" +adress); 
      System.out.println("The Phone number of the Teacher: "+num); 
      System.out.println("The Subject Specialization of the Teacher" + subS); 
      System.out.println("The Monthly salary of the teacher" +sal + tax); 
     } 
    }