简体   繁体   中英

How to get the variable from other method Java

I get a result in one method the ResultOfFaktorial and I want to get the value to another method for saving to the file.

I tried make an object from it at least I hope but does not work maybe I made some stupid mistake. I tried to read the advice here but I don't get so much wisdom from it.

public class faktorial {
    static void myfactorial() {
        int ResultOfFaktorial;
        int faktorial = 5;
        int vysledek = 1;

        for (int i = 1; i <= faktorial; i++) {
            vysledek = vysledek * i;
        }
        ResultOfFaktorial = vysledek;
        System.out.println("Vysledek faktorialu je: " + ResultOfFaktorial);
    }   
}

The next class with method write to file

public class file {
    static void WriteToFile() {
        try {
            FileWriter myWriter = new FileWriter("newfile1.txt");
            myWriter.write("Tady bude vysledek" +ResultOfFaktorial);
            myWriter.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }  
    }
}

I get the error message

I expect I get 120 in another method for store the value.

Right now your method is printing out the result to the console and will not provide anything to the class trying to call it.

In myfactorial() change the void to an int and have myfactorial() return the value of ResultOfFaktorial instead of printing it out.

To get the value of ResultOfFaktorial in WriteToFile() have it make a call to faktorial.myfactorial()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM