how to do what when typing in the console:
java -jar calculator.jar 3 + 7
immediately gave a response and did not require the program to run
listing my calculator.
import java.util.Scanner;
public class calculator {
private static Scanner read;
public static void main (String [] args) {
read = new Scanner (System.in);
double first;
double second;
String operator;
System.out.print ("& gt; & gt;");
first = read.nextDouble ();
operator = read.next ();
second = read.nextDouble ();
if (operator.equals ("*")) {
System.out.println ("=" + (first * second));
}
if (operator.equals ("/")) {
System.out.println ("=" + (first / second));
}
if (operator.equals ("+")) {
System.out.println ("=" + (first + second));
}
if (operator.equals ("-")) {
System.out.println ("=" + (first - second));
}
}
}
Update
From @Nofate’s hint, this is a crutch in the end. The only thing in the console is the line you need to enter without spaces.
java -jar calculator.jar 2 + 5
public class calculator {
public static void main (String [] args) {
String s = args [0];
char [] ch = s.toCharArray ();
String str1 = "";
String str2 = "";
String operator = "";
char charTmp = '';
int count = 0;
int countFirsDigit = 0;
int countSecondDigit = 0;
double x = 0;
double y = 0;
while (count & lt; ch.length - 1) {
char c = ch [countFirsDigit];
if (Character.isDigit (c)) {// check if a character is a number
String strTmp = Character.toString (c); // converting char to String
str1 = str1.concat (strTmp); // concatenation of a sequence of characters
x = Double.parseDouble (str1); // converting a string of numbers to double
countFirsDigit ++; // counter of the first number
count ++; // total counter
countSecondDigit ++; // counter of the second number
} else {
countSecondDigit ++;
count = countSecondDigit;
charTmp = c; // define the operator
operator = Character.toString (charTmp);
char c2 = ch [countSecondDigit];
if (Character.isDigit (c2)) {
String strTmp = Character.toString (c2);
str2 = str2.concat (strTmp);
y = Double.parseDouble (str2);
}
}
}
if (operator.equals ("*")) {
System.out.println ("=" + (x * y));
}
if (operator.equals ("/")) {
System.out.println ("=" + (x / y));
}
if (operator.equals ("+")) {
System.out.println ("=" + (x + y));
}
if (operator.equals ("-")) {
System.out.println ("=" + (x - y));
}
}
}
Answer 1, authority 100%
The args
array in the main (...)
method contains the command line parameters passed to the program at startup.
All you need to do is take them from there in order and convert them to the desired types.
first = Double.parseDouble (args [0]);
operator = args [1];
second = Double.parseDouble (args [2]);