我有两个问题:
我有一个名为numbers2.txt的文本文件,显示(1,2,3,4,5,6,7,8,9,10)。如何将这些数字存储到ArrayList?我相当肯定你必须使用Double.parseDouble(string s)方法,但我不熟悉这个方法。
这个程序的目的是从我的ArrayList中随机选择一个运算符,然后用两个随机数计算问题。为了 if-statement我会把什么代替运营商?
这是我的代码:
String operator;
double answer;
Random rand = new Random();
ArrayList<String> myArray = new ArrayList<String>();
ArrayList<Double> doubles = new ArrayList<Double>();
public void CreateArrayList() {
myArray.add("add");
myArray.add("subtract");
myArray.add("multiply");
myArray.add("divide");
myArray.add("remainder");
myArray.add("greater than");
myArray.add("less than");
myArray.add("max");
myArray.add("min");
myArray.add("power");
try {
FileReader inFile = new FileReader("data/numbers2.txt");
Scanner scanner = new Scanner(inFile);
scanner.close();
}
catch (Exception ex) {
ex.printStackTrace();}
}
{
}
public void showOperations() {
double x = Math.floor(Math.random()*10);
double y = Math.floor(Math.random()*10);
int z = rand.nextInt(myArray.size());
if(operator == "add") {
answer = (x+y);
System.out.println(x + " "+ z +" "+y+ "= "+ answer);
}
} }
这是我的主要方法:
public static void main(String[] args) {
// TODO Auto-generated method stub
Operator op = new Operator();
op.CreateArrayList();
op.showOperations();
}
非常感谢任何帮助。谢谢。
答案 0 :(得分:0)
打开扫描仪后直接关闭扫描仪。这是毫无意义的举动。尝试实际使用来读取文件。此外,如果出现异常,请使用finally
块关闭扫描仪:
Scanner scanner = null;
try {
FileReader inFile = new FileReader("data/numbers2.txt");
scanner = new Scanner(inFile);
while(scanner.hasNextDouble){
doubles.add(scanner.nextDouble());
}
} catch (Exception ex) {
ex.printStackTrace();}
} finally {
if(scanner != null) {
scanner.close();
}
}
对于运算符部分,您不能只获取随机索引,还必须从该索引中检索元素:
int z = rand.nextInt(myArray.size());
// Get the element
operator = myArray.get(z);
switch (operator) {
case "add": {
answer = (x + y);
System.out.println(x + " + " + y + " = " + answer);
}
case "subtract": {
answer = (x - y);
System.out.println(x + " - " + y + " = " + answer);
}
case "multiply": {
answer = (x * y);
System.out.println(x + " * " + y + " = " + answer);
}
// and so on...
default:
System.out.println(x + ", " + y);
}