alright so im wondering how can I read an integer and string from the same line? Ill give an example: if I have input=3K how can I make my output look like this: 3K=3000?
2 Answers
Start by breaking down you requirements.
- You have an input value of [number][modifier]
- You need to extract the number from the modifier
- You need to apply the modifier to the number
If you want a variable/flexible solution, where you can supply any type of modifier, you will need to determine the number of digits the user has entered and then the modifier.
Once you have that, you can split the String, convert the digits to an int and apply the appropriate calculations based on the modifier...
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
int index = 0;
while (index < input.length() && Character.isDigit(input.charAt(index))) {
index++;
}
if (index >= input.length()) {
System.out.println("Input is invaid");
} else {
String digits = input.substring(0, index);
String modifier = input.substring(index);
int value = Integer.parseInt(digits);
switch (modifier.toLowerCase()) {
case "k":
value *= 1000;
break;
//...
}
System.out.println("Expanded value = " + value);
}
6 Comments
Kick Buttowski
can I ask for your help?
MadProgrammer
@KickButtowski What do you mean?
Kick Buttowski
can we talk in chat room plz?
Pshemo
@KickButtowski Why not post separate question for your question?
Pshemo
OK, so I will leave you two alone. Play nicely :)
|
String input = "3k";
String output = input.replaceAll("[Kk]", "000");
int outputAsInt = Integer.parseInt(output);
4 Comments
Pshemo
What if there are other
k in string which shouldn't be replaced?Kick Buttowski
@Pshemo it is a good point but I never saw 3kk, it is usually 3k
gger234
nah it was actually just like this it was supposed to be! thanks a lot, btw, String input should be "3K" and not "3k" as long as String output = input.replace("K", "000"); :)
gkrls
you are right. i updated the answer to cover both upper-lower case k and multiple k's
kwhich was placed before digit with000?String, strip of the non-numeric data and apply the required modify to the numeric component...replaceAllmethod, but I am not sure if you are interested in such solution.