Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial<noob />
17,062 PointsCalculator program in java
Hi, im trying to program a simple Calculator program with java.. craig dosent explain alot of the things i did here, they are from google. here is the code :
import java.io.Console;
public class Calculator {
public static void main(String[] args) {
Console console = System.console();
console.printf("Welcome to the calculator program! \n");
String name = console.readLine("Enter your username: ");
console.printf("Hello, %s!\n", name);
while(true){
try
{
String numberAsString = console.readLine("Please enter a number : ");
int number = Integer.parseInt(numberAsString);
String operation = console.readLine("Please enter an operation +/-/*/ : ");
String numberTwoAsString = console.readLine("Please enter another number: ");
int number2 = Integer.parseInt(numberTwoAsString);
if(operation.equals("+"))
{
console.printf("The result is " + (number+number2));
}
else if(operation.equals("-"))
{
console.printf("The result is " + (number-number2));
}else if(operation.equals("*"))
{
console.printf("The result is" + (number*number2));
}
}
catch(NumberFormatException e)
{
console.printf("U have entered invalid input, Try again..\n ");
continue;
}
String choice = console.readLine("Do u want to make a calculation again? Press Y or N\n");
if(choice.equalsIgnoreCase("N"))
{
break;
}
else
{
continue;
}
}
}
}
I have few questions:
- i am struggling to block users to enter valid operations. 2.Any best practices with the code?
thanks