gpt4 book ai didi

java - 返回错误 int 值的变量

转载 作者:行者123 更新时间:2023-12-01 22:12:26 25 4
gpt4 key购买 nike

编写了以下几行代码,旨在将 2 个值插入到对话框中,并分配给 2 个不同的变量。假设我插入 22,那么它应该在文本字段中显示为 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.

最佳答案

函数 charAt(index) 返回一个 char,然后您可以将其隐式解析为 int。 '2' 的 int 值为 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
}

关于java - 返回错误 int 值的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58648938/

25 4 0
文章推荐: java - 在 Spring Boot Controller 中反序列化 json 时 List null