Reading Characters from StdIn [closed]

老子叫甜甜 提交于 2019-12-13 11:27:14

问题


    public class New
    {
        public static void main(String[] args)
        {
            System.out.println("Calculator");

            float a = StdIn.readFloat(); 
            char sign = StdIn.readChar();
            float b = StdIn.readFloat();
            float c = 0;

            if (sign == '+')    c = a+b;
            else if (sign == '-')   c = a-b;
            else if (sign == 'x')   c = a*b;
            else if (sign == '/')   c = a/b;

            System.out.println(c);

        }
    }

I need some help with this bit of code, I'm attempting to make a calculator that takes StdIn input with both character and float data types.


回答1:


Try the Scanner class.

Like this:

import java.util.Scanner;

public class New
{

public static void main(String[] args)
{
    System.out.println("Calculator");

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter Parameter ");
    System.out.print("a      : ");
    float a = scanner.nextFloat();

    System.out.print("+|-|*|/: ");
    String op = scanner.next();

    System.out.print("b      : ");
    float b = scanner.nextFloat();
    float c = 0;

    switch (op)
    {
        case "+":
            c = a + b;
            break;

        case "-":
            c = a - b;
            break;

        case "*":
            c = a * b;
            break;

        case "/":
            c = a / b;
            break;

        default:
            System.out.println("Illegal operant");
    }

    System.out.println("Result: " + c);
}
}

I added a switch case instead of the else ifs.



来源:https://stackoverflow.com/questions/18688755/reading-characters-from-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!