Originally Posted by
Yes.
Hey, I'm having some problems a basic calculator that I'm messing about with in Java. Would be appreciated if some of you guys could give me some pointers as to where I'm going wrong...
import java.util.Scanner;
public class Calculator {
Scanner kybd;
kybd = new Scanner(System.in);
public void main(String[] args) {
String calcname = "Calculator";
System.out.println("Welcome to " + calcname + "please enter your name");
String name = kybd.readString();
System.out.println("Welcome. Press 1 to multiply and 2 to divide");
int choice = kybd.readInt();
choice = kybd.nextInt();
if (choice == 1) {
System.out.println("Enter your first number");
int num1 = kybd.readInt();
System.out.println("Enter your second number");
int num2 = kybd.readInt();
System.out.println(num1 + " times " + num2 + "equals" + num1 * num2 + ".");
} else if (choice == 2) {
System.out.println("Enter your first number");
int Dnum1 = kybd.readInt();
System.out.println("Enter your second number");
int Dnum2 = kybd.readInt();
System.out.println(Dnum1 + " divided by " + Dnum2 + "equals" + Dnum1 / Dnum2 + ".");
} else {
System.out.println("Please check your input");
}
}
}
Cheers!
Did you try static Scanner kbrd = new Scanner(System.in); ?
Also, did you have try and catch block in case it divides by zero?
Like
boolean isOk = false;
while (isOk == false)
{
try
{
num1 = kbrd.nextInt();
num2 = kbrd.nextInt();
num3 = num1/num2;
isOk = true;
}
catch (InputMismatchException imeRef )
{ // beginning of catch
String str ;
str = console.next();
System.out.println( "Enter a value"
+" that is an integer, i.e. not a decimal " +
"\n" + imeRef.toString());
} // end of catch
} // end of while