2

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.

Jerry Stratton
  • 2,699
  • 19
  • 25
Alexandre Krabbe
  • 557
  • 1
  • 5
  • 22

3 Answers3

3

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

Community
  • 1
  • 1
user3814613
  • 200
  • 1
  • 1
  • 9
  • The input isn't always made of 3 parts, sometimes it has 4 parts. What determines that is the String at the start of the input, if it is "SAQUE" or "DEPOSITO" than it will have more 2 parts (int and double). However, if the string is "TRANSFERENCIA" than it has more 3 parts (int, int and double) – Alexandre Krabbe Jul 10 '16 at 00:54
  • I can see the logic behind it, the problem is.. I'm debugging my program step by step and it reads the whole line as a String input, but when I do `String[] tokens = input.split("\\s+")` it doesn't split the string, i have access to the variables pannel and `tokens[0]` is the whole input. – Alexandre Krabbe Jul 10 '16 at 01:08
2
String[] s = scanner.nextLine().split(" ");

Then you'll have 3 strings:

  1. s[0] that'll return "DEPOSITO"
  2. s[1] returns "123"
  3. s[2] and it'll return "1000.00"

And now:

Integer i = Integer.parseInt(s[1]);
Double d = Double.parseDouble(s[2]);
DISSENNATORE
  • 109
  • 1
  • 11
1

you can parse value like this

   Scanner scanner = new Scanner(System.in);
    String array[] = scanner.nextLine().split("\\s");
    String strValue = array[0];
    int intValue = Integer.valueOf(array[array.length - 2]);
    int intValue1 = 0;
    double doubleValue = Double.valueOf(array[array.length - 1]);
    if ("TRANSFERENCIA".equalsIgnoreCase(strValue)) {
        intValue1 = Integer.valueOf(array[array.length - 3]);
    }
shivam
  • 480
  • 3
  • 12