Question:
JAVA how to use scanner to detect *SPECIFIC* user input in command line?
Abdul Ahmad
2013-11-15 06:53:54 UTC
for example, i have a calculator program that runs on command line. When i do:
java MyCalculatorProgram 10 x 10
i get the result (100.00),
what my program does is see if the user input includes a number, followed by a math sign, followed by another number. and depending on the math sign (+, -, /, x) it will do the right math operation to give the right result...
so MyCalculatorProgram 10 / 10 would give 1 (this is all command line)
and MyCalculatorProgram 10 + 10 would give 20 etc...
however, I dont know how to make this happen using a scanner... Im really new to java so im still learning things on my own. one thing i want to avoid is having to pass arguments through code and compile the code everytime i want to do a math operation... anyways... heres a copy of the code if anyone is interested (if you have suggestions to make the code better i would be very thankful and more than happy to learn);

public enum MathFunctions1_0 {
MULTIPLY, DIVIDE, ADD, SUBTRACT
}

public class MathCalculatorTest2_0 {
MathFunctions1_0 mathFunction1;
public MathCalculatorTest2_0 (MathFunctions1_0 mathFunction1) {
this.mathFunction1 = mathFunction1;
}

public void DoMath(double digit1, double digit2) {
double mathResult = 0;
switch (mathFunction1) {
case MULTIPLY:
mathResult = digit1*digit2;
break;
case DIVIDE:
mathResult = digit1/digit2;
break;
case ADD:
mathResult = digit1+digit2;
break;
case SUBTRACT:
mathResult = digit1-digit2;
break;
default:
System.out.println("Incorrect arithmatic character, please insert a correct arithmatic character between the two numbers (x, /, +, -)");
}
System.out.println(mathResult);
}

public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Please correct syntax");
} else {
double firstDigit = Double.parseDouble(args[0]);
String userInput1 = args[1];
double secondDigit = Double.parseDouble(args[2]);
MathCalculatorTest2_0 C;
switch (userInput1) {
case "x":
C = new MathCalculatorTest2_0(MathFunctions1_0.MULTIPLY);
C.DoMath(firstDigit, secondDigit);
break;
case "/":
C = new MathCalculatorTest2_0(MathFunctions1_0.DIVIDE);
C.DoMath(firstDigit, secondDigit);
break;
case "+":
C = new MathCalculatorTest2_0(MathFunctions1_0.ADD);
C.DoMath(firstDigit, secondDigit);
break;
case "-":
C = new MathCalculatorTest2_0(MathFunctions1_0.SUBTRACT);
C.DoMath(firstDigit, secondDigit);
break;
default: System.out.println("Please insert correct arithmatic character.");
}
}
}
}
Three answers:
husoski
2013-11-15 07:46:55 UTC
The best way to get details on the standard Java classes is that the official API doc pages. For Scanner, see:



http://docs.oracle.com/javase/7/docs/api/index.html?java/util/Scanner.html



At first, this may be difficult reading. Scroll down to the "Constructor Summary" and you'll find a lot of ways to create a Scanner object, but they really boil down to:



new Scanner(source)



...where "source" is an opened input file or device, a File or Path object that identifies a file by name (to be opened by the scanner), or a string. Scanning strings makes a lot of interesting things easy. For example, simulating multiple "command lines" can be done with:



static String[] stringToTokens(String input) {

.... java.util.ArrayList tokens = new java.util.ArrayList();

.... java.util.Scanner scan = new java.util.Scanner(input);

.... while ( scan.hasNext() ) {

.... .... tokens.add( scan.next() );

.... }

.... return scan.toArray( new String[1] );

}



That uses the ArrayList class to handle the details of creating a variable-length list of strings and then convert the final result to a fixed-length array of Strings, very much like the args[] array passes to main().



One way to use that is to put your "business" logic into it's own static method (not main()) and have main do:



.... java.util.Scanner sysin = new java.util.Scanner( System.in );

.... while (true) { // loop until user enters "quit"

.... .... String line = sysin.nextLine();

.... .... if (line.equals("quit"))

.... .... .... break;

.... .... runCalculator( stringToTokens( line ) );

.... }



That's it. That shows another use of Scanner...breaking an input stream into individual lines without having to construct a BufferedReader and handle I/O exceptions.



In my calculator (20+ years old, written in C, not Java, but a lot of the ideas are the same), I use that command line test to run just one line and return if there are any arguments passed to main, or drop into that "conversational mode" loop-until-quit if there are no arguments. This is natural for me, since there were no windows when I got started...everything was at the command line. I still use that calculator, since it has functions in it that no off-the-shelf program has.





One c
brilliant_moves
2013-11-15 15:04:05 UTC
I think your calculator program is more complicated than it needs to be.

Here's my version, which uses command line arguments OR scanner for input.

See what you think:



import java.util.Scanner;



public class Calc {

public static void main(String[] args) {



Scanner scan = new Scanner(System.in);

String operator;

int number1, number2;



if (args.length == 3) {

number1 = Integer.parseInt(args[0]);

operator = args[1];

number2 = Integer.parseInt(args[2]);

} else {

System.out.print("Enter first number: ");

number1 = scan.nextInt();

System.out.print("Enter operator: ");

operator = scan.next();

System.out.print("Enter second number: ");

number2 = scan.nextInt();

} //end if



double result=0;



if(operator.equals("x")) {

result=number1*number2;

} else if(operator.equals("/")) {

if (number2==0) {

System.out.println("Cannot divide by zero!");

} else {

result=number1/(number2 * 1.0); // floating point division

} // end if

} else if(operator.equals("+")) {

result=number1+number2;

} else if(operator.equals("-")) {

result=number1-number2;

} else {

System.out.println("Operator must be + - x or /");

} // end if



System.out.println(result);



} // end main()

} // end class
2013-11-15 14:57:34 UTC
Scanner input=new Scanner(System.in);



then just do input.nextInt();



that's it.



http://orangecounty.craigslist.org/cps/4181000090.html



These guys are awesome when I was learning java I just needed to see examples of what I wanted coded. They did it cheap.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...