IMJensen IMJensen - 1 month ago 4x
Java Question

User input sorted into two arrays, double and string

My goal is too make a simple calculator. I have already made one that can take two values and either add, subtract etc, but I want too try and make one that can read user input like this:

2 + 3
and also
3 * 4 + 5 / 2
, as examples. I'm taking an introduction course in programming.

So user input decides how many values and how many operations (rules of precedence is not accounted for).

I thought that maybe I could feed user input directly into two arrays using a while loop with an if else if inside. In pseudo code,

while (input is not quit)
if input is a value, put in value array
if input is symbol, put in symbol array

So far I've written this:

public static void main(String[] args){
Scanner sc = new Scanner(;
String input = "";
Double[] values = new Double[10];
String[] symbols = new String[10];
int v = 0;
int s = 0;

while (!input.equals("q")) {
input = sc.nextLine();
if (sc.hasNextDouble()) {
values[v] = Double.parseDouble(input);
} else {
symbols[s] = input;

Test run is like this:

[2.0, 2.0, null, null, null, null, null, null, null, null]
[2, a, b, s, q, null, null, null, null, null]

I kind of can see how I need too press q twice, but I don't understand why one of the twos goes in the string-array.

If I try two enter a number after I've entered a character I get an exception and program exits.

Thanks for replies!


Your test for which way to process the input looks ahead at the next input to make its decision, so your value in input and your test are out of phase. I'd suggest something like this:

bool done = false;
while (!done) {
    if (sc.hasNextDouble()) {
        values[v] = Double.parseDouble(sc.nextLine());
    } else {
        symbols[s] = sc.nextLine();
        if (symbols[s].equals("q")) done = true;

I'm not sure why you want to capture "q" in your array, but since that's how you did your code, I've done that here as well. You could keep it out of the array by making a small change to the else block.