Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognizing spaces in java

Tags:

java

I'm a newb and I started out trying out some things, so I made a calculator that only required one line. It works when I do it in this format : Int space String space int. EG : 10 + 50. If I don't do spaces like 50+50 the program fails. Is there someway to recognise spaces in Java? Bare in mind that I'm a noob but I find that I did a great job that keeped me motivated. Here's teh code :

package Tests;

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.println("Enter your values : ");
    int first = input.nextInt();
    String character = input.next();
    int second = input.nextInt();
    int answer = 0;


    switch (character) {
    case "*":
        answer = first * second;
        break;
    case "/":
        answer = first/second;
        break;
    case "-":
        answer = first-second;
        break;
    case "+":
        answer = first+second;
        break;
    default:
        System.out.println("Failed to recognise character");
        break;

    }

    System.out.println("Answer : " + answer);
}
}
like image 863
user3022359 Avatar asked Mar 21 '23 13:03

user3022359


2 Answers

Scanner#next reads the next token from the input string based on whatever delimiter you have set for your Scanner object when you create it. The default delimiter is whitespace, so when you space out the operands and operator your program processes them correctly. You could set the delimiters for your Scanner as the operators.

Scanner input = new Scanner(System.in);
input.useDelimiter("\+|\-|\*|\\");

and your program will function properly.

like image 187
Hunter McMillen Avatar answered Apr 05 '23 23:04

Hunter McMillen


There are some convenience methods in Scanner that you're using now (i.e. nextInt()) but for your purpose you should probably just get the nextLine() and do some more complex parsing of the expression.

This is probably too much and I wouldn't make this my main focus right now if I were you, but eventually you may want to read up about formal languages and use tooling such as http://www.antlr.org/ for purposes like these.

like image 37
Sebastiaan van den Broek Avatar answered Apr 05 '23 23:04

Sebastiaan van den Broek