gpt4 book ai didi

Java 字符串乘以 2 个整数

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

我尝试根据 2 个字符串相乘来搜索多个线程。然而,似乎我找到的大多数链接都不适用,或者我无法很好地解释它们。

是否可以告诉我当前代码有什么问题?

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;

}

}

我的最终输出应该乘以以下数字

System.out.println("您插入的总乘法为 "+sample * sample2+ ".");

最佳答案

不能将字符串相乘。您可以将数字相乘,听起来这就是您想要做的。事实上,您已经将字符串解析为整数 - 然后忽略结果。您只需要更改此:

 Integer.parseInt(sample); 
Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");

至:

 int value1 = Integer.parseInt(sample); 
int value2 = Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "
+ (value1 * value2) + ".");

关于Java 字符串乘以 2 个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28581449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com