2014-01-07 4 views
-5

У меня есть два класса. Я хочу использовать english и french из первого класса во втором классе (класс Вопрос). Пожалуйста, помогите мне исправить этот код, потому что он показывает мне ошибку.использование переменной из другого класса

блоки кода:

package josephtraduire; 

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

public class FileParser implements IParser{ 

    @Override 
    public void parseFile() throws IOException{ 
     String french=""; 
     String english=""; 

     try(BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\text.txt"))){ 
      String line;   
      while ((line = br.readLine())!=null){ 
        String[] pair = line.split(";"); 
        french=(pair[0]); 
        english=(pair[1]); 
      } 
     }   
    }    

} 

и

package josephtraduire; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.Date; 
import java.util.Scanner; 

public class Question extends FileParser { 

String mot ; 
String reponse ; 
String name; 
int nb; 
int nbquest ; 
String traduction; 

Question (String name , int nb){ 
    this.name=name; 
    this.nb=nb; 
} 

Question() throws IOException{ 

    InputStreamReader isr = new InputStreamReader(System.in); 
    BufferedReader in = new BufferedReader(isr); 
    { 
     System.out.println("Entrer votre nom "); 
     String nom = in.readLine(); 
     name=nom; 
    }  

    do { 
     System.out.println("Rentrez le nombre de question : (max 20)"); 
     Scanner nombrequest = new Scanner(System.in); 
     nbquest = nombrequest.nextInt(); 
     nb=nbquest; 
    } while (nbquest>20 ||nbquest<=0); 

} 

public void Play() throws IOException{ 

    int i=0; 
    boolean bool=true;  
    int score=0; 
    String continuer; 
    Date maDate = new Date(); 
    String a = maDate.toString() ; 

    while (i<nbquest && bool) { 
     InputStreamReader isr = new InputStreamReader(System.in); 
     BufferedReader in = new BufferedReader(isr); 

     System.out.println("donner la traduction de "+french); 
     String reponseee = in.readLine();  
     traduction=reponseee; 

     if(bool=true){ 
      if(traduction.equals(english)){ 
       score++; 
       System.out.println("Bravo! Bonne reponse"); 
      }else{ 
       System.out.println("Mauvaise reponse"); 
      } 
     } 
+8

Отформатируйте свой код и опубликуйте только соответствующий фрагмент кода. –

+6

... ваше ... ваше кодирование форматирования ... ужас .... –

+1

Пожалуйста, отформатируйте свой код еще раз и удалите все лишние пробелы и т. Д. –

ответ

1

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

Переменные - жить так долго, как жизнь класса, они объявленную в теле класса, но не в какой-либо метод или конструктор

Метод переменных - жить так долго, как метод и уже не будет, как правило, не делать какую-то работу, а затем ушли, они объявлены в метода/конструктор

public class ClassThatWantsFields { 

    public String combineFields(ClassWithFields classWithFields){ 
     //if I have access to the object classWithFields then I have access to its 
     //public methods (and possibly also protected and default access; but this is outside the scope of this question) 
     return classWithFields.getEnglish()+classWithFields.getFrench(); 
    } 

    public static void main(String[] args){ 
     ClassWithFields classWithFields=new ClassWithFields(); 
     ClassThatWantsFields classThatWantsFields=new ClassThatWantsFields(); 

     System.out.println(classThatWantsFields.combineFields(classWithFields)); 
    } 

} 


public class ClassWithFields { 
    private String English; //these are instance variables, they live for as long as the object lives 
    private String French; 

    private String preservedMayFly; 

    public ClassWithFields(){ 
     English="A language called English"; 
     French="A language called French"; 

     //mayfly is a method variable, it will be gone once the constructor 
     //exits, anything you want to keep for the life of the object should 
     //NOT be a method variable 
     String mayfly="I won't live long"; 

     //preservedMayFly is an instance variable and will live as long as 
     //the object 
     preservedMayFly=mayfly+"but I can be used within the method" 
    } 

    public String getEnglish() { 
     return English; 
    } 

    public String getFrench() { 
     return French; 
    } 



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