Style
Your structure for this program is fine, except one bug highlighted below below. However, from first glance, you can make some style adjustments to increase the readability of your program. Coding conventions are extremely important - and although things like "do I put brackets on the same line or a new line?" are convtroversialcontroversial, it is essential that you write clean and readable code. A little spacing never hurt anybody, but it should be consistent and clean.
float num2= input.nextFloat();
Put a space before the equal sign.
String Operation = input.next();
Variable names should typically be lower camel case. Operation
is actually a class from the java.rmi.server library, so you should rename this to simply operation
.
case "division":
if (num1 == 0 || num2 == 0) ;
{
System.out.println("You can not divide by or with a zero!");
}
There should not be a semi-colon after the if-statement. This is causing wrong output! Line up your brackets. Also, why can't you divide 0? 0 / 5
is a perfectly valid operation.
You can clean this up simply by using the following
case "division":
if (num2 == 0)
System.out.println("You cannot divide by zero!");
else
System.out.println(num1 / num2);
break;
You could also keep the brackets if you wish. If the statement contains only one inner statement, you don't need brackets, but some people prefer it for the readability. This is a personal style.
case "division":
if (num2 == 0) {
System.out.println("You cannot divide by zero!");
} else {
System.out.println(num1 / num2);
}
break;
If you really want to trim it down, you can use the ternary operator ?
.
case "division":
System.out.println(num2 == 0 ? "You cannot divide by zero!" : (num1 / num2));
break;
Once you've done that, challenge yourself by getting yourself familiar with reading input files, so you don't have to type your input every time! You could try experimenting with a BufferedReader
for example.