简体   繁体   中英

accessing variable within main method

I am very new to Java and writing this program to shuffle words and fix the suffle words. The following is my program. After I call mix() , I would like to be able to assign the output of word to team array within main.

For some reason, I can call mix() it works but I cannot access word which is in the shuffle function. Since I am in main and all these function within main , I thought I can access the variables. Any ideas what I am missing here?

import java.util.Scanner;
import java.io.*;
import java.util.*;

public class Project2
{


    public static void main(String[] args) 
    {


                System.out.println("Select an item from below: \n");
                System.out.println("(1) Mix");
                System.out.println("(2) Solve");
                System.out.println("(3) Quit");


                int input;
                Scanner scan= new Scanner(System.in);
                input = scan.nextInt();

                //System.out.println(input);  
                if(input==1) {
                    mix();
                    System.out.println(word);
                    char team[]=word.toCharArray();
                    for(int i=0;i<team.length;i++){
                        System.out.println("Data at ["+i+"]="+team[i]);
                    }
                }
                else{
                    System.out.println("this is exit");
                    } 
        }




        static void mix()
         {
        String [] lines=new String[1000];//Enough lines.
        int counter=0;
        try{
            File file = new File("input.txt");//The path of the File
            FileReader fileReader1 = new FileReader(file);
            BufferedReader buffer = new BufferedReader(fileReader1);
            boolean flag=true;
            while(true){
                try{
                    lines[counter]=buffer.readLine();//Store a line in the array.
                    if(lines[counter]==null){//If there isn't any more lines.
                        buffer.close();
                        fileReader1.close();
                        break;//Stop reading and close the readers.

                    }
                    //number of lines in the file
                    //lines is the array that holds the line info
                    counter++;

                    }catch(Exception ex){
                        break;
                    }
            }

            }catch(FileNotFoundException ex){
                System.out.println("File not found.");
            }catch(IOException ex){
                System.out.println("Exception ocurred.");
            }


                int pick;
                 Random rand = new Random();
                 pick = rand.nextInt(counter ) + 0;

                System.out.println(lines[pick]);
                ///scramble the word

                shuffle(lines[pick]);


    }

    static void shuffle(String input){
        List<Character> characters = new ArrayList<Character>();
        for(char c:input.toCharArray()){
            characters.add(c);
        }

        StringBuilder output = new StringBuilder(input.length());
        while(characters.size()!=0){
            int randPicker = (int)(Math.random()*characters.size());
            output.append(characters.remove(randPicker));
        }

        String word=output.toString();


    }


  }

Return string value from shuffle() method using return statement:

static String shuffle(String input) {
     // . . .
     return output.toString();
}

...and then use it in mix:

String word = shuffle(lines[pick]);

But it is better to read basic java tutorials before programming.

In Java, variables cannot be seen outside of the method they are initialized in. For example, if I declare int foo = 3; in main, and then I try to access foo from another method, it won't work. From the point of view of another method, foo does not even exist!

The way to pass variable between methods is with the return <variable> statement. Once the program reaches a return statement, the method will quit, and the value after the return (perhaps foo ) will be returned to the caller method. However, you must say that the method returns a variable (and say what type is is) when you declare that method (just like you need to say void when the method does not return anything!).

public static void main(String[] args){
     int foo = 2;
     double(foo); //This will double foo, but the new doubled value will not be accessible
     int twoFoo = double(foo); //Now the doubled value of foo is returned and assigned to the variable twoFoo
}

private static int double(int foo){//Notice the 'int' after 'static'. This tells the program that method double returns an int. 
     //Also, even though this variable is named foo, it is not the same foo
     return foo*2;
}

Alternatively, you could use instance variable to have variables that are accessible by all the methods in your class, but if you're new to Java, you should probably avoid these until you start learning the basics of object-oriented programming.

Hope this helps! -BritKnight

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