我有这段简短的代码片段,我必须在其中检查一个字符串以查看它是否包含整数和可能的小数。该字符串是金额(12.34)
,因此它也不能超过第四个索引。
我的问题是我被告知要使用 charAt()
(在我的代码中我使用了 matches()
和 contains()
这是错误的)来检查整数和小数,这样这个例程将返回一个 boolean 值,如果字符串与这些参数一起工作,则该值为真,但是我很困惑如何将其转换为使用 charAt()
而不是 matches()
和 contains()
。
另外,如果我的格式有误,措辞有误,或者代码看起来很糟糕,我很抱歉,我正在学习 Java 的第一个学期,这是我上过的第一门编程课,所以我有点粗糙。
import java.util.Scanner;
public class Auction
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if(price.matches("[0-9]*") && price.length() <= 5)
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else if(price.matches("[0-9]*") && price.length() <= 5 && price.contains("."))
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else
{
System.out.println("Invalid input");
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if(quantity.contains("."))
{
System.out.println("Invalid input");
}
}
}
最佳答案
我正在用手机打字。所以请原谅错误。您的教授是否要求您使用 charAt 而不是正则表达式和匹配项?
if (inpString!= null && !inpString.isEmpty () && inpString.length() <= 5){
int periodCount = 0;
for (int i=0; i < inpString.length (); i++){
char c = inpString.charAt (i);
if (c == '.'){
periodCount++;
}else if (c >= '0' && c <= '9'){
}else {
System.out.println("invalid output");
break;
}
if(periodCount > 1){
System.out.println("too may periods. Invalid output");
break;
}
}
}else {
System.out.println ("invalid input");
}
如果您需要检查是否没有千位,即 1.234,您能评论一下吗?如果是,请确保
inpString.substring
(inpString.lastIndexOf
(".")).length < 3
所有的 null 和 indexOutOfBounds 检查
关于java - 验证数字和句点/小数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33716455/