gpt4 book ai didi

Java 基本 CLI 计算器

转载 作者:行者123 更新时间:2023-12-01 09:35:08 27 4
gpt4 key购买 nike

我想制作一个用于基本数学运算的计算器。如果用户输入除/、*、-、+ 以外的任何其他字符,程序应退出。但用户只能输入其他字符才能退出。程序必须重新显示主菜单。我多次尝试只通过数学运算。但我想不出办法。

这是我的代码

package com.cv;

import java.util.Scanner;

class Q_04 {
public static double math(double x, double y, char a) {
if (a == '/') {
return x / y;
} else if (a == '*') {
return x * y;
} else if (a == '+') {
return x + y;
} else if (a == '-') {
return x - y;
}
return a;
}

public static void main(String[] argv) {
System.out.println(
"\t*:For multiplication\n\t/:For division\n\t+:For addition\n\t-:For substraction\n\tAny other character:To exit mathematical operation");
Scanner sc = new Scanner(System.in);
String z = sc.nextLine();
char a = z.charAt(0);
System.out.print("Enter Number 1: ");
double x = sc.nextDouble();
System.out.print("Enter Number 2: ");
double y = sc.nextDouble();
double result = 0;
System.out.println("Answer is " + math(x, y, a));
}
}

最佳答案

我不会敲代码,但我会写出总体思路。首先有一个 while 循环来获取运算符。如果操作符有效,则执行break;,否则将重复输入。只需这样做即可解决您的问题。其余的代码将随之而来。请注意范围(即在括号内声明变量)。

编辑:如果你想中断程序,只需添加一个if语句if (!(operator.equals("*") ||operator.equals("+") ...等。另外,if如果你真的想要好的设计,你可以使用哈希集来存储操作。

关于Java 基本 CLI 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39045914/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com