2013-04-03 211 views
0

我正在研究一個程序,需要生成一個三位數的隨機數,然後掃描每個數字以便與猜測遊戲的輸入進行比較。Java:找不到合適的構造函數掃描器(int)

我沒有初始化實例變量,我只是沒有把它們放在這裏。我也有其他方法,我認爲這不會影響我現在遇到的問題。老實說,我對編程和Java很陌生,所以它可能比我想象的要複雜得多。但我的問題是,當我創建一個名爲randScan的掃描器對象並嘗試將其設置爲掃描我的secretNumber對象(隨機生成)時,出現一個錯誤消息,提示「找不到適合Scanner(int)的構造函數...」和那麼它下面的很多其他錯誤(輸入方式太多)。我只是不明白爲什麼它不會掃描randomNumber,因爲它是一個int。

任何幫助將不勝感激! :)

import java.util.Random; 
import java.util.Scanner; 
import javax.swing.JOptionPane;  

// Generates three random single digit ints. The first cannot be zero 
// and all three will be different. Called by public method play() 
public String generateSecretNumber() 
{ 

    do 
    { 
     secretNumber = (int)(generator.nextInt(888)+101) ;    
     // scan the random integer 
     Scanner randScan = new Scanner(secretNumber) ; //<- THIS IS THE PROBLEM! 
     num1 = randScan.nextInt();      // scan the first digit 
     num2 = randScan.nextInt() ;      // scan the second digit 
     num3 = randScan.nextInt() ;      // scan the third digit 
    } 
    while (num1 == 0 || num1 == num2 || 
     num2 == num3 || num1 == num3) ; // re-generate if any digits are the same 

    return number ; 
+3

爲什麼你需要'掃描儀? – NilsH

+0

我需要用它來比較另一個3位數的輸入,所以我使用掃描儀分別分離每個數字,並將其與三位猜測輸入進行對比,以便我們可以打印出他們正確猜測數字的「提示」。 –

回答

4

如果你只是想獲得的secretNumber三個數字(如整數值),你可以使用:

num1 = secretNumber/100; 
num2 = (secretNumber/10) % 10; 
num3 = secretNumber % 10; 

有沒有必要轉換到這裏使用字符串。在另一方面,如果你不需要secretNumber本身,想必你只需要1到9之間產生三個數字做是使用像最簡單的方法:

List<Integer> digits = new ArrayList<Integer>(); 
for (int i = 1; i <= 9; i++) { 
    digits.add(i); 
} 
Collections.shuffle(digits, generator); 

.. 。然後在列表中使用的前三個值:

num1 = digits.get(0); 
num2 = digits.get(1); 
num3 = digits.get(2); 
+0

我這樣做的原因是因爲該方法需要一個字符串類型的輸出,所以我必須將該數字轉換爲字符串以便從該方法返回值。但是你對這三位數字有一個很好的觀點,分割和使用mod要簡單得多。也許我可以將每個數字分別轉換爲一個字符串,然後將它們連接成一個。 –

0

Available constructors for scanner

Scanner(File source) 
Scanner(File source, String charsetName) 
Scanner(InputStream source) 
Scanner(InputStream source, String charsetName) 
Scanner(Readable source) 
Scanner(ReadableByteChannel source) 
Scanner(ReadableByteChannel source, String charsetName) 
Scanner(String source) 

對於單位數,Y OU應該

String secretNumberString = new String(secretNumber); 

可能會通過與String.valueOf(yourInt)

1

一個字符串你應該處理secretNumber爲一個字符串,然後之後你需要嘗試Scanner#hasNextInt
按照文件

Returns true if the next token in this scanner's input can be 
interpreted as an int value in the default radix using the nextInt() method. 
The scanner does not advance past any input. 


所以我想這可能會解決您的問題
所以你的代碼就像

secretNumber = (int)(generator.nextInt(888)+101) ;    
     String secretNumberString = new String(secretNumber); 
     Scanner randScan = new Scanner(secretNumberString) ; 
     if(randScan.hasNextInt()) 
      num1 = randScan.nextInt(); 
      //Remaining code 
相關問題