簡體   English   中英

為什么我不能在循環內打印用戶提供的變量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM