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

标签 java

如果这个问题的答案如此明显,我深表歉意,我什至不应该在这里发布这个,但我已经查找了编译以下代码的错误结果,并没有找到能够穿透我厚实、未受过教育的头骨的解释.

这个程序的目的是从用户那里获取 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

而且它也需要是static,因为您正试图在静态上下文(即 main 方法)中访问它。


另一种选择是在 main() 方法中但在循环开始之前声明它,以便在整个 main 方法中都可以访问它(如 "Patricia Shanahan" 所建议)。

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

关于java - 为什么我不能在循环中打印用户提供的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24677836/

相关文章:

java - @Preload 的作用是什么(Jira Activity 对象)?

java - DateTimeFormatter.parse() 更正日期信息而不是抛出异常

java - 三月两个日期之间的天数差异错误

java - 为什么我从服务器得到错误的对象属性?

java - 在推土机中映射抽象类

java - 拆分以下命令

java - 接受多部分文件的 DELETE 方法的 Mockmvc

java - Component.getWidth() 在不同的上下文中返回 0

java - 从库中查找正则表达式源,例如。 hibernate validator

java - JPA无效流头: 32303138