2013-04-03 76 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 
相关问题