需要帮助来了解有关 While 循环条件语句和类型转换的一些基本 Java 概念

我只是想编写一个简单的计算器,它工作正常......


我现在要做的是包含一个“do while”或“while”循环来重复一个语句,直到用户输入四个基本操作符之一。我已经使用其他方法(if 和 switch)实现了它,但我想简化它。


此外,我在学习如何解析字符scanner和JPane方法时遇到了很多问题。我可以使用互联网上的各种资源来实现,但是一个简单的方法可以帮助我更清楚地理解逻辑,而不仅仅是实现将受到高度赞赏......


    public class MyCalculator{

    public static void main (String [] args){


    // Let us code a simple calculator

    char OP;

    System.out.println("This is a simple calculator that will do basic calculations such as :\nAddition, Multiplication, Substraction and Division.");


    // Create a scanner object to Read user Input.

    Scanner input = new Scanner(System.in);


    System.out.println("Enter Any positive number followed by pressing ENTER.");

    int firstNum = input.nextInt();


    // Need to Loop the below statement till one of the four (+,-,*,/) operator is entered.


    System.out.println("Enter your choice of OPERATOR sign followed by pressing ENTER.");

    OP = input.next().charAt(0);


    System.out.println("Enter your Second number followed by an ENTER stroke.");

    int secNum = input.nextInt();


    // Various possible Resolution

    int RSum = firstNum+secNum;

    int RSubs= firstNum-secNum;

    int RPro = firstNum*secNum;

    double DPro = firstNum/secNum;


    // Conditional statements for Processing

    Switch (OP){ 

    case '+': System.out.println("The Resulting sum is "+ RSum);

    break;

    case '-': System.out.println("The Resulting sum is "+ RSubs);

    break;

    case '*': System.out.println("The Resulting Product is "+ RPro);

    break;

    case '/': System.out.println("The Resulting Divisional product is "+ DPro);

    break;

    default : System.out.println("Try Again");


        }


    }

}


DIEA
浏览 116回答 1
1回答

长风秋雁

你可以使用这样的东西:while(scanner.hasNext()) {&nbsp; //some code&nbsp; &nbsp;int number = scanner.NextInt();}但我会实现一个计算器如下:int num1 = scanner.NextInt();String op = scanner.Next();int num2 = scanner.NextInt();您可以按如下方式遍历字符串并进行检查:for (char ch : exampleString.toCharArray()){&nbsp; System.out.println(ch);}您还可以按如下方式循环字符串:for (int i=0; i<examplestring.length(); i++) {&nbsp; char c = examplestring.charAt(i);}您可以循环直到获得 + 或 - ,如下所示:char operator;&nbsp; &nbsp;&nbsp;do {&nbsp; char operator = scanner.next().get(0);}while(operator != '+' || operator != '-')您可以循环和打印错误消息,如下所示:char operator;do {&nbsp; char operator = scanner.next().get(0);&nbsp; if(!isValidOperator(operator)) {&nbsp; &nbsp; System.out.println("invalid operator");&nbsp; }}while(!isValidOperator(operator))public boolean isValidOperator(char operator) {&nbsp; if(operator == '+') {&nbsp; &nbsp; return true;&nbsp; } else if (operator == '-') {&nbsp; &nbsp; return true;&nbsp; }&nbsp; return false;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java