Alexandre Krabbe Alexandre Krabbe - 1 year ago 49
Java Question

How to read a String followed by an int in Java?

I've been struggling to get this done. What I need is to read a input like this:

DEPOSITO 123 1000.00
, but the String "DEPOSITO" needs to be saved in one variable, the int "123" to another variable and the double "1000.00" to another variable. The problem is that I couldn't find anything like
scanner.nextString()
, if I could scan just the string into a variable, I probably could scan the rest of the input stream with
scanner.nextInt()
and
scanner.nextDouble()
. If I do
scanner.next()
on a attempt to read only the string, it reads the whole line, so what is the answer to my problem here? I'm really clueless.

Answer Source

Since the input always begins with a string, you could get the string first, and then determine how many variables there are after it based on that:

String input = scanner.nextLine();

// use regex to split string
String tokens = input.split("\\s+");

String firstPart = tokens[0];

int intPart = 0;
double doublePart = 0;
int transferenciaInt = 0;

if(firstPart.equals("SAQUE") || firstPart.equals("DEPOSITO"))
{
    intPart = Integer.parseInt(tokens[1]);
    doublePart = Double.parseDouble(tokens[2]);
}
else
{
    intPart = Integer.parseInt(tokens[1]);
    transferenciaInt = Integer.parseInt(tokens[2]);
    doublePart = Double.parseDouble(tokens[3]);
}

For more information on regular expressions (regex) see this: Learning Regular Expressions