[英]Condensing basic code using || operator with a string
I'm quite new to java programming. 我是java编程的新手。 I was unable to find any information relating to the use of the ||
我无法找到有关使用||的任何信息 operator with strings.
运算符与字符串。 I was wondering if there was a more efficient way to do this code in particular that was still easily readable.
我想知道是否有更有效的方法来执行此代码,特别是仍然易于阅读。 I tried making a simple calculator as a way to familiarize myself with IfThenElse statements.
我尝试使用一个简单的计算器来熟悉IfThenElse语句。
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
double first;
double second;
String option;
while(true){
System.out.println("What function would you like to calculate?");
option=input.next();
if(option.equals("add") || option.equals("+")){
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double add=first+second;
System.out.println(add);
}
else if(option.equals("subtract") || option.equals("-")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double subtract=first-second;
System.out.println(subtract);
}
else if(option.equals("multiply") ||option.equals("*")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double multiply=first*second;
System.out.println(multiply);
}
else if(option.equals("divide") || option.equals("/")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double divide=first/second;
System.out.println(divide);
}
else if(option.equals("end")){
System.exit(0);
}
}
}
}
For the most part I am wondering about the if requirements, which I have tested and they do work, but it seems a bit clunky to me. 在大多数情况下,我想知道如果要求,我已经测试过它们确实有效,但对我来说似乎有点笨拙。 However, any critique would be greatly appreciated.
但是,任何批评都会受到高度赞赏。
Switch/case statements are a nice alternative to a series of ifs, and as of Java 7 you can use switch statements with strings. switch / case语句是一系列ifs的不错选择, 从Java 7开始,你可以使用带有字符串的switch语句。 Note the syntactical difference between the two.
注意两者之间的语法差异。 Instead of grouping things with curly braces, each case ends with a
break
statement. 每个案例都以
break
语句结尾,而不是用花括号分组。
switch (option) {
case "add":
case "+":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double add=first+second;
System.out.println(add);
break;
case "subtract":
case "-":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double subtract=first-second;
System.out.println(subtract);
break;
case "multiply":
case "*":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double multiply=first*second;
System.out.println(multiply);
break;
case "divide":
case "/":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double divide=first/second;
System.out.println(divide);
break;
case "end":
System.exit(0);
}
I would then suggest combining the duplicated prompt code. 然后我会建议组合重复的提示代码。 If you find yourself copying and pasting code it's usually a good idea to take a step back and figure out how you can avoid the repetition.
如果您发现自己正在复制和粘贴代码,那么退后一步并找出如何避免重复通常是一个好主意。 Duplicated code is a sign that you should do some refactoring.
重复的代码表明您应该进行一些重构。
if (option.equals("end")) {
System.exit(0);
}
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
switch (option) {
case "add":
case "+":
double add=first+second;
System.out.println(add);
break;
case "subtract":
case "-":
double subtract=first-second;
System.out.println(subtract);
break;
case "multiply":
case "*":
double multiply=first*second;
System.out.println(multiply);
break;
case "divide":
case "/":
double divide=first/second;
System.out.println(divide);
break;
}
Furthermore, you could also eliminate the duplicate printouts by using a single result
variable for all of the calculations. 此外,您还可以通过对所有计算使用单个
result
变量来消除重复的打印输出。
if (option.equals("end")) {
System.exit(0);
}
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double result;
switch (option) {
case "add": case "+": result = first + second; break;
case "subtract": case "-": result = first - second; break;
case "multiply": case "*": result = first * second; break;
case "divide": case "/": result = first / second; break;
}
System.out.println(result);
You're use of ||
你使用的是
||
seems fine to me. 对我来说似乎很好。 However I have a number of general suggestions to make the code better overall.
但是我有一些一般性的建议可以使代码整体更好。
First of all, why not have isAdd
, isSubtract
, etc. functions? 首先,为什么不具备
isAdd
, isSubtract
等功能? For example: 例如:
private boolean isAdd(String input){
return input.equalsIgnoreCase("add") || input.equals("+");
}
Same goes for the other operators. 其他运营商也是如此。 Than you can have code such as:
比你可以拥有如下代码:
if (isAdd(option)) ...
Which is more readable than 哪个更具可读性
if (input.equalsIgnoreCase("add") || input.equals("+")) ...
In a larger program, you might need to check these kinds of things more than once, and then having a method to do this becomes extra-handy. 在一个更大的程序中,您可能需要多次检查这些类型的东西,然后有一个方法来做这个变得非常方便。 Also, this way if you want to change the definition of "add" (for example now "a" also qualifies), you change code in one place and the whole program complies.
此外,这种方式如果您想要更改“添加”的定义(例如现在“a”也符合条件),您可以在一个地方更改代码并且整个程序符合要求。
Secondly, why not extract the bodies of these if
statements into other functions? 其次,为什么不将这些
if
语句的主体提取到其他函数中呢? Than your code would read like so: 比你的代码读的那样:
if (isAdd(option))
performAddition();
else if (isSubtract(option))
performSubtraction();
// .. etc
// function definitions here
Making for a much more readable program, as opposed to what you currently have. 制作一个更易读的程序,而不是你现在拥有的程序。
Thirdly, notice where you put your spaces. 第三,注意放置空间的位置。
option = input.next()
looks better than option=input.next()
. option = input.next()
看起来比option=input.next()
更好。
That's it pretty much. 这就是它。 Good luck :)
祝好运 :)
John Kugelman and Aviv Cohn both gave good advice. John Kugelman和Aviv Cohn都提出了很好的建议。 I would like to add that your application will throw an
InputMismatchException
if you don't enter a valid number at the call to nextDouble()
. 我想补充一点,如果你在调用
nextDouble()
没有输入有效数字,你的应用程序将抛出一个InputMismatchException
。 Instead of your program terminating because of the exception you can prompt the user to enter a valid number after which he/she can try again. 由于异常而不是您的程序终止,您可以提示用户输入有效的数字,之后他/她可以再试一次。
One way to do this is by adding the following methods to SimpleCalculator
: 一种方法是将以下方法添加到
SimpleCalculator
:
private static Double getValidNumber()
{
Double nr = null;
while( nr == null )
{
nr = getNextDouble();
if(nr == null) System.out.println("Please enter a valid number.");
}
return nr;
}
private static Double getNextDouble()
{
Scanner input=new Scanner(System.in);
Double output = null;
try{ output = input.nextDouble(); }catch(InputMismatchException e){}
return output;
}
Then in your main method, simply replace the calls to input.nextDouble()
by getValidNumber()
. 然后在main方法中,只需用
getValidNumber()
替换对input.nextDouble()
的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.