I'm really a beginner Please tell us about the source code problem

Asked 2 years ago, Updated 2 years ago, 27 views

What I originally planned was to be like a very, very basic calculator

It is possible to calculate various formulas, but there is no program error.

If you enter the formula, the result will not come out and no value will come out.

I'd appreciate it if you could point out which part went wrong.

Example: If you enter 3 + 5 * 6 / 5, the result should come out

There's just a blank. Masters, please!

package main;

import java.util.Scanner;

public class Main4 {

public static void main(String[] args) {
    // // TODO Auto-generated method stub
    System.out.print ("Enter Formula");
    Scanner s = new Scanner(System.in);
    int x = s.nextInt();
    while(true)
    {
        String ops = s.next();
        if (ops == null)
        {
            break;
        }
        char op = ops.charAt(0);
        int y = s.nextInt();
        int z = 0;
        switch(op)
        {
        case '+':
            x += y;
            break;
        case '-':
            x -= y;
            break;
        case '*':
        x *= y;
        break;
        case '/':
        x /= y;
        break;
        case '%':
        x %=y;
        break;
        default:
            System.out.println ("Input Error");

        }
    }
        System.out.println(x);
    }

}

java

2022-09-22 19:36

1 Answers

Did you enter "3 + 5 * 6 / 5" at once?

Looking at the code, you have to enter only one letter at a time after entering '3', '+', and then '5'.

You said you didn't get any results and no value, but the program probably stopped waiting for input.

We recommend that you kindly write a notice with a print statement for each part you receive. :)


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

    System.out.print ("Enter the first digit");
    int x = s.nextInt();

    System.out.print ("Enter Operator");
    String ops = s.next();

    System.out.print ("Enter a second digit");
    int y = s.nextInt();

    if (ops == null){
        System.out.print ("No operator");
        return;
    }
    char op = ops.charAt(0);
    switch(op) {
        case '+':
            x += y;
            break;
        case '-':
            x -= y;
            break;
        case '*':
            x *= y;
            break;
        case '/':
            x /= y;
            break;
        case '%':
            x %=y;
            break;
        default:
            System.out.println ("Input Error");
    }
    System.out.println(x);
}


2022-09-22 19:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.