$29
This introductory assignment is designed to familiarize you with the mechanics of creating, compiling, and running a text-mode Java application. You do not need to hand this assignment in.
Compile and Run a Simple Java Program
You can use the JDK on the Linux host turing.cs.niu.edu (or hopper.cs.niu.edu). If you prefer, you may build and run this program in an IDE such as Eclipse, IntelliJ, or Netbeans. It’s still a good idea to at least familiarize yourself with the process of command-line compilation and execution on our Unix system since you’ll need to do that at some point this semester.
The source code below simply prompts for and accepts two numbers from the user, adds them, and displays the result. This is supplied so that you can go through the mechanics of editing, compiling and running a console-based Java program. You will not hand it in, but you should write (or at least copy and paste it) and run it.
Type in the program listed below using nano or another Unix editor (if you’re working on Unix), an IDE’s editor, or Notepad, Wordpad, or another ASCII editor (on Windows).
Save the file as Add.java
On Unix, compile it using the command:
javac Add.java
On Unix, run it using the command: java Add
Notes:
The file name Add.java is case-sensitive and should match the class name in the program below.
Details of the code will be covered in class in the first couple of weeks.
/**
Program to add two numbers... note that input is
accepted as a String and then an attempt is made
to convert it to a double for calculations. Non-
numeric input is detected by the Exception
mechanism and a default value is assigned to the
value.
*
Other methods of the Scanner class can read valid
ints, doubles, etc. with methods such as
nextDouble()...
*/
import java.util.Scanner;
public class Add {
public static void main(String[] args) {
String amountStr;
double num1,
num2,
total;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: "); amountStr = sc.next();
// Try to convert amount String to double for calculation
try {
num1 = new Double(amountStr).doubleValue(); } catch (NumberFormatException e) {
System.out.println("Bad numeric input; 1st num set to 100"); num1 = 100;
}
System.out.println("Enter the second number: "); amountStr = sc.next();
try {
num2 = new Double(amountStr).doubleValue(); } catch (NumberFormatException e) {
System.out.println("Bad numeric input; 2nd num is set to 50"); num2 = 50;
}
total = num1 + num2; System.out.println("Sum is: " + total);
}
}