我在Java方面遇到了问题。我正在尝试检查提供的输入是否只包含十进制数字(数字和一个“。”)这段代码由我的教授提供,它并没有真正评估。我真的无法弄清楚出了什么问题。
import javax.swing.JOptionPane;
public class MoneyCount {
public static void check(String s) {
boolean decimalPoint = false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.') {
if (!decimalPoint) {
decimalPoint = true;
}
} else {
JOptionPane.showMessageDialog(null,
"You must enter an integer value");
System.exit(0);
}
}
}
public static void main(String[] args) {
//retrieve amount due
String moneyd = JOptionPane.showInputDialog("Enter the amount due");
check(moneyd);
double amountd = Double.parseDouble(moneyd) * 100;
String moneyr = JOptionPane.showInputDialog("Enter amount you would like to pay");
check(moneyr);
double amountr = Double.parseDouble(moneyr) * 100;
}
}
答案 0 :(得分:1)
问题是弄清楚你教授的代码有什么问题或编写自己的方法吗?
如果是前者,我还会指出错误信息的意图应该是“你必须输入一个十进制值”。
答案 1 :(得分:0)
尝试像这样更改您的代码
public static void check(String s) {
boolean decimalPoint = false;
for (int i = 0; i < s.length();i++) {
if (s.charAt(i) == '.') {
if (!decimalPoint) {
decimalPoint = true;
}else{
JOptionPane.showMessageDialog(null,
"Not a valid number (contains more than one .)");
System.exit(0);
}
}
}
if (decimalPoint) {
{
JOptionPane.showMessageDialog(null,
"You must enter an integer value");// you need only integer as input
System.exit(0);
}
}
}
只有在检查整个字符串后才能显示消息。 那是在完成循环之后
答案 2 :(得分:0)
从桌面检查开始(哦,亲爱的主人,我从未想过我会再说一遍)......
基本上所有这个方法都会检查s
是否包含多个.
个字符
从s
开始等于123.123
decimalPoint
= false
i
= 0
时,s.charAt(i)
将为1
。i
= 1
时,s.charAt(i)
将为2
。i
= 2
时,s.charAt(i)
将为3
。i
= 3
时,s.charAt(i)
将为.
。decimalPoint
为false
,将decimalPoint
更改为true
i
= 4
时,s.charAt(i)
将为1
。i
= 5
时,s.charAt(i)
将为2
。i
= 6
时,s.charAt(i)
将为3
。从s
开始等于1.2.3
decimalPoint
= false
i
= 0
时,s.charAt(i)
将为1
。i
= 1
时,s.charAt(i)
将为.
。decimalPoint
为false
,将decimalPoint
更改为true
i
= 2
时,s.charAt(i)
将为2
。i
= 3
时,s.charAt(i)
将为.
。decimalPoint
为true
,显示错误消息并退出从s
开始等于123
decimalPoint
= false
i
= 0
时,s.charAt(i)
将为1
。i
= 1
时,s.charAt(i)
将为2
。i
= 2
时,s.charAt(i)
将为3
。decimalPoint
是false
因此,唯一一个中断的案例是第二个......请注意,此方法没有考虑输入字母字符时可能出现的情况......但这不是它为...而设计的......
答案 3 :(得分:0)
您可以使用try和catch来验证字符串是否为小数,或者不像上面的代码:
public static void check(String s) {
try {
Integer.parseInt(s);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"You must enter an integer value");
System.exit(0);
}
}
答案 4 :(得分:0)
检查一下
公共课测试{
public static void main(String[] args) throws ParseException {
String moneyd = JOptionPane.showInputDialog("Enter the amount due");
if (check(moneyd)) {
double amountd = Double.parseDouble(moneyd) * 100;
System.out.println("ok");
} else {
System.out.println("Not a valid number");
System.exit(0);
}
}
public static boolean check(String s) {
boolean decimalPoint = false;
for (int i = 0; i < s.length(); i = i + 1) {
if (s.charAt(i) == '.') {
if (!decimalPoint) {
decimalPoint = true;
} else {
return (false);
}
}
}
return true;
}
}
答案 5 :(得分:0)
“它没有真正评估”是什么意思。
我理解代码的方式: