如何参考我的代码使用 SCANNER reader 严格允许一个字符作为输入?

How to strictly allow exactly ONE char as input using SCANNER reader with reference to my code?

下面的代码适用于具有四个基本数学运算符的简单计算器。这是一个工作程序,它按预期工作。但是,我有几个问题需要理解和改进我的程序以及我对 Java 的理解。 (我使用过 google,但冗余信息的数量让我感到困惑,并且在 Whosebug 上也没有找到任何完美的答案,尽管有许多相关问题。相信我,我在发帖之前确实尝试过)。

  1. 如何确保用户输入的是一个字符? 在我的程序中,它接受多个字符 (+-*) 但仅对第一个字符 (+) 进行操作。我想确保不接受超过一个字符作为输入。

  2. 程序执行成功后,如何让用户重复main方法?我的意思是,用户将两个数字相加,得到他的答案,然后他想进行另一次计算,这次可能是将两个数字相乘。我可以询问用户是或否以继续,但如何让 him/her 回到开头? (循环会工作吗?如何工作?)

  3. A程序结束我用了两种方法来输出一条消息。 system.out.print 工作正常,但 JOptionPane 方法不显示消息并且程序不终止(我已将其注释掉)。我想明白为什么?

  4. 开关中是否需要默认大小写?我是否遵循正确的代码结构? (花括号的排列和使用)

注意:正如我所说,这个计算器工作正常,像我这样的新手可以使用它来更好地理解这个概念,因为我已经对每个细节进行了评论。请理解,由于限制,我无法在问题标题中添加所有内容...

package mycalculator;

import javax.swing.JOptionPane;
import java.util.*;
public class MyCalculator{
public static void main (String [] args){
        // Let us code a simple calculator//

// Variable type declarations//          
  char OP;
  int firstNum; 
  int secNum;         

// Display an explanation of what this program does//
    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);

// Ask user to input any positive number and read it//
    System.out.println("Enter Any positive number followed by pressing 
    ENTER.");
    firstNum = input.nextInt();

// Ask user to input/decide his choice operator and read it //
    System.out.println("Enter a valid OPERATOR sign followed by pressing 
    ENTER.");
    OP = input.next().charAt(0);  

// Loop the below statement till one of the four (+,-,*,/) is entered.// 
    while(OP != '+' && OP != '-' && OP != '*' && OP != '/'){
        System.out.println("Please Re-enter a valid Operator (+,-*,/)");
        OP = input.next().charAt(0);}

// Ask user for any second number and read it//
   System.out.println("Enter your Second number followed by an ENTER 
   stroke.");
   secNum = input.nextInt();

// Various possible Resolution based on OP value.//
   int RSum = firstNum+secNum;
   int RSubs= firstNum-secNum;
   int RPro = firstNum*secNum;
   double DPro = firstNum/secNum;

// Conditional statements for Processing Results based on OP and display.//
    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;
//Maybe the default case is actually not needed but is added for totality//
  default : System.out.println("Try Again");
    break;
    }

// The following code maybe deleted, it is for experimental purpose//
// Just checking if additional statements executes after a program 
   completes//
    System.out.println("Test Message ");
//  JOptionPane.showMessageDialog(null, "The Process Ends Here!");
//The test message works fine//    
//The JOptionPane statement don't work and program doesn't end. WHY?//         
   }           
 }

1) 您可以检查字符串 input.next() 的大小。如果是一个,则继续,否则再次提示操作员选择。

2)我建议最好创建一个不同的方法并将所有逻辑放入其中,并根据需要调用它的次数或调用无限次。

4)Should switch statements always contain a default clause?

How can I make sure that the user input is exactly and strictly one char? here in my program, it accepts more than one character (+-*) but operates on the first char (+) only. I want to make sure more than one character is not accepted as input.

如果您使用控制台应用程序和 Scanner,您唯一能做的就是读取 String 并检查其长度。如果您使用 Swing,您可以实施 KeyPressListener 并在用户按下按钮后立即继续(但不适用于控制台应用程序)。

After successful execution of the program, how can I somehow let the user repeat the main method? I mean, a user adds two numbers, gets his answer and he wants to do another calculation, maybe multiply two numbers this time. I can ask the user for yes or no to continue but how do I take him/her back to the beginning? (will a loop work? how?)

您不能重复 main 方法。在 Java main 方法只执行了一次。要重复您的代码,您可以将整个 main 方法内容包装到无限循环或将内容移动到单独的方法并从 main 方法的循环中调用它。

A the end of the program I used two methods to output a message. The system.out.print works fine but the JOptionPane method doesn't display the message and the program doesn't terminate (I have commented it out). I would like to understand why?

JOptionPane 仅适用于图形应用程序 (Swing/AWT)。这在控制台中不可用。你那里只有标准输入和输出。

Is the default case required in the switch? And Am I following the correct code structure? (the arrangements and uses of curly braces)

否,default 大小写 JVM 语法 是可选的。我记得,例如在 C++ 中,建议放置它(事件为空),以排除编译器的副作用。我不知道 Java 中是否有这样的推荐,但是当我使用 switch 时,我更喜欢总是添加它以排除逻辑问题(但这绝对是 根据语法可选 例)。您正确使用 switch

public static void main(String[] args) {
    System.out.println("This is a simple calculator that will do basic calculations such as :"
            + "\nAddition (+)"
            + "\nMultiplication (*)"
            + "\nSubtraction (-)"
            + "\nDivision (/)");

    System.out.println();

    try (Scanner scan = new Scanner(System.in)) {
        while (true) {
            System.out.println("Enter Any positive number followed by pressing ENTER.");
            int first = scan.nextInt();

            System.out.println("Enter a valid OPERATOR (+,*,-,/) sign followed by pressing ENTER.");
            String operator = scan.next();

            while (operator.length() != 1 || !"+*-/".contains(operator)) {
                System.out.println("Please Re-enter a valid Operator (+,-*,/)");
                operator = scan.next();
            }

            scan.nextLine();
            System.out.println("Enter your Second number followed by an ENTER stroke.");
            int second = scan.nextInt();

            if ("+".equals(operator))
                System.out.println("The Resulting sum is " + (first + second));
            else if ("*".equals(operator))
                System.out.println("The Resulting mul is " + (first * second));
            else if ("-".equals(operator))
                System.out.println("The Resulting sub is " + (first - second));
            else if ("/".equals(operator))
                System.out.println("The Resulting div is " + ((double)first / second));

            System.out.println();
            System.out.println("Do you want to exit ('y' to exit)?");

            if ("y".equals(scan.next()))
                return;

            System.out.println();
        }
    }
}