Hi
Just started a basic programming course which uses Java. I use the Netbeans IDK for coding and running my programs. I'm only 1 week into the course but I want to get my head around the coding. I haven't done any Java programming before. Gotta start somewhere I guess.
My program is supposed to ask for the user's name, give a feedback message and then prompt the user for 2 integers which it will use to perform some basic arithmetic. The program should then print the output of the calculations.
I didn't seem to get any errors during the build and compile, but when I run it I get errors. Here's the code and output...
/* A program to ask user name and then calculate the sum, product, difference * and quotient of two integers defined by user */ import java.util.Scanner; public class Arithmetic { public static void main(String[] args) { String usersName; // The user's name as entered by user. String upperCaseName; // The user's name converted to upper case letters System.out.print("Please enter your name: "); Scanner input = new Scanner ( System.in ); usersName = input.next(); upperCaseName = usersName.toUpperCase(); System.out.println("Hi " + upperCaseName + ","); System.out.printf("%s\n%s\n", "This program will", "do some calculation for you!"); int number1; int number2; int sum; int product; int differencel; int differenceh; int quotient; System.out.print("Enter first number: "); number1 = input.nextInt(); System.out.print("Enter second number: "); number2 = input.nextInt(); sum = number1 + number2; System.out.printf( "Sum is %d\n", sum); product = number1 * number2; System.out.printf( "Product is %d\n", product); differencel = number2 - number1; differenceh = number1 - number2; if ( number1 == number2 ) System.out.println( "The difference is zero." ); if ( number1 < number2 ) System.out.printf( "The difference is %d\n", differencel ); if ( number1 > number2 ) System.out.printf( "The difference is %d\n", differenceh ); quotient = number1 / number2; System.out.printf( "Quotient is %d\n", quotient); } //end of method } //end of class
OUTPUT:
run:
Please enter your name: JN
Hi JN,
This program will
do some calculation for you!
Exception in thread "main" java.util.InputMismatchException
Enter first number: at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Arithmetic.main(Arithmetic.java:36)
Java Result: 1
BUILD SUCCESSFUL (total time: 9 seconds)
Am I close? How's my style? Is it too muddled? Any help or guidance is greatly appreciated. Cheers.