【问题标题】:How to compare Numbers from a file with random numbers?如何将文件中的数字与随机数进行比较?
【发布时间】:2014-12-27 06:12:43
【问题描述】:

大家好,就是这样。我的乐透应用程序有效,但我只需要最后一件事来实现,我对此有一个非常大的问题。所以我有 6 个号码保存在“lotto.dat”文件中。 1, 2, 3, 4, 5, 6。如果我不选择获取新数字,应用程序会生成 6 个新的随机数并进行比较。这行得通。

但是,如果我不想要 6 个新数字,请将它们保存在 ArrayList 中并将它们打印流到“lotto.dat”中,该文件现在包含 6 个数字,其中包含 arrayList 事物的括号 cus。我有一种感觉,这可能是问题所在,因为当保存新号码时,它说即使有也没有匹配。

这是我的数字方法:

  Scanner scann = new Scanner(System.in);

  File f = new File("lotto.dat");

  PrintStream output = new PrintStream(f);

  output.print(num1 + " " + num2 + " " + num3 + " " + num4 + " " + num5 + " " + num6);

  System.out.println("Your lotto numbers: " + num1 + " " + num2 + " " + num3 + " " + num4 + " " + num5 + " " + num6);

  System.out.println("Would you like to keep these numbers? y/n");

  String yn = scann.nextLine();

  if(!yn.equals("y")){

     newNumbers();

  }//While yn !y

在我的 newNumbers 方法中,我用控制台中编写的 6 个 newNumbs 填充 ArrayList。然后我将arraylist 打印到被覆盖的“lotto.dat”中。

现在这是我比较随机数(来自 ArrayList 的数字)的代码:

  for(int n : numbers) {      // go through all the numbers in the list

     String match = doCompare(n);  // doCompare metode

     if(match.equals("true")){

        List<Integer> numbersMatch = new ArrayList<>();

           numbersMatch.add(n);

        Thread.sleep(1000);
        System.out.println();
        System.out.println("Match on the number: " + n);

        count++;
     } 
  }

这是我的 doCompare 方法:

  Scanner sc = new Scanner(new File("lotto.dat"));

  List<Integer> mn = new ArrayList<>();

  while(sc.hasNextInt()){
     mn.add(sc.nextInt());    
  }

  if(mn.contains(n)){

     String tf = "true";
     return tf;

  }
  else{

     String tf = "false";
     return tf;

  }

我确实花了很多时间试图解决这个问题,但我做不到。为什么不比较数字?唯一真正改变的是,lotto.dat 中保存的新号码在外部文件中有“[]”。

【问题讨论】:

  • 抱歉,我的咖啡不能正常工作,所以我需要澄清一下。您的确切问题是:“如果数字是新生成的,则文件中的数字比较不起作用?”我说得对吗?
  • 您的doCompare() 方法应该返回boolean,而不是必须与truefalse 进行比较的String。你的问题仍然模糊不清。

标签: java methods arraylist printstream


【解决方案1】:

你说

但如果我不想要 6 个新数字,请将它们保存在 ArrayList 中并将它们打印流到“lotto.dat”中,该文件现在包含 6 个数字,其中包含 arrayList 事物的括号 cus。

考虑到上面的语句,下面的代码会出现问题,因为当扫描仪看到括号时,您的 while 循环将立即退出,并且数组中不会有任何 int

 while(sc.hasNextInt()){
 mn.add(sc.nextInt());}

既然您的问题很清楚,您可以尝试在文件中写入一个 for 循环,以防止这些括号包含在您的文件中,或者您可以使用正则表达式在读取之前从文件中消除那些不是 int 的字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2017-07-09
    相关资源
    最近更新 更多