If ENTER is inputted, i.e. null or empty string, the following error is thrown. Can't seem to work around it.
Exception in thread "main" java.lang.NumberFormatException: empty String at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at
java.lang.Double.parseDouble(Double.java:538) at
com.company.Main.main(Main.java:67) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Instructions
Design a program that will prompt for and read in two numbers as
strings. The numbers could be decimal numbers (double or float) or
whole numbers (int). Convert these numbers from String to numeric.
You can either choose the correct numeric type for the number of
convert directly to double since it is the largest enclosing type. If
the numbers are not valid, please inform the user and prompt again.
After both valid numbers are read in, read in an operator (+, -, *,
/). If the operator read in is not one of the allowed operators,
inform the user and prompt again. Once everything is valid perform the
indicated operation using the two numbers.
Do not use a try...catch block to intercept errors. All other options
are open to you.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String sInput;
String nInput;
double dInput;
String sInput2;
String nInput2;
double dInput2;
boolean inputOK = false;
String operator = "";
int decCount;
String operatorSelect;
double total = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
do {
System.out.print("Enter first number: ");
//decimals count validation reset.
decCount = 0;
sInput = scanner.nextLine();
if (sInput == null) {
sInput = "0";
}
//purge !numerals || !decimals.
nInput = sInput.replaceAll("[^0-9.]", "");
//decimal count validation.
for (int i = 0; i < nInput.length(); i++) {
if (nInput.charAt(i) == '.') {
decCount = decCount + 1;
}
}
//break if input valid.
if (decCount <= 1) {
break;
}
} while (true);
dInput = Double.parseDouble(nInput);
do {
System.out.print("Enter second number: ");
//decimals count validation reset.
decCount = 0;
sInput2 = scanner.nextLine();
//purge !numerals || !decimals.
nInput2 = sInput2.replaceAll("[^0-9.]", "");
//decimal count validation.
for (int i = 0; i < nInput2.length(); i++) {
if (nInput2.charAt(i) == '.') {
decCount = decCount + 1;
}
}
//break if input valid.
if (decCount <= 1) {
break;
}
} while (true);
dInput2 = Double.parseDouble(nInput2);
while (inputOK == false) {
System.out.println("Operator to select: \n1) +\n2) -\n3) *\n4) /\n");
operatorSelect = scanner.nextLine();
switch (operatorSelect) {
case "1":
total = dInput + dInput2;
inputOK = true;
operator = "+";
break;
case "2":
total = dInput - dInput2;
inputOK = true;
operator = "-";
break;
case "3":
total = dInput * dInput2;
inputOK = true;
operator = "*";
break;
case "4":
total = dInput / dInput2;
inputOK = true;
operator = "/";
break;
default:
System.out.println("Invalid input.");
}
}
System.out.println(dInput + " " + operator + " " + dInput2 + " = " + total);
}
}
}
If you press enter, sInput is not null, it's an empty String.
sInput = scanner.nextLine();
if (sInput.equals("")) {
sInput = "0";
}
The expression ^-?\d+(,\d+)*(\.\d+(e\d+)?)?$ will match a string that starts with an optional negative sign, one or more digits, optionally followed by a comma and more digits, followed by an optional fractional component which consists of a period, one or more digits, and another optional component, the exponent followed by more digits.
This is not the only solution as there can be many expressions that can match these sets of number strings.
I haven't optimized your code just added the regex check and empty check
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String sInput;
String nInput;
double dInput;
String sInput2;
String nInput2;
double dInput2;
boolean inputOK = false;
String operator = "";
int decCount;
String operatorSelect;
double total = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
do {
System.out.print("Enter first number: ");
//decimals count validation reset.
decCount = 0;
sInput = scanner.nextLine();
if (sInput.isEmpty()) {
System.out.println("Empty value Please Enter again");
continue;
}
if (!sInput.matches("^-?\\d+(,\\d+)*(\\.\\d+(e\\d+)?)?$")) {
System.out.println("Invalid input Please Enter again");
continue;
}
break;
//Not needed regex will take care of everything
// //purge !numerals || !decimals.
// nInput = sInput.replaceAll("[^0-9.]", "");
// //decimal count validation.
// for (int i = 0; i < nInput.length(); i++) {
// if (nInput.charAt(i) == '.') {
// decCount = decCount + 1;
// }
// }
// //break if input valid.
// if (decCount <= 1) {
// break;
// }
} while (true);
dInput = Double.parseDouble(sInput);
do {
System.out.print("Enter second number: ");
//decimals count validation reset.
decCount = 0;
sInput2 = scanner.nextLine();
if (sInput2.isEmpty()) {
System.out.println("Empty value Please Enter again");
continue;
}
if (!sInput2.matches("^-?\\d+(,\\d+)*(\\.\\d+(e\\d+)?)?$")) {
System.out.println("Invalid input Please Enter again");
continue;
}
break;
//purge !numerals || !decimals.
// nInput2 = sInput2.replaceAll("[^0-9.]", "");
// //decimal count validation.
// for (int i = 0; i < nInput2.length(); i++) {
// if (nInput2.charAt(i) == '.') {
// decCount = decCount + 1;
// }
// }
// //break if input valid.
// if (decCount <= 1) {
// break;
// }
} while (true);
dInput2 = Double.parseDouble(sInput2);
while (inputOK == false) {
System.out.println("Operator to select: \n1) +\n2) -\n3) *\n4) /\n");
operatorSelect = scanner.nextLine();
switch (operatorSelect) {
case "1":
total = dInput + dInput2;
inputOK = true;
operator = "+";
break;
case "2":
total = dInput - dInput2;
inputOK = true;
operator = "-";
break;
case "3":
total = dInput * dInput2;
inputOK = true;
operator = "*";
break;
case "4":
total = dInput / dInput2;
inputOK = true;
operator = "/";
break;
default:
System.out.println("Invalid input.");
}
}
System.out.println(dInput + " " + operator + " " + dInput2 + " = " + total);
break;
}
}
}
Related
I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Hangman {
public static void main(String[] args) {
String playAgainMsg = "Would you like to play again?";
String pickCategoryMsg = "You've tried all the words in this category!\nWould you like to choose another category?";
int winCounter = 0, loseCounter = 0, score = 0;
String[] words;
int attempts = 0;
String wordToGuess;
boolean playCategory = true, playGame = true;
int totalCounter = 0, counter;
while (playCategory && playGame)
{
while (playCategory && playGame) {
words = getWords();
counter = 0;
while (playGame && counter < words.length) {
wordToGuess = words[counter++];
if (playHangman(wordToGuess)) {
winCounter++;
System.out.println("You win! You have won " + winCounter + " game(s)." + " You have lost " + loseCounter + " game(s).");
} else {
loseCounter++;
System.out.println("You lose! You have lost " + loseCounter + " game(s)." + " You have won " + winCounter + " game(s).");
}
if (counter < words.length) playGame = askYesNoQuestion(playAgainMsg);
}
if (playGame) playCategory = askYesNoQuestion(pickCategoryMsg);
}
}
}
public static boolean playHangman(String wordToGuess) {
String[] computerWord = new String[wordToGuess.length()];
String[] wordWithDashes = new String[wordToGuess.length()];
for (int i = 0; i < computerWord.length; i++) {
computerWord[i] = wordToGuess.substring(i, i+1);
wordWithDashes[i] = "_";
}
Scanner in = new Scanner(System.in);
int attempts = 0, maxAttempts = 7;
boolean won = false;
int points = 0;
while (attempts < maxAttempts && !won) {
String displayWord = "";
for (String s : wordWithDashes) displayWord += " " + s;
System.out.println("\nWord is:" + displayWord);
System.out.print("\nEnter a letter or guess the whole word: ");
String guess = in.nextLine().toLowerCase();
if (guess.length() > 1 && guess.equals(wordToGuess)) {
won = true;
} else if (wordToGuess.indexOf(guess) != -1) {
boolean dashes = false;
for (int i = 0; i < computerWord.length; i++) {
if (computerWord[i].equals(guess)) wordWithDashes[i] = guess;
else if (wordWithDashes[i].equals("_")) dashes = true;
}
won = !dashes; // If there are no dashes left, the whole word has been guessed
} else {
drawHangmanDiagram(attempts);
System.out.println("You've used " + ++attempts + " out of " + maxAttempts + " attempts.");
}
}
int score = 0;
score = scoreGame(attempts);
System.out.println("Your score is: " + score);
return won;
}
//should take in a failure int from the main method that increments after every failed attempt
public static void drawHangmanDiagram(int failure)
{
if (failure == 0)
System.out.println("\t+--+\n\t| |\n\t|\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 1)
System.out.println("\t+--+\n\t| |\n\t| #\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 2)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 3)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| / \\\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 4)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 5)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| /\n\t|\n\t|\n\t+--");
else if (failure == 6)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| / \\\n\t|\n\t|\n\t+--");
}
// Asks user a yes/no question, ensures valid input
public static boolean askYesNoQuestion(String message) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println(message + " (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
public static boolean askForCategory(int category) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("\nWould you like to play again? (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
// Asks the user to pick a category
public static String[] getWords() {
String[] programming = {"java", "pascal", "python", "javascript", "fortran", "cobol"};
String[] sports = {"gymnastics", "badminton", "athletics", "soccer", "curling", "snooker", "hurling", "gaelic", "football", "darts"};
String[] result = {""};
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("Pick a category:\n1. Programming\n2. Sports");
answer = in.nextLine().toLowerCase();
if (answer.matches("[1-2]")) validAnswer = true;
else System.out.println("Invalid input! Enter the number of the category you want.");
} while (!validAnswer);
int selection = Integer.parseInt(answer);
switch (selection) {
case 1: result = randomOrder(programming); break;
case 2: result = randomOrder(sports); break;
}
return result;
}
// Sorts a String array in random order
public static String[] randomOrder(String[] array) {
int[] order = uniqueRandoms(array.length);
String[] result = new String[array.length];
for (int i = 0; i < order.length; i++) {
result[i] = array[order[i]];
}
return result;
}
// Generates an array of n random numbers from 0 to n-1
public static int[] uniqueRandoms(int n) {
int[] array = new int[n];
int random, duplicateIndex;
for (int i = 0; i < n; ) {
random = (int) (Math.random() * n);
array[i] = random;
for (duplicateIndex = 0; array[duplicateIndex] != random; duplicateIndex++);
if (duplicateIndex == i) i++;
}
return array;
}
public static int scoreGame(int attempts)
{
int score = 0;
switch (attempts)
{
case 0: score = 70; break;
case 1: score = 60; break;
case 2: score = 50; break;
case 3: score = 40; break;
case 4: score = 30; break;
case 5: score = 20; break;
case 6: score = 10; break;
case 7: score = 0; break;
}
return score;
}
}
I have got it working so that it keeps count of the games won and lost, as well as assigning a score based on the amount of attempts/lives saved but I haven't been able to find a way to get it to keep a total score for all of the games played. Each game unfortunately has a seperate score. If anyone can advise me on a way of doing this, it would be greatly appreciated.
Create an int totalScore variable where winCounter, loseCounter and score are defined. Then increment it after each call to scoreGame()
score = scoreGame(attempts);
totalScore += score;
System.out.println("Your score is: " + score);
If you want to permanently save statistics between sessions then it's a whole nother story. You would need to write your scores to a file after each round and then start your program by reading this score file. It's hardly impossible, but requires a bit more 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:
("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")
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();
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