I've tried searching a number of threads in terms of multiplying 2 strings. However, it seems that most of the links I found weren't applicable or I couldn't interpret them well enough.
Would it be possible if could tell me what is wrong with my current code?
public static void main(String[] args) {
String sample = value1();
String sample2 = value2();
//========== Test if users placed any characters within the boxes =========\\
try {
Integer.parseInt(sample);
} catch (NumberFormatException e) {
System.out.println("System detects that you are using characters");
return;
}
try {
Integer.parseInt(sample2);
} catch (NumberFormatException e) {
System.out.println("System detects that you are using characters");
return;
}
Integer.parseInt(sample);
Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
}
public static String value1() { //obtain first user input.
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample = value1();
}
return sample;
}
public static String value2() { //obtain second user input.
String sample2 = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample2.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample2 = value2();
}
return sample2;
}
}
My final output should multiply the following numbers
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
You can't multiply strings together. You can multiply numbers, and it sounds like that's what you want to do. Indeed, you're already parsing the strings as integers - and then ignoring the result. You just need to change this:
Integer.parseInt(sample);
Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
to:
int value1 = Integer.parseInt(sample);
int value2 = Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "
+ (value1 * value2) + ".");
See more on this question at Stackoverflow