1

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?

5
  • 1
    Replace k which was placed before digit with 000? Commented Sep 11, 2014 at 23:20
  • and how do I do that? Commented Sep 11, 2014 at 23:22
  • Read it as a String, strip of the non-numeric data and apply the required modify to the numeric component... Commented Sep 11, 2014 at 23:25
  • I guess with (int) Ill atleast get 3, no? but im not sure what to do with the k :/ Commented Sep 11, 2014 at 23:25
  • I would use regex and replaceAll method, but I am not sure if you are interested in such solution. Commented Sep 11, 2014 at 23:27

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

can I ask for your help?
@KickButtowski What do you mean?
can we talk in chat room plz?
@KickButtowski Why not post separate question for your question?
OK, so I will leave you two alone. Play nicely :)
|
0
String input = "3k";

String output = input.replaceAll("[Kk]", "000");

int outputAsInt = Integer.parseInt(output);

4 Comments

What if there are other k in string which shouldn't be replaced?
@Pshemo it is a good point but I never saw 3kk, it is usually 3k
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"); :)
you are right. i updated the answer to cover both upper-lower case k and multiple k's

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.