变量返回错误的int值

时间:2019-10-31 17:58:17

标签: java oop variables joptionpane netbeans-8

对以下各行进行了编码,目的是在对话框中插入2个值,并已分配给2个不同的变量。假设我插入22,然后它将在textField中显示为2x2 = 4,相反,它显示的内容类似于50 x 50 = 2500。

String a = JOptionPane.showInputDialog("Qual cálculo deseja fazer? (AB = A x B)", "AB");

   aNum = a.charAt(0);
   bNum = a.charAt(1);
   int cNum = aNum*bNum;

    Game.getNumbers(aNum, bNum);

    JOptionPane.showInputDialog(aNum, bNum);

    TF1.setText(Game.First() +" x "+ Game.Second() +" = "+ cNum);

涉及的课程:

public class Game1 {

private int first = 0;
private int second = 0;
private int score = 0;
private int hiScore = 0;


public void numTotalCheck(int a){

    String option1 = null;
    char option = 0;

    do{
    if (a == (first*second)){

        JOptionPane.showMessageDialog(null, "Parabéns. Você acertou!");

        score = score + 100;
        if(score > hiScore){

            hiScore = score;
        }
    }else{

        score = score - 100;
        if(score > hiScore){

            hiScore = score;
        }
        JOptionPane.showMessageDialog(null, "Errado!");

        option1 = JOptionPane.showInputDialog("Deseja jogar novamente? <S/N>");
        option = option1.charAt(0);
    }
    }while((option == 's') || (option == 'S'));


}

public void getNumbers(int a, int b){

    first = a;
    second = b;
}

public int First(){

    return first;
}

public int Second(){

    return second;
}

结果:

Result of "22" input.

2 个答案:

答案 0 :(得分:0)

您正在将字符(char)视为数字(integer)。这是一个隔离您所看到的内容的示例。

此代码采用String值“ 2”并从中获取一个字符,然后打印该字符。

char c = "2".charAt(0);
System.out.println("c: " + c);

--> c: 2

如果您尝试相同的操作,但是将结果存储为int,则存储的值不是相同的,而是“ 50”:

int i = "2".charAt(0);
System.out.println("i: " + i);

--> i: 50

在幕后,任何字符值都用数字表示,因此字符“ 2”是整数50。您可以挖掘ASCII图以了解它们的映射方式。

有很多方法可以修复您的代码,但是由于您已经以字符串值开头,因此,获得正确结果的一种方法是使用Integer.parseInt(),如下所示:

int parsedValue = Integer.parseInt("2");
System.out.println("parsedValue: " + parsedValue);

--> parsedValue: 2

答案 1 :(得分:0)

函数charAt(index)返回一个char,然后将其隐式解析为int。 int值'2'是50,所以它是50 * 50 = 2500。

一个简单的解决方法是要求输入格式为A; B。然后,您可以执行以下操作:

String s =JOptionPane.showInputDialog("Enter two numbers like this: Number A;Number B", "AB");
String[] temp = s.split(";");
if(temp.length == 2) {
  try {
    int aNum = Integer.parseInt(temp[0]);
    int bNum = Integer.parseInt(temp[1]);
    int cNum = aNum*bNum;
  } catch(NumberFormatException nfe) {
    // One or both of the values weren't ints.
  }
} else {
  // Some error here, because of too few/ too many values
}