简体   繁体   中英

In java, how do I store each scanner input in a 'for' loop to another method?

I'm trying to send a variable out of a 'for' loop, and save it to a string in another class, but I just end up with the latest input when doing a system print in the last class. Now I suspect this is because of;

ProcessInput c = new ProcessInput();

But I cannot for the life of me understand how I work around that particular problem.

I realize this could be avoided if I appended latest input to a string, and sendt the string after the loop finished. Alas my assignment is not so. Also I'm quite new at this, so be gentle.

public class Query {

    private void question() {

        ProcessInput c = new ProcessInput();
        String feedback = "";
        for(int i = 0; i < 10; i ++) {
            System.out.print("Input information " + (i + 1) + "/10: ");
            Scanner userInput = new Scanner(System.in);
            feedback = userInput.next();
            c.paste(feedback);
        }
    }
}


public class ProcessInput {

    public void paste(String feedback) {
        String line = "";
        line += feedback + " ";
        System.out.println(line);
    }
}

The line is in the local scope of the method and therefore, it is reset every time the method is called. You need to make it an instance variable, so that for every instance created, it preserves the value for that instance.

public class ProcessInput {
    String line = ""; // outside the paste method, in the class
    public void paste(String feedback) {
        line += feedback;
        System.out.println(line);
    }
}

The concept that you must understand is java is pass by value and not reference, So you are only passing the new input entered every time to the method "paste".

Simple solution

public class Query {

    private void question() {

        ProcessInput c = new ProcessInput();
        String feedback = "";
        for(int i = 0; i < 10; i ++) {
            System.out.print("Input information " + (i + 1) + "/10: ");
            Scanner userInput = new Scanner(System.in);
            feedback = feedback+userInput.next();
            c.paste(feedback);
        }
    }

public class ProcessInput {

    public void paste(String feedback) {       
        System.out.println(feedback);
        }
    }

It is more important you understand the underlying concept of passing values between methods in java.

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