Java 为什么我不能在循环中打印用户提供的变量?

Java 为什么我不能在循环中打印用户提供的变量?,java,Java,我很抱歉,如果这个问题的答案是如此明显,我甚至不应该在这里张贴这一点,但我已经查找了编译以下代码的错误结果,并没有发现任何解释能够穿透我的厚,未受过教育的头骨 这个程序要做的是从用户那里得到2个整数并打印出来,但我不知怎么搞砸了 import java.util.Scanner; public class Exercise2 { int integerone, integertwo; //putting ''static'' here doesn't solve the prob

我很抱歉,如果这个问题的答案是如此明显,我甚至不应该在这里张贴这一点,但我已经查找了编译以下代码的错误结果,并没有发现任何解释能够穿透我的厚,未受过教育的头骨

这个程序要做的是从用户那里得到2个整数并打印出来,但我不知怎么搞砸了

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);
    }
}
如能提供相关文献的解释或链接,将不胜感激

编辑:我想在这里使用一个循环,以探索执行此操作的多种方法。

在第二次使用同一变量时删除int关键字。因为当你这么做的时候,它实际上是在声明另一个同名的变量

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
第二次使用同一变量时,请删除int关键字。因为当你这么做的时候,它实际上是在声明另一个同名的变量

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
那么:

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);    
  }
}
那么:

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);    
  }
}

他还需要使整合素静止。否则,这就超出了范围。他是从main方法访问它的。或者在main内声明它,但在循环外。他还需要使integerone保持静态。否则,这就超出了范围。他是从main方法访问它的。或者在main内声明它,但在循环外。