我正在研究一个Java程序,该程序应该表现得像一个“虚拟寻宝游戏”,基本上它会随机进行数字运算,直到找到与您要寻找的动物相匹配的数字,然后显示结果。该信息应该存储在文件中,然后显示在控制台中,但是只要我单击运行,它就会终止。我在想某种逻辑错误,因为我对语法没有任何了解。
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
public class AnimalPopulation {
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
int totalTrials = 0;
int animalsSpotted = 0;
double randNum = 0;
double myAnimal = 4.0;
double notMyAnimal = 0;
String data = "int";
Scanner in = new Scanner(System.in);
Scanner inFile = new Scanner ("animals.txt");
PrintWriter outFile = new PrintWriter(new File("animals.txt"));
//BufferedReader in = new BufferedReader(new FileReader("animals.txt"));
System.out.println("How many trials will you be running? (It must be greater than or equal to 1,000.)");
totalTrials = in.nextInt();
while(animalsSpotted < totalTrials) {
animalsSpotted++;
randNum = (1 + (Math.random()* 9));
if(randNum < myAnimal) {
outFile.println(notMyAnimal++);
}else if(randNum > myAnimal) {
outFile.println(notMyAnimal++);
}else if(randNum == myAnimal) {
outFile.println(myAnimal++);
while(inFile.hasNext()) {
data = inFile.next();
System.out.println(data);
}
inFile.close();
}
}
outFile.close();
}
}
答案 0 :(得分:2)
第一件事是您必须将randNum更改为int并使用ThreadLocalRandom
,如答案中所述,另一件事是首先将所有数据写入文件,然后读取它不要并行执行,这是一个程序,以您为例:
import java.io.*;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class AnimalPopulation{
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int totalTrials = 0;
int animalsSpotted = 0;
int randNum = 0;
double myAnimal = 4.0;
double notMyAnimal = 0;
String data = "int";
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(new File("animals.txt"));
//BufferedReader in = new BufferedReader(new FileReader("animals.txt"));
System.out.println("How many trials will you be running? (It must be greater than or equal to 1,000.)");
totalTrials = in.nextInt();
while(animalsSpotted < totalTrials) {
animalsSpotted++;
randNum = ThreadLocalRandom.current().nextInt(1,11);
if(randNum < myAnimal) {
outFile.println(notMyAnimal++);
}else if(randNum > myAnimal) {
outFile.println(notMyAnimal++);
}else if(randNum == myAnimal) {
outFile.println(myAnimal++);
}
}
outFile.close();
File file = new File("animals.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
答案 1 :(得分:1)
randNum为double
,而(1 + (Math.random()* 9))
产生的分数在1到10之间,因此极不可能等于4.0。相反,您可能需要将类型更改为int
,并使用ThreadLocalRandom.current().nextInt(1,11)
来生成1到10之间的值。