[英]Why can't I print a variable that is provided by user inside a loop?
如果这个问题的答案如此明显,我深表歉意,我什至不应该在这里发布这个信息,但是我已经在编译以下代码结果时发现了错误,并且找不到能够穿透我厚重而未受教育的头骨的解释。
该程序的作用是从用户那里获取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
}
怎么样:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.