简体   繁体   中英

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.

What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.

import java.util.Scanner;

public class Exercise2
{   
    int integerone, integertwo; //putting ''static'' here doesn't solve the problem
    static int number=1;
    static Scanner kbinput  = new Scanner(System.in);
    public static void main(String [] args)     
    {
        while (number<3){
            System.out.println("Type in integer "+number+":");
            if (number<2)
            {
                int integerone = kbinput.nextInt(); //the integer I can't access
            }
            number++;
        }
        int integertwo = kbinput.nextInt();
        System.out.println(integerone); //how do I fix this line?
        System.out.println(integertwo);
    }
}

Explanation or a link to the right literature would be greatly appreciated.

EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.

Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.

static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
    System.out.println("Type in integer "+number+":");
    if (number<2)
    {
       integerone = kbinput.nextInt(); //no int keyword
    }
    number++;
}
integertwo = kbinput.nextInt(); // no int keyword

And it needs to be static as well since you're trying to access it in a static context (ie) the main method.


The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan" ).

public static void main(String [] args) {
    int integerone, integertwo; // declare them here without the static
    ... // rest of the code
}

How about:

import java.util.Scanner;

 public class Main {

   public static void main(String[] args) {
        Scanner kbinput  = new Scanner(System.in);

        System.out.println("Type in an integer: ");
        int integerone = kbinput.nextInt();

        System.out.println("Type another: ");
        int integertwo = kbinput.nextInt();

        System.out.println(integerone);
        System.out.println(integertwo);    
  }
}

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