Math string with no spaces? - java

import java.util.Scanner;
public class Improved {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number operaion number: ");
int operand1 = Integer.parseInt(input.nextLine());
char expo1 = input.next().charAt(0);
int operand2 = Integer.parseInt(input.nextLine());
System.out.println( operand1 + expo1 + operand2 + "=");
if ( expo1 == '/' && operand2 == '0' ){
System.out.println("Cannot divide by zero"); }
else
if (expo1 == '-') {
System.out.println(operand1-operand2);
} else
if (expo1 == '+') {
System.out.println(operand1+operand2);
} else
if (expo1 == '/') {
System.out.println(operand1/operand2);
} else
if (expo1 == '%') {
System.out.println(operand1%operand2);
}
else{
System.out.println(" Error.Invalid operator.");
}
}
}
//This bottom works, but I found out that this is not what is supposed to be done with this problem
/*
public class Else {
public static void main(String[] args) {
int operand1;
char exp1;
int operand2;
if (args.length != 3 ) {
System.err.println("*** Program needs 3 arguements***");
System.err.println("Usage: java Else int1 exp int2");
System.exit(1);
}
operand1 = Integer.parseInt(args[0]);
exp1 = args[1].charAt(0);
operand2 = Integer.parseInt(args[2]);
System.out.print(args[0] + args[1] + args[2] + "=");
if(exp1 == '-') {
System.out.println(operand1 - operand2);
} else
if (exp1 == '+') {
System.out.println(operand1 + operand2);
} else
if (exp1 == '/') {
System.out.println(operand1 / operand2);
} else
if (exp1 == '%') {
System.out.println(operand1 % operand2);
}
else{
System.out.println(" Error.Invalid operator.");
}
}
}
*/
What I want the program to do is ask one to enter a math operation 1/2 or 1%2 (not multiplication)
, but just like that without spaces. Still, I want to check which operation is being done which is why i put the if statements. What I don't get is how the program would know when an operation appears in a string. I'm not even sure if I set it correctly. Overall, I want a string that reads the number then the operation an then the number again. I'm sorry if this seems like doing my hw, but I have tried making this program multiple times, but can't understand how I can do this with a string. I wrote the second one to show that I have done this multiple times, so you can ignore it. Thank You very much!

read input as a String using:
String inputString = input.nextLine();
get the index of the operator:
int indexOp = inputString.indexOf("+");
if(indexOp < 0) indexOp = inputString.indexOf("-"); //cannot find +, so find -
if(indexOp < 0) indexOp = inputString.indexOf("/"); //cannot find -, so find /
if(indexOp < 0) indexOp = inputString.indexOf("%"); //cannot find /, so find %
get the first and second operand with:
int operand1 = Integer.parseInt(inputString.substring(0,indexOp));
int operand2 = Integer.parseInt(inputString.substring(indexOp+1,inputString.length());
get the operator from the indexOp we got earlier:
char operator = inputString.charAt(indexOp);
Hope it helps :)

I have no doubt there are a number of ways this might be achieved, this is simply another example...
What this tries to do, is break down the incoming text into groups of digits and non digits. It then loops through these groups making up the various elements of the calculation...
Scanner input = new Scanner(System.in);
System.out.println("Enter a number operaion number: ");
String text = input.nextLine();
System.out.println("Input = " + text);
text = text.replaceAll("\\s", "");
System.out.println("Parse = " + text);
Pattern p = Pattern.compile("\\d+|\\D+");
Matcher m = p.matcher(text);
int index = 0;
int op1 = -1;
int op2 = -2;
String exp1 = "";
while (index < 3 && m.find()) {
System.out.println(index);
String part = m.group();
switch (index) {
case 0:
op1 = Integer.parseInt(part);
break;
case 2:
op2 = Integer.parseInt(part);
break;
case 1:
exp1 = part;
break;
}
index++;
}
System.out.println(op1 + " " + exp1 + " " + op2);
What this does have, is the power to to allow you to supply a much longer calculation, for example 20+30/40-50...etc.
You would need to park each operand and exponent into some kind of List and extract them as you need them...or you could actually do the calculation directly within the while loop

Try this:
package week11;
import java.util.Scanner;
public class maths {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter a number ");
int x = scanner.nextInt();
System.out.println("put +, -, / or * ");
char expo1 = scanner.next().charAt(0);
System.out.println("second number please ");
int y = scanner.nextInt();
System.out.println( "Answer is" + ":");
if ( expo1 == '/' && y == '0' ){
System.out.println("cannot be divided by 0"); }
else
if (expo1 == '-') {
System.out.println(x-y);
} else
if (expo1 == '+') {
System.out.println(x+y);
} else
if (expo1 == '/') {
System.out.println(x/y);
} else
if (expo1 == '%') {
System.out.println(x%y);
}
else{
System.out.println(" Error!");
}
}
}

I would like to add another solution, which removes a lot of the parsing work.
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Scratch {
public static void main(String[] args) throws ScriptException {
System.out.println("Enter an operation:");
Scanner input = new Scanner(System.in);
String operation = input.nextLine();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval(operation);
System.out.printf("%s = %s%n", operation, result);
}
}
sample result
Enter an operation:
2 + 3 * 4
2 + 3 * 4 = 14.0

Related

How can I handle input string, during the process of if, else if, else including Integer.parseInt?

I would like to handle this situation about inputting wrong string, but error keeps happening because of the else if argument.
Tried try, catch but don't know how to apply it to this code.
import java.util.Scanner;
public class game
{
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
I expect the result from the else block, but when I input wrong string like "c" or "f" and etc, number format exception error: For input string: "c" (or "f" and etc) happens. Thanks for reading this, and hope you solve this problem.
int check = 0;
try{
check = Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.println("Wrong input");
continue;
}
If you loop this input processing,if it enters catch,you may take input again or you can do what you want when invalid input is entered.If there is no exception,check is your input value,then you can use it in your if and else-if statements like
if(check>0){
...
}
Before Else blocks, you can parse the input like this:
if (input.equals("q")) {
System.out.print("quit the game.");
return;
}
int parsedInput = 0;
try {
parsedInput = Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.out.print("Error. Please try again.");
return;
}
Then you can write if-else for integer input like below:
if (parsedInput == 0) { ... }
else if (parsedInput >= 2 && parsedInput <= 9) {...}
Last else is not needed because I moved it to catch block.
try this it can handle exception
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
int check_input = Integer.parseInt(input);
if (check_input == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
} else if (check_input >= 2 && check_input <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
} catch (Exception e) {
System.out.print("Error. Please try again.");
}
}
}
You just need to check the user provided input is number or not. Before parsing it.
I have added new isNumberic method which is returning boolean flag depending user's input and verify it.
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
Game game = new Game();
boolean isvalid = game.isNumeric(input);
if (input.equals("q")) {
System.out.print("quit the game.");
}
else if (isvalid && Integer.parseInt(input) == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (isvalid && Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
}
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}
}
You can't send values like a , b, c etc for
Integer.parseInt(String s)
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
I have try catch block to catch numberformat exception with message to enter valid integer
public static void main(String args[]) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
try {
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
catch (NumberFormatException e ) {
System.out.print("pleae enter Valid integer");
}
It's obvious that you are getting this error because you are calling Integer.parseInt on a string variable which doesn't contain an Integer. What you should be doing is putting a check once you get the input to check if the string contains what you need. Something like below
while (true)
{
// Check that the input is between 0 and 9 or q.
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
// If it is not, ask for input again.
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
// If input is correct, break this look.
break;
}
}
Below is the whole code
public class game
{
public static void main(String[] args)
{
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
while (true)
{
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
break;
}
}
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9)
{
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
Verify input in two separate if/else blocks. Add this code to your "else" statement to catch strings other than "q".
else{
try {
int inputNumber = Integer.parseInt(input);
if(inputNumber == 0) {
// code..
} else if (inputNumber >= 2 && inputNumber <= 9) {
// code..
}
} catch(java.lang.NumberFormatException e) {
System.out.print("Error. Please try again.");
}
}
why don't use try catch?
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
Integer i = Integer.parseInt(input);
}catch (NumberFormatException e){
System.out.print("Error. Please try again.");
return;
}

Validation error in code

I am experiencing trouble in the creation of my reverse polish notation calculator with my validation code. I need the calculator to accept the two shift operators (<< and >>) as part of the calculations. The following snippets of code is the validation part and also the calculation.
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
} catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
invalidlines++;
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
} else {
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/\\<<\\>>\\%\\&\\|]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
} else {
return false;
}
}
}
below is the calculator part:
String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true) {
display("Please enter an equation");
keyboardInput = kbScan.nextLine();
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch (equation[2]) { // This case switch checks the third position of the
// string to decide which operator is being used. It then works out the
// answer and breaks to the next instruction
case ("+"):
answer = num1 + num2;
break;
case ("-"):
answer = num1 - num2;
break;
case ("/"):
answer = num1 / num2;
break;
case ("*"):
answer = num1 * num2;
break;
case ("<<"):
answer = num1 << num2;
break;
case (">>"):
answer = num1 >> num2;
break;
case ("%"):
answer = num1 % num2;
break;
case ("|"):
answer = num1 | num2;
break;
case ("&"):
answer = num1 & num2;
break;
}
display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
} else {
display("The equation you entered is invalid");
}
}
Whenever a valid expression is entered the following error is shown in the console:
Enter F for file calculator or K for keyboard input
k
Please enter an equation
10 2 <<
The equation you entered is invalid
Please enter an equation
And I cannot figure out which part of my validation is wrong for these expressions.
Problem is with your operators regex.
User rather something like:
("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")

How can i separate two data types in user input?

I am creating a calculator in which a user will directly input the numbers and the operator...
Here is my code:
int answer = 0;
int num1, num2;
char operator;
System.out.print("Enter calculation: ");
num1 = kb.nextInt();
operator = kb.next().charAt(0);
num2 = kb.nextInt();
The code above will accept the user input when there are spaces like this:
1 + 1
so the program will give an answer which is 2.
But if i input 1+1 it will give an error
Exception in thread "main" java.util.InputMismatchException
How can i do that it will separate integer to character? because i set the operator as character. So that it will accept one digit to several digit numbers. Like 500+84 or 1520/872, 30*5, 148-65?
I don't have much experience with the java.util.Scanner class. But, I suspect that it tokenizes on a well-defined token separator, such as spaces, tabs, a comma, pipe characters, etc. So, this may be a poor choice in tokenizing your type of input.
To successfully tokenize your type of input, I suggest implementing a proper lexical analyzer. This may be overkill here (like using a tank to hunt a rabbit), but to do it properly and formally with some guarantee of success, you would need to write a lexical analyzer. The web is chock-full of examples of writing a lexical analyzer. For your input, it may look something like this:
public class Scanners {
public static void main(String args[]) {
Lexer lexer = new Lexer("32221-8 +45 ");
for(String token : lexer)
System.out.println("token = "+token);
}
private static final class Lexer implements Iterable<String> {
private int pos=0;
private final String input;
private final int inputLength;
private String token;
public Lexer(String input) {
this.input = input;
this.inputLength = input.length();
advance();
}
private void advance() {
if(pos>=inputLength) {
token = null;
return;
}
char c = input.charAt(pos++);
if(Character.isDigit(c))
token = advanceNumber(c);
else if(Character.isJavaIdentifierStart(c))
token = advanceVariable(c);
else if(Character.isWhitespace(c)) {
advanceWhitespace();
advance();
} else
// here, assuming a one-character operator
token = Character.toString(c);
}
private String advanceNumber(char c) {
StringBuilder sb = new StringBuilder().append(c);
while(pos<inputLength) {
c = input.charAt(pos);
if(Character.isDigit(c)) {
sb.append(c);
++pos;
} else
break;
}
return sb.toString();
}
private String advanceVariable(char c) {
StringBuilder sb = new StringBuilder().append(c);
while(pos<inputLength) {
c = input.charAt(pos);
if(Character.isJavaIdentifierPart(c)) {
sb.append(c);
++pos;
} else
break;
}
return sb.toString();
}
private void advanceWhitespace() {
while(pos<inputLength && Character.isWhitespace(input.charAt(pos)))
++pos;
}
#Override
public Iterator<String> iterator() {
return new Iterator<String>() {
#Override
public boolean hasNext() {
return token != null;
}
#Override
public String next() {
String retval = token;
advance();
return retval;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
}
// output
// ------
// token = 32221
// token = -
// token = 8
// token = +
// token = 45
It does not expect negative operands. It throws an exception if a number is too big. It does not explain what the "error in expression" is. So there's plenty of room for improvement.
Scanner scn = new Scanner( System.in );
Pattern pat = Pattern.compile( "\\s*(\\d+)\\s*([-+*/])\\s*(\\d+)\\s*" );
while( scn.hasNextLine() ){
String line = scn.nextLine();
Matcher mat = pat.matcher( line );
if( mat.matches() ){
int op1 = Integer.parseInt( mat.group(1) );
char od = mat.group(2).charAt(0);
int op2 = Integer.parseInt( mat.group(3) );
System.out.println( op1 + " " + od + " " + op2 );
} else {
System.out.println( "error in expression" );
}
}
This is a simpler version. Similar caveats apply here, too. Moreover, it throws an exception on invalid numbers and accepts almost anything as an operator.
Scanner scn = new Scanner( System.in );
scn.useDelimiter( "\\b|\\s+" );
while( scn.hasNextLine() ){
int op1 = scn.nextInt();
char od = scn.next().charAt(0);
int op2 = scn.nextInt();
System.out.println( op1 + " " + od + " " + op2 );
scn.nextLine();
}
Try using 3 scanner?
Scanner scn = new Scanner(System.in);
int operand1, operand2;
String operator;
operand1 = Integer.parseInt(scn.next());
operator = scn.next();
operand2 = Integer.parseInt(scn.next());
OP changes his question I left.
I was away just now after I posted this solution. Didn't have time to improve it. Now I give you a better and simple solution:
I supposed you do not expect user to input things like "12+45*67/20" right? Assuming there will be two operands.
1) Receive input as 1 whole string
2) Trim all the spaces from the input
3) Split string into tokens of integers
Scanner scn = new Scanner(System.in);
String[] token = new String[12];
System.out.print("Enter equation:");
String input = scn.nextLine().trim();
String operator = "";
double answer=0, operand1=0, operand2=0;
if (input.indexOf("+") != -1){
token = input.split("\\+");
operator = "+";
}
else if (input.indexOf("-") != -1){
token = input.split("-");
operator = "-";
}
else if (input.indexOf("*") != -1){
token = input.split("\\*");
operator = "*";
}
else if (input.indexOf("/") != -1){
token = input.split("/");
operator = "/";
}
else
System.out.println("Invalid equation!");
if(token[0].matches("[0-9]+") && token[1].matches("[0-9+]"))
{
operand1 = Double.parseDouble(token[0]);
operand2 = Double.parseDouble(token[1]);
switch (operator)
{
case "+": answer = operand1 + operand2;
break;
case "-": answer = operand1 - operand2;
break;
case "*": answer = operand1 * operand2;
break;
case "/": answer = operand1 / operand2;
break;
}
}
System.out.println(answer);
Just copy and paste the whole thing to test it, it will work.
You can do it like this:
Scanner scn = new Scanner(System.in);
Integer operand1, operand2;
char operator;
System.out.println("Enter first operand: ");
operand1 = scn.nextInt();
System.out.println("Enter operator: ");
operator = scn.next().charAt(0);
System.out.println("Enter second operand: ");
operand2 = scn.nextInt();

How to assign a random number a string value in my program

as the title suggests I am doing a program for homework that is a slot machine. I have searched around and I am pretty satisfied that the program works correctly enough for me. The problem Im having is on top of generating the random numbers, I am supposed to assign values for the numbers 1-5 (Cherries, Oranges, Plums, Bells, Melons, Bars). Then I am to display the output instead of the number when my program runs. Can anyone get me pointed in the right direction on how to do this please?
import java.util.Random;
import java.util.Scanner;
public class SlotMachineClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Coins = 1000;
int Wager = 0;
System.out.println("Steve's Slot Machine");
System.out.println("You have " + Coins + " coins.");
System.out.println("Enter your bet and press Enter to play");
while (Coins > 0)
{
int first = new Random().nextInt(5)+1;
int second = new Random().nextInt(5)+1;
int third = new Random().nextInt(5)+1;
Wager = input.nextInt();
if(Wager > Coins)
Wager = Coins;
System.out.println(first + " " + second + " " + third);
if(first == second && second == third)
{ Coins = Coins + (Wager * 3);
System.out.println("You won " + (Wager * 3) + "!!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else if((first == second && first != third) || (first != second && first == third) || (first != second && second == third))
{ Coins = Coins + (Wager * 2);
System.out.println("You won " + (Wager * 2) + "!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else {Coins = Coins - Wager;
System.out.println("You Lost!" + "\nPlay Again? if so Enter your bet.");}
}
while (Wager == 0)
{
System.out.println("You ran out of coins. Thanks for playing.");
}
}
}
If you have an int and want to have some String associated with that, there are a couple of ways to do that.
The first one is to have an array of Strings and look them up.
public static String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
public String getNameForReel(int reelValue) {
return text[reelValue];
}
// And to call it...
System.out.println(getNameForReel(first)); //etc...
Or, you can do it in a switch statement (I don't prefer this, but you might):
public String getNameForReel(int reelValue) {
switch(reelValue) {
case 0: return "Cherry";
case 1: return "Bell";
case 2: return "Lemon";
case 3: return "Bar";
case 4: return "Seven";
}
}
You need a lookup table:
String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
Then you can just do
System.out.println(text[first] + " " + text[second] + " " + text[third]);
without creating more methods.
The non-array solution most likely to be used a by new programmer in an intro course would be a nested if-else:
String fruitToPrint = "";
if (num == 0)
fruitToPrint = "Cherries";
else if (num == 1)
fruitToPrint = "Oranges";
else if (num == 2)
fruitToPrint = "Plums";
else if (num == 3)
fruitToPrint = "Bells";
else if (num == 4)
fruitToPrint = "Melons";
else if (num == 5)
fruitToPrint = "Bars";
else
System.out.println("Couldn't assign fruit from num=" + num);
System.out.println("The corresponding fruit was " + fruitToPrint);
Create an array:
String[] s = {Cherries, Oranges, Plums, Bells, Melons, Bars};
Then you can print s[num-1] instead of num (where num is the random int). E.g. if your random int came out to be 2, print s[2-1] i.e. s[1] which will be Orange.
Here's an alternative solution to the question which I think follows best programming practices. This is probably even less allowed for your assignment than an array, and will be a dead giveaway that you got your answer on StackOverflow, but the problem would lend itself to using an enum type with an int->enum mapping:
enum Fruit {
Cherries(1),
Oranges(2),
Plums(3),
Melons(4),
Bars(5);
private static final Map<Integer, Fruit> lookupMap = new HashMap<Integer, Fruit>();
static {
for (Fruit fruit : Fruit.values()) {
lookupMap.put(fruit.getLookup());
}
}
static Fruit fromLookup(int lookup) {
return lookupMap.get(lookup);
}
private final int lookup;
private Fruit(int lookup) {
this.lookup = lookup;
}
int getLookup() {
return lookup;
}
}
void printEnumExample() {
int fruitToPrint = 4;
System.out.println(Fruit.fromLookup(fruitToPrint)); // <- This will print "Melons"
}

java rpn calculator

i would like to include a simple RPN type calculator function in one of my projects.
basically i need a method that can convert for example:
"30 / ((1 + 4) * 3)" into "2"
does anyone know of any pre-written libs that can do this?
thanks.
You should implement Shunting Yard Algorithm
also look : Reverse Polish notation
You can use Shunting Yard (Jep API)
I suggest you to write it in python if you don't have to implement it in Java because of it's built-in methods
print eval("30 / ((1 + 4) * 3)")
ideone demo
You need a parser and a stack.
Google brought back a bunch of links. I can't recommend any of them, because none of my apps require an RPN calculator.
If this is homework, please mark it as such.
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class Rpncalculator
{
static final HashMap<String, Integer> prec;
static
{
prec = new HashMap<>();
prec.put("^", 3);
prec.put("%", 2);
prec.put("*", 2);
prec.put("/", 2);
prec.put("+", 1);
prec.put("-", 1);
}
public static void main(String[] args)
{
Queue<String> infixQueue = new LinkedList<>(); //Standard Queue class provided by Java Framework.
Scanner sc = new Scanner(System.in);
Double number = 0.0;
Character c, cNext = ' ';
String input;
String multiDigit = "";
do
{
System.out.println("Enter your INFIX expression or 'quit' to exit: ");
input = sc.nextLine();
input = input.replaceAll(" ", ""); //ignore spaces in input infix expression
if (input.equals("quit"))
{
System.exit(0);
}
for (int i = 0; i < input.length(); i++)
{
c = input.charAt(i);
if (i + 1 < input.length())
{
cNext = input.charAt(i + 1);
}
if (c.equals('(') || c.equals(')'))
{
if (c.equals('(') && cNext.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
// System.exit(0);
} else
{
infixQueue.add(c.toString());
}
} else if (!Character.isDigit(c))
{
if (infixQueue.isEmpty() && c.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
} else if (cNext.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
} else
{
infixQueue.add(c.toString());
}
} else if (Character.isDigit(c))
{
if (i + 1 < input.length() && input.charAt(i + 1) == '.') //to handle decimal
{
int j = i + 1;
multiDigit = c.toString() + input.charAt(j); //to handle multidigit
while (j + 1 <= input.length() - 1 && Character.isDigit(input.charAt(j + 1)))
{
multiDigit = multiDigit + input.charAt(j + 1);
j++;
}
i = j;
infixQueue.add(multiDigit);
multiDigit = "";
} else if (i + 1 <= input.length() - 1 && Character.isDigit(input.charAt(i + 1)))
{
int j = i;
//multiDigit=c.toString()+input.charAt(i);
while (j <= input.length() - 1 && Character.isDigit(input.charAt(j)))
{
multiDigit = multiDigit + input.charAt(j);
j++;
}
i = j - 1;
infixQueue.add(multiDigit);
multiDigit = "";
} else
{
infixQueue.add(c.toString());
}
}
}
infixToPostfix(infixQueue);
} while (!input.equals("quit"));
}
//method to convert from infix to postfix
public static void infixToPostfix(Queue<String> infixQueue)
{
Stack operatorStack = new Stack();
Queue<String> postQueue = new LinkedList<>();
String t;
while (!infixQueue.isEmpty())
{
t = infixQueue.poll();
try
{
double num = Double.parseDouble(t);
postQueue.add(t);
} catch (NumberFormatException nfe)
{
if (operatorStack.isEmpty())
{
operatorStack.add(t);
} else if (t.equals("("))
{
operatorStack.add(t);
} else if (t.equals(")"))
{
while (!operatorStack.peek().toString().equals("("))
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
operatorStack.pop();
} else
{
while (!operatorStack.empty() && !operatorStack.peek().toString().equals("(") && prec.get(t) <= prec.get(operatorStack.peek().toString()))
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
operatorStack.push(t);
}
}
}
while (!operatorStack.empty())
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
System.out.println();
System.out.println("Your POSTFIX expression is: ");
//numbers and operators all seperated by 1 space.
for (String val : postQueue)
{
System.out.print(val + " ");
}
postfixEvaluation(postQueue);
}
//method to calculate the reuslt of postfix expression.
public static void postfixEvaluation(Queue<String> postQueue)
{
Stack<String> eval = new Stack<>(); //Standard Stack class provided by Java Framework.
String t;
Double headNumber, nextNumber, result = 0.0;
while (!postQueue.isEmpty())
{
t = postQueue.poll();
try
{
double num = Double.parseDouble(t);
eval.add(t);
} catch (NumberFormatException nfe)
{
headNumber = Double.parseDouble(eval.peek());
eval.pop();
nextNumber = Double.parseDouble(eval.peek());
eval.pop();
switch (t)
{
case "+":
result = nextNumber + headNumber;
break;
case "-":
result = nextNumber - headNumber;
break;
case "*":
result = nextNumber * headNumber;
break;
case "/":
//in java, there is no exception generated when divided by zero and thus checking
//for
if (headNumber == 0)
{
System.out.println("\nERROR: Cannot Divide by zero!\n");
return;
} else
{
result = nextNumber / headNumber;
break;
}
case "%":
result = nextNumber % headNumber;
break;
case "^":
result = Math.pow(nextNumber, headNumber);
break;
}
eval.push(result.toString());
}
}
System.out.println("\nRESULT is: ");
DecimalFormat df = new DecimalFormat("0.000");
for (String val : eval)
{
System.out.println(df.format(Double.parseDouble(val)) + "\n");
}
}
}
Actually, this is not an "RPN" question, because you want to evaluate an algebraic expression.
7th is primarily a RPN language, but can evaluate algebraic expressions with the restriction that they must not contain spaces and must be enclosed in round braces:
private static final ScriptEngineManager mgr = new ScriptEngineManager();
private static final ScriptEngine engine = mgr.getEngineByName( "7th" );
…
try {
Number d;
d = (Number)engine.eval( "(30/((1+4)*3))" ); // 2.0
d = (Number)engine.eval( "30 1 4 + 3 * /" ); // 2.0
}
catch( ScriptException ex ) {
ex.printStackTrace();
}

Categories