簡體   English   中英

無法在基本類型int上調用nextint()

[英]Cannot invoke nextint() on the primitive type int

所以我正在學習Java,也許他沒有很好地解釋掃描儀的工作方式和限制,或者我正在尋找一些愚蠢的東西......但是我在answer = answer.nextInt(); 我沒有得到這個bomb錯誤,但它的使用方式幾乎相同......

碼:

    Scanner yesNo = new Scanner(System.in);
    Scanner input = new Scanner(System.in);
    // 
    //answer auto set to no. goes to first if, then asks for confirmation,
    // then check answer again and go to if, else if or else. 
    //
    int answer = 0;
    while (answer != 1)
        if (answer == 0) {
            System.out.println("In how many seconds should we detonate?");
            int bomb = input.nextInt();
            //this number will be used later in else if (answer == 1)
            System.out.println("Is " + bomb + " seconds correct? 1 for yes, 0 for no");
            answer = answer.nextInt();
            //error above "Cannot invoke nextint() on the primitive type int"
            //Need this to grab a number from user to assign a new value to answer

做什么? 謝謝。

首先,你有一個帶有paramether System.in的Scanner實例,所以它會“記錄”你的鍵盤(我假設沒有使用yesNo掃描儀)。 然后,你有一個名為“answer”的int變量,你可以賦值為零。 最后,您有另一個名為“炸彈”的變量,您將獲得所需的值。

正如我在你的答案中看到的那樣,你在一件事上是錯的:“input.nextInt()”是一個int值。 當你使用input.nextInt()時,你會發送一條消息,上面寫着“嘿兄弟,給我這個愚蠢的人類按下的第一個int”,但是你沒有做更多的事情。 “input”只是一個記錄擊鍵的掃描器(正如它的類名所示)。

所以事實上,當你執行“input.nextInt()”時,你將獲得一個int值,當你執行“bomb = input.nextInt()”或“answer = input.nextInt()”時,你唯一的事情是'正在做的是給予“炸彈”或“回答”這個int值。

int是原始值。 它不是Object,也沒有方法。

可能你想做

answer = input.nextInt();

nextInt()是一個函數,它是對象類型Scanner的一部分。 要調用.nextInt(),您必須擁有Scanner類型的對象。

所以行“int bomb = input.nextInt();” 工作正常,因為“輸入”是類Scanner的對象。 該函數運行並從輸入返回另一個對象,一個整數,存儲在int bomb中。

行“answer = answer.nextInt();” 無法編譯,因為“answer”是類整數的對象。 integer沒有名為nextInt()的函數。

適當的行是“answer = input.nextInt();” 使用您的Scanner對象返回另一個整數以“answer”存儲。

int answer = 0;

answer = answer.nextInt();

你在int上調用nextInt() 你需要在掃描儀上調用它:

answer = input.nextInt();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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