gpt4 book ai didi

Java解析字符串输入

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:26 25 4
gpt4 key购买 nike

我在解析特定输入情况时遇到问题。我正在使用扫描类来处理这个问题。我尝试使用修剪功能,但似乎不起作用。我想解决这个问题的一种方法是使用正则表达式,但在这种情况下我该怎么做呢?还有其他解决方案吗?我遇到问题的输入是:

55, 34, 12, 1

55, 34,      12, 1

当我输入空格而不是连续的逗号时。

此输入将起作用:

55,34,12,1

我的代码:

public class Excercise3


{

public static double round(double value, int places)
{
if (places < 0) throw new IllegalArgumentException();

BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}


public static void main(String args[])
{

Scanner scan = new Scanner(System.in);
String test = scan.nextLine();
// String test = scan.next();
//test.trim();
String delims = "[,]";
String[] strarray = test.split(delims);


for (String str : strarray)
{

Integer numofWidgets = Integer.parseInt(str);

if (numofWidgets > 0 && numofWidgets <= 12)
{
System.out.print("The widgets will cost " + (round(((numofWidgets * 12.39) + 3), 2) + "\n"));
}
else if ( numofWidgets > 12 && numofWidgets <= 50 )
{
if (numofWidgets > 30 )
{
System.out.print("The widgets will cost " + (round(((numofWidgets * 11.99) + 5), 2) + "\n"));
}
else
{

System.out.print("The widgets will cost " + (round(((numofWidgets * 11.99) + 3), 2) + "\n"));
}
}
else if ( numofWidgets > 50)
{

System.out.print("The widgets will cost " + (round(((numofWidgets * 11.49) + 5), 2) + "\n"));
}


}
scan.close();

}



}

重要修复:

String test = scan.nextLine();

最佳答案

只需将它们分开

String delims = ",";        

并在解析之前使用trim()

Integer numofWidgets = Integer.parseInt(str.trim());

关于Java解析字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24747252/

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