Coded the following lines with the intent of inserting 2 values into a Dialog Box and have assigned to 2 different variables. Let's say I insert 22, it then should display as 2x2 = 4 in the textField, instead, it prints something like 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);
Classes involved:
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;
}
Results:
The function charAt(index)
returns a char, which you then implicitely parse into an int. The int value of '2' is 50, so it's 50 * 50 = 2500.
An easy fix would be to ask for an input format like A;B. Then you could do the following:
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
}