[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 182
  • Last Modified:

Command line Java

In a effort to learn Java, how can one enter two numbers from command line user input followed by the addition of the two numbers?  
C:>javac Prog.java
22  <-- User inputs two numbers
4   <-- Program returns the sum of the two numbers.

Other things in Java appear to be easier than command line input.
0
vanuatu
Asked:
vanuatu
  • 3
  • 2
1 Solution
 
OviCommented:
import java.io.*;

public class test1 {

 public static int read() {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String line = "";
   try {
     line = br.readLine();
   } catch(Exception e) {}
   return(Integer.parseInt(line));
 }
 
 public static void write(String message) {
   System.out.print(message);
 }
 
 public static void main(String[] args) {
   write("First number: ");
   int n = read();
   write("Second number: ");
   int n1 = read();
   write("Result: " + (n + n1) + "\n");
 }
}
0
 
vanuatuAuthor Commented:
Ovi,

Could you explain what each line of code above
public static void main(String[] args) does?
0
 
OviCommented:
//imports classes to have access to IO operations
import java.io.*;

public class test1 {

// method for reading a line from jthe system inputStream. A line means an array of characters terminated with \n
 public static int read() {
   //creates a reader object to read from the inputStream
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  //will hold the readed content
   String line = "";
   try {
     //read a single line
     line = br.readLine();
   } catch(Exception e) {}
   //convert and return the readed string as a int value
   return(Integer.parseInt(line));
 }
 

//method for displaying messages to standard out
 public static void write(String message) {
//just write to system output
   System.out.print(message);
 }

// main method of the class, it specifies that this class is an "executable" one from operating system the command line.
 public static void main(String[] args) {
 //calls to methods for reading and writing
   write("First number: ");
   int n = read();
   write("Second number: ");
   int n1 = read();
   write("Result: " + (n + n1) + "\n");
 }
}
0
 
vanuatuAuthor Commented:
Thanks Ovi! :-)
0
 
OviCommented:
Any time.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now