0

I am making a multiplication app for kids on Android. Here is the code I have:

import java.awt.*;
import java.math.*;
import javax.swing.*;
public class S1P4 extends JFrame
{


public static void main(String[] args){
    int l = 0;
    int x =(int)(Math.random()*100);
    int y =(int)(Math.random()*10);
    int answer = -1;
    String answer3 = null;
    int []anArray;
    anArray = new int[20];



    for ( int i=0; i < 20; i++)
    {
        if ( (i % 2)==0)
            anArray[i]=(int)(Math.random()*100);
        else
            anArray[i]=(int)(Math.random()*10);
    }

    String answerString = "";
    String rightAnswer = "";
    for (l=0; l<20; l++) 
    {
        rightAnswer = Integer.toString(anArray[l] * anArray[l+1]);
        answerString = (JOptionPane.showInputDialog("The Problem is " + anArray[l] + " * " + anArray[l+1] + ", What is the answer? "));
    while (answerString.equals(""))
        answerString =JOptionPane.showInputDialog("Please type an answer to the problem:  " + anArray[l] + " * " + anArray[l+1] + ", What is the answer? "); 
    while (!answerString.equals(rightAnswer))
        answerString =JOptionPane.showInputDialog("Good try! but that's not it.. The problem again is:  " + anArray[l] + " * " + anArray[l+1] + ", What is the answer? ");                  
    }
    for (int n=0; answerString != rightAnswer; n++){
        if (anArray[l] == 1){
        System.out.println("Congratulations! you got all the correct answers in "+ n + l +"tries!");
        System.exit(0);}
        else{
            System.out.println("Error.");
            }
    }
}

Why won't this code work? I want it to print how many tries it took the user to get all the multiplication problems correct.

for (int n=0; answerString != rightAnswer; n++){
    if (anArray[l] == 20){
    System.out.println("Congratulations! you got all the correct answers in "+ n + l +"tries!");
    System.exit(0);}
    else{
        System.out.println("Error.");
        }
  }
}
4

2 回答 2

3

您应该使用equals()来比较字符串:

for (int n=0; !answerString.equals(rightAnswer); n++){

!=比较引用,而不是实际的字符串对象。此外,一个while-loop 似乎更适合这个:

int n = 0;
while (!answerString.equals(rightAnswer)) {
    ...
    n++
}

一般情况下,当循环控制变量与循环条件无关时,最好使用while-loop。

此外,如果您想null在比较字符串时考虑大小写,请考虑使用TextUtils.equals().

也可以看看:

于 2013-08-18T21:08:31.640 回答
0

您没有记录用户尝试获得正确答案的次数。在 while (!answerString.equals(rightAnswer)) {...} 中,您需要为尝试次数增加一个计数器。

最后的 for() 循环没有任何用处。它使用 n 作为循环计数器,但检查 anArray[l] (此时 l 将为 20,这是数组中未定义的索引 - 您只分配 20 个值)。

最后,你有一个错误。您正在尝试计算 anArray[l] * anArray[l+1],但是当 l==19 时,l+1 将为 20,您将尝试访问数组末尾的一个。您需要初始化 21 个值,但只需循环 20 次,此方法才能正常工作。

于 2013-08-18T23:10:10.377 回答