Hello I can't seem to get my while loop to terminate the code when I'm typing the String "quit". Any help would be appreciated.
package CalculatorProg;
import java.util.Scanner;
public class MainDriver {
public static void main(String[] args){
BinaryExpression operation = new BinaryExpression();
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
while(true){
String calc;
String num1;
String num2;
num1 = userinput.next();
calc = userinput.next();
num2 = userinput.next();
String[] input = new String[5];
input[0] = num1;
input[1] = " ";
input[2] = calc;
input[3] = " ";
input[4] = num2;
if(calc.equals("+")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Add(x, y));
}
else if(calc.equals("-")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Subtract(x, y));
}
else if(calc.equals("*")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Multiply(x, y));
}
else if(calc.equals("/")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Divide(x, y));
}
else{
System.out.println("The operation is not valid.");
}
if(input[0].equalsIgnoreCase("quit")){
break;
}
}
System.exit(0);
}
}
The code is waiting on user input at calc = userinput.next();
public boolean hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
You should first validate the input inside its own condition.
Example:
package CalculatorProg;
import java.util.Scanner;
public class MainDriver {
public static void main(String[] args) {
BinaryExpression operation = new BinaryExpression();
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
while (true) {
String calc;
String num1;
String num2;
num1 = userinput.next();
calc = userinput.next();
num2 = userinput.next();
String[] input = new String[5];
input[0] = num1;
input[1] = " ";
input[2] = calc;
input[3] = " ";
input[4] = num2;
if (!input[0].equalsIgnoreCase("quit")) {
if (calc.equals("+")) {
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Add(x, y));
} else if (calc.equals("-")) {
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Subtract(x, y));
} else if (calc.equals("*")) {
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Multiply(x, y));
} else if (calc.equals("/")) {
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Divide(x, y));
} else {
System.out.println("The operation is not valid.");
}
} else {
break;
}
}
System.exit(0);
}
}
Try checking for the 'quit' before any of the other conditions:
package CalculatorProg;
import java.util.Scanner;
public class MainDriver {
public static void main(String[] args){
BinaryExpression operation = new BinaryExpression();
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
while(true){
String calc;
String num1;
String num2;
num1 = userinput.next();
if(num1.equalsIgnoreCase("quit")){
break;
}
calc = userinput.next();
num2 = userinput.next();
String[] input = new String[5];
input[0] = num1;
input[1] = " ";
input[2] = calc;
input[3] = " ";
input[4] = num2;
if(calc.equals("+")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Add(x, y));
}
else if(calc.equals("-")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Subtract(x, y));
}
else if(calc.equals("*")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Multiply(x, y));
}
else if(calc.equals("/")){
System.out.print(num1);
System.out.print(" ");
System.out.print(calc);
System.out.print(" ");
System.out.print(num2);
System.out.print(" ");
System.out.print("=");
System.out.print(" ");
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(operation.Divide(x, y));
}
else{
System.out.println("The operation is not valid.");
}
}
System.exit(0);
}
}
The problem may have been that it is trying to parse 'quit' to an integer, which would cause an error and never reach the quit condition.
Or it could be that the code is waiting for an input at 'calc = userinput.next();', but i'm not sure if you tried entering the next two inputs
Code is probably stuck on the second next() call. Try just using a single call to nextLine() and a call to String::split
String input = userinput.nextLine(); // Get an entire line
if (input.equalsIgnoreCase("quit")){ // Check the exit first
break;
}
// If it hasn't exited assume that its an equation
String[] inputSplit = input.split(); // Split the input by spaces
String calc inputSplit[1];
String num1 inputSplit[0];
String num2 inputSplit[2];
I hope it will fit for you. I give it to some helping information to users when the program is running. You can try it out! :D
package CalculatorProg;
import java.util.Scanner;
public class MainDriver {
public static void main(String[] args){
BinaryExpression operation = new BinaryExpression();
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
while(true){
String calc;
String num1;
String num2;
System.out.print("Number 1 (if quit then program exits) =");
num1 = userinput.next();
if(num1.equalsIgnoreCase("quit")) {
System.out.println("program quit");
break;
}
System.out.print("Operator =");
calc = userinput.next();
System.out.print("Number 2 =");
num2 = userinput.next();
String[] input = new String[5];
input[0] = num1;
input[1] = " ";
input[2] = calc;
input[3] = " ";
input[4] = num2;
if(calc.equals("+")){
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + operation.Add(x,y));
//System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + (x+y));
}
else if(calc.equals("-")){
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + operation.Subtract(x, y));
//System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + (x-y));
}
else if(calc.equals("*")){
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + operation.Multiply(x, y));
//System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + (x*y));
}
else if(calc.equals("/")){
int x, y;
x = Integer.parseInt(num1);
y = Integer.parseInt(num2);
System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + operation.Divide(x, y));
//System.out.println(num1 + " " + calc + " " + num2 + " " + "=" + " " + (x/y));
}
else{
System.out.println("The operation is not valid. You can give +, -, *, / for operator!");
}
}
System.exit(0);
}
}
Related
Im trying to make a simple calculator but with 2 files. The first file is for the normal code and the 2nd file is for the switch case. What im trying to do is to use the input from num1 num2 to switch.java My issue is that num1 num2 cannot be resolved to a variable in Switch.java
week1.java
import java.util.Scanner;
public class week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int operator2 = 0;
Switch swish = new Switch();
swish.switchcase();
}
}
Switch.java
import java.util.Scanner;
public class Switch
{
void switchcase()
{
switch(operator1){
case '+':
operator2 = num1 + num2;
System.out.println("Addition: " + (week1.num1) + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '-':
operator2 = num1 - num2;
System.out.println("Subtraction: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '*':
operator2 = num1 * num2;
System.out.println("Multiplication: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '/':
operator2 = num1 / num2;
System.out.println("Division: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
}
}
}
You must pass parameters to your switchcase method, and obtain a result back.
Class Week1:
import java.util.Scanner;
public class Week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int result = Switch.switchcase(num1, operator1, num2);
System.out.println(num1 + " " + operator1 + " " + num2 + " = " + result);
}
}
Class Switch:
public class Switch {
public static int switchcase(int num1, char operator1, int num2) {
switch(operator1){
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
}
}
}
Try using the below classes. Local variables inside a method will only be accessible inside that method. The variables has to be passed to another method for processing.
It is a best practice to begin class with capital letter.
Visit https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html
import java.util.Scanner;
public class Week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int operator2 = 0;
Switch swish = new Switch();
swish.switchcase(num1, operator1, num2);
}
}
public class Switch
{
void switchcase(int num1, char operator1, int num2)
{
int operator2;
switch(operator1){
case '+':
operator2 = num1 + num2;
System.out.println("Addition: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '-':
operator2 = num1 - num2;
System.out.println("Subtraction: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '*':
operator2 = num1 * num2;
System.out.println("Multiplication: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '/':
operator2 = num1 / num2;
System.out.println("Division: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
}
}
}
The result i get :
Enter a number :
5
Enter another number :
4
What do you want to perform on these numbers?
You have entered a wrong action, please try again
Where did i go wrong in my code?
import java.util.Scanner;
public class App {
public static void main(String[] args) {
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
}
Instead of using sc.nextline() on line 15 use sc.next(). The program will now wait for your input before continuing.
Can you change your code like below:
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine(); // ADD THIS LINE
String word = sc.nextLine();
The problem here is with the num2 = sc.nextDouble(); the newline char is not consumed.
Below is the code I use:
public static void main(String args[]) throws Exception {
// A1Pattern.printPattern(26);
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine();
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
OUTPUT:
Enter a number :
1
Enter another number :
2
What do you want to perform on these numbers?
Subtraction
1.0 Subtraction 2.0 : -1.0
The java.util.Scanner.next() method finds and returns the next complete token from this scanner.
Use scanner.next() instead of scanner.nextLine().
I am trying to make this file loop, but I keep getting an error on at the last if statement (Marked by an arrow).
The program is supposed to read in a file with the first line being the name of the customer.
On the second line, the first number is the number of trees to be removed(150 per tree), the second number is tree trimming to be done(50 an hour).
The third line are all the stumps to be removed and their diameter(one number is one stump and also it's diameter).
This is the file that is supposed to be read in (http://pastebin.com/gXkujcaM).
public class Prog_5 {
public static void main(String[] args) throws FileNotFoundException {
String name = "Joe";
double trees = 0;
double treeTrimming = 0;
double stumpInches = 0;
double stumpTotal = 0;
double total = 0;
double totalRev = 0;
Scanner in = new Scanner(System.in);
System.out.print("Input file: ");
String inputFile = in.nextLine();
System.out.print("Output file: ");
String outputFile = in.nextLine();
in.close();
File input = new File(inputFile);
in = new Scanner(input);
PrintWriter output = new PrintWriter(outputFile);
while(in.hasNext()){
name = in.nextLine();
output.println("Customer: " + name);
System.out.println("Customer: " + name);
trees = in.nextDouble();
trees *= 150;
output.println("Tree Removal: $" + trees);
System.out.println("Tree Removal: $" + trees);
treeTrimming = in.nextDouble();
treeTrimming *= 50;
output.println("Tree Trimming: $" + treeTrimming);
System.out.println("Tree Trimming: $" + treeTrimming);
while (in.hasNextDouble()) {
stumpInches = in.nextDouble();
if (stumpInches != -1) {
stumpTotal = stumpTotal + 30;
if (stumpInches > 12) {
stumpInches -= 12;
stumpInches *= 2;
}
stumpTotal += stumpInches;
}
}
output.println("Stump Removal: $" + stumpTotal);
System.out.println("Stump Removal: $" + stumpTotal);
total = (trees + treeTrimming + stumpTotal);
output.println("Total: $" + total);
System.out.println("Total: $" + total);
totalRev += total;
stumpTotal = 0;
trees = 0;
treeTrimming = 0;
if(in.hasNext());
in.next();
}
output.close();
}
}
it is your if loop is problem . you should write it like below . but you terminated it with ;
if(in.hasNext()){
in.next();
}
so it will keep throwing nosuchelement exception every time if it reaches EOF
There is no need of outer while loop, if condition at the end. Inner while loops takes care of what your program is intended to do. PFB corrected code:
import java.io.*;
import java.util.Scanner;
public class Prog_5 {
public static void main(String[] args) throws FileNotFoundException {
String name = "Joe";
double trees = 0;
double treeTrimming = 0;
double stumpInches = 0;
double stumpTotal = 0;
double total = 0;
double totalRev = 0;
Scanner in = new Scanner(System.in);
System.out.print("Input file: ");
String inputFile = in.nextLine();
System.out.print("Output file: ");
String outputFile = in.nextLine();
in.close();
File input = new File(inputFile);
in = new Scanner(input);
PrintWriter output = new PrintWriter(outputFile);
// while (in.hasNext()) {
name = in.nextLine();
output.println("Customer: " + name);
System.out.println("Customer: " + name);
trees = in.nextDouble();
trees *= 150;
output.println("Tree Removal: $" + trees);
System.out.println("Tree Removal: $" + trees);
treeTrimming = in.nextDouble();
treeTrimming *= 50;
output.println("Tree Trimming: $" + treeTrimming);
System.out.println("Tree Trimming: $" + treeTrimming);
while (in.hasNextDouble()) {
stumpInches = in.nextDouble();
if (stumpInches != -1) {
stumpTotal = stumpTotal + 30;
if (stumpInches > 12) {
stumpInches -= 12;
stumpInches *= 2;
}
stumpTotal += stumpInches;
}
}
output.println("Stump Removal: $" + stumpTotal);
System.out.println("Stump Removal: $" + stumpTotal);
total = (trees + treeTrimming + stumpTotal);
output.println("Total: $" + total);
System.out.println("Total: $" + total);
totalRev += total;
stumpTotal = 0;
trees = 0;
treeTrimming = 0;
// if (in.hasNext())
// ;
// in.next();
// }
in.close();
output.close();
}
}
I am trying to write a program that ask a user for 2 numbers and then ask the user to pick a command from a menu by entering the correspond number to the command.
I can write the program if i take the input as an Int but cannot figure it out for a string, also it has to be a string.
I am having problems when it enters the while loop to validate the user input it does not stop when the statement is false it will stay in the loop I can not figure out what i am doing wrong.
Here is the code i have.
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
System.out.println();
while (!input.equals(1) && !input.equals(2) && !input.equals(3) && !input.equals(4)) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
System.out.println();
if (input.equals(1)) {
System.out.print(L + " * " + R + " = " + (L * R));
} else if (input.equals(2)) {
System.out.print(L + " / " + R + " = " + (L / R));
} else if (input.equals(3)) {
System.out.print(L + " + " + R + " = " + (L + R));
} else {
System.out.print(L + " - " + R + " = " + (L - R));
}
}
stdIn.close();
}
}
Any help would be much appreciated.
Thank you in advanced.
The line input = stdIn.next(); is taking input as String
while your comparison is against integer. So a String never equals Int
You may try changing your while loop condition to:
while (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4"))
note the double quote around the numbers
Is answered, but check this
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
while (true) {
if (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4")) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
} else {
if (input.equals("1")) {
System.out.print(L + " * " + R + " = " + (L * R));
break;
} else if (input.equals("2")) {
System.out.print(L + " / " + R + " = " + (L / R));
break;
} else if (input.equals("3")) {
System.out.print(L + " + " + R + " = " + (L + R));
break;
} else {
System.out.print(L + " - " + R + " = " + (L - R));
break;
}
}
}
stdIn.close();
}
}
I am attempting to simplify my long code of a calculator program, but I have a road block. I have a new else if statement for each calculator operator, but what I want to do is allow the user to manually type in, on one line, the entire operation they would like to perform and have the code compute it.
Here's what I have:
do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();
if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 * num2;
System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);
answer = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");
This is what I want the output to be:
Enter operation:
4 * 6
4 * 6 = 24
Should be able to enter any operation here on one line. I am not asking you to write my calculator for me, I am asking how to allow the computer to read in the entire operation off one line and compute it, then print it.
If you use scanner readLine then you can read a whole line
e.g.
4 * 6
This line can then be split to get three tokens
String tokens [] = line.split (" ");
then you can see what operation to do based upon token[1]
if (token[1].equals ("-") {
//lets minus token[2] from token[0]
// need to convert String to Number
}
You can use String.split and store it in an array. Then it will return an array of string, parse those back to integers. the do the operation you want. The x variable will be the result.
if(maininput.contains("+")) {
String[] stringarr = string.split("\\+");
int x = Integer.parseInt(stringarr[0]) + Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " + " + stringarr[1] + " = " + x);
} else if(maininput.contains("-")) {
String[] stringarr = string.split("\\-");
int x = Integer.parseInt(stringarr[0]) - Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " - " + stringarr[1] + " = " x);
}
... And so on.
You could try parsing the line using a Pattern object, something like this:
Pattern opPattern = Pattern.compile("(\\d+) *([+-*/]) *(\\d+)");
Matcher matcher = opPattern.matcher(userLine);
if(matcher.find()) {
int op1 = Integer.toValue(matcher.group(1));
int op2 = Integer.toValue(matcher.group(3));
String op = matcher.group(2);
if(op.equals("+")) {
// do + op ...
} else ... {
// etc...
}
} else {
// error in line, not the form of an operation
}
Have a look at the javadoc, as I'm not sure if I used the correct method names and the like, just tried to illustrate the idea...