for循环中的字符串比较

时间:2013-08-18 21:04:06

标签: java android if-statement for-loop

我正在为Android上的孩子制作一个乘法应用程序。这是我的代码:

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.");
            }
    }
}

为什么这段代码不起作用?我希望它能够打印用户获取所有内容的尝试次数 乘法问题正确。

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.");
        }
  }
}

2 个答案:

答案 0 :(得分:3)

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

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

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

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

通常,当循环控制变量与循环条件无关时,最好使用while - 循环。

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

另见:

答案 1 :(得分:0)

您无法跟踪用户尝试获得正确答案的次数。在while(!answerString.equals(rightAnswer)){...}中,您需要增加计数器的次数。

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

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