Reputation: 1605
I'm having problem parsing a particular input case. I'm using scanning class to deal with this. I tried using trim function but didn't seem to work. I guess one way to go about this is to use a Regular expression but how would I do that in this case? Any other solutions? The input I am having a problem with is :
55, 34, 12, 1
or
55, 34, 12, 1
Its when I put an input of spaces and not continuous commas.
This input will work:
55,34,12,1
My Code:
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();
}
}
Important fix:
String test = scan.nextLine();
Upvotes: 0
Views: 12968
Reputation: 66
You can also try replacing all the space in the string with
test = test.replace(" ","");
before splitting with split()
method
This should transform your input in this way
55, 34, 12, 1 ---> 55,34,12,1
Upvotes: 0
Reputation: 240870
just split them by
String delims = ",";
and before parsing into it use trim()
Integer numofWidgets = Integer.parseInt(str.trim());
Upvotes: 1