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...
Related
This is the code that I have so far. I just want to know if I'm correct. I am very new to this and most likely I'm correct but I still wanted to know. thanks
Scanner input = new Scanner(System.in);
//variables
int number1;
int number2;
System.out.println("enter first number: ");
number1 = input.nextInt();
System.out.println("enter first number: ");
number2 = input.nextInt();
int multiple = number1 % number2;
if((number1 % number2) == 0) {
System.out.println("Yes, " + number1 + " is a multiple of " + number2);
}
else {
System.out.println("No, " + number1 + " is not a multiple of " + number2);
}
System.out.println("The multiple is: " + multiple);
}
I guess you want if a number is divisible by other or not and want to get multiplier if so.
Scanner input = new Scanner(System.in);
//variables
int number1;
int number2;
System.out.println("enter first number: ");
number1 = input.nextInt();
System.out.println("enter second number: ");
number2 = input.nextInt();
if((number1 % number2) == 0) {
System.out.println("Yes, " + number1 + " is a multiple of " + number2);
System.out.println("The multiple is: " + (number1 / number2));
}
else {
System.out.println("No, " + number1 + " is not a multiple of " + number2);
}
Your code works fine. But if you consider couple of things here it would be good.
Change your second prompt to "enter second number"
Currently you are printing message "The multiple is: " every time whether you find multiple or not.
So print this message only when you found a multiple. Move this line to if block to achieve this.
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 just writed this program, it is to train myself for the upcomming exam this monday.
A thing i would like to add is: after a user is done with one of the exchange options 1/2/3 i would like to give the option to let the user return to the beginning welcome to the money exchange! etc.....
i have tried some a for loop and a while loop but i couldn't get it to work.
Would be cool if after the money exchange process that the user get the option to return to the beginning by typing y or n is this possible?
/* This program is written as a excercise to prep myself for exams.
* In this program the user can:
* 1. Select a currency (other than euro's)
* 2. Input the amount of money
* 3. transfer the amount of currency to euro's
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat() ;
df.setMaximumFractionDigits(2);
int choice = input.nextInt() ;
double transfee = 2.41 ;
double USrate = 0.9083 ;
double GBrate = 1.4015 ;
double YENrate = 0.0075 ;
if (choice > 3 || choice < 1) {
System.out.println("Invalid input!...... Please try agian\n");
} else {
if(choice == 1) {
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble() ;
double deuros = USamount * USrate ;
double ddisburse = deuros - transfee ;
System.out.print("\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ " + df.format(deuros) + "\n");
System.out.print("Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... " + df.format(ddisburse) + "\n" );
}else {
if(choice == 2){
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate ;
double gdisburse = geuros - transfee;
System.out.print("\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ " + df.format(geuros) + "\n");
System.out.print("Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... " + df.format(gdisburse) + "\n");
}else {
if(choice == 3){
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate ;
double ydisburse = yeuros - transfee ;
System.out.print("\nInput amount Yen:... " + YENamount + "\n");
System.out.print("Worth in euro's..... " + df.format(yeuros) + "\n");
System.out.print("Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. " + df.format(ydisburse) + "\n");
}
}
}
}
}
}
You could wrap your program with a while loop, which checks if the user entered 'y' at the end like this:
import java.text.DecimalFormat;
import java.util.Scanner;
class YourClassName
{
public static void main(String[] args)
{
boolean askAgain = true;
while (askAgain)
{
Scanner input = new Scanner(System.in);
System.out.println(
" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
int choice = input.nextInt();
double transfee = 2.41;
double USrate = 0.9083;
double GBrate = 1.4015;
double YENrate = 0.0075;
if (choice > 3 || choice < 1)
{
System.out.println("Invalid input!...... Please try agian\n");
} else
{
if (choice == 1)
{
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble();
double deuros = USamount * USrate;
double ddisburse = deuros - transfee;
System.out.print(
"\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ "
+ df.format(deuros) + "\n");
System.out.print(
"Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... "
+ df.format(ddisburse) + "\n");
} else
{
if (choice == 2)
{
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate;
double gdisburse = geuros - transfee;
System.out.print(
"\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ "
+ df.format(geuros) + "\n");
System.out.print(
"Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... "
+ df.format(gdisburse) + "\n");
} else
{
if (choice == 3)
{
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate;
double ydisburse = yeuros - transfee;
System.out.print("\nInput amount Yen:... "
+ YENamount + "\n");
System.out.print("Worth in euro's..... "
+ df.format(yeuros) + "\n");
System.out.print(
"Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. "
+ df.format(ydisburse) + "\n");
}
}
}
}
System.out.println("Do you want to do another calculation? (y/n)");
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
}
}
}
Setting the boolean variable to true first lets you enter the loop. The user will be asked as long as he types an y at the end. Every other character would exit the loop:
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
You could also check for explicit n, but that is up to you.
Put the code inside a while loop (while(true)). At the end of each if block
add one nested if.
System.out.print(Do you want to continue?");
if(in.next().equals("Y")) {
continue;
}
And you have add one extra menu(4th) for exit :
if(choice == 4){
break;
}
Any help would be appreciated.
I am not trying to list the operators, ( I know that it would work that way) i want to know if i can put them in a bundle as i attempted in my code below (it did not work, anyone knows why? how to fix it?):
}
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);
double answer;
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
String operator = token[1];//this is the operator
if (operator.equals(function)){
for (int i = 0; i<length; i++) {
}
System.out.println("Operation is " + token[1] + ", numbers are " + token[0] + " and " + token[2]);
}
else {
System.out.println("Your entry of "+ input + " is invalid");
}
}
first you should split .you can't access token[0] before declare tokens
String function = "[+\\-*/]+"; //this
String[] token = input.split(function );//and this
then use array[index]
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);
edit....
you should use .matches instead .equals because .equals looking for entire String not regular expression
complete code
Scanner scan = new Scanner(System.in);
System.out.println("enter your operation");
String input = scan.next();
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
double answer;
String operator = input.toCharArray()[token[0].length()]+"";
if (operator.matches(function) && (token[0]+token[1]+operator).length()==input.length()) {
System.out.println("Operation is " + operator+ ", numbers are " + token[0] + " and " + token[1]);
} else {
System.out.println("Your entry of " + input + " is invalid");
}
output>>
for input "2+3" > Operation is +, numbers are 2 and 3
for input "24+45" > Operation is +, numbers are 24 and 45
for input "2++4" > Your entry of 2++4 is invalid
the code may be like this
double answer;
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
String operator = input.substring(token[0].length,token[0].length+1)//this is the operator
if (token.length > 1){
System.out.println("Operation is " + token[1] + ", numbers are " + token[0] + " and " + token[2]);
}
else {
System.out.println("Your entry of "+ input + " is invalid");
}
}
Access token after splitting input
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);
And
String operator = token[1];//this is the operator
wont work because delimiter wont be there in the String array after splitting.
This program is designed to add 2 random numbers generated by the computer, when the user answer goes wrong , the computer tells the user to try it again, by using the while loop. The program will stop once the user enters a correct number. I have to calculate the wrong count in the while loop, however, it gives me the wrong count 1 when it is the second attempt.Please be kind enough to tell me where I go wrong in the code. Thank you.
import java.util.Scanner;
public class add {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = (int) (Math.random() * 10);
int num2 = (int) (Math.random() * 10);
int wrong = 0;
System.out.println("What is " + num1 + "+" + num2 + "=" + "?");
int answer = input.nextInt();
while (num1 + num2 != answer) {
System.out.println("Wrong answer, Try again . " +
"What is " + num1 + "+" + num2 + "? ");
answer = input.nextInt();
System.out.println("The number of attemt is " + wrong);
++wrong;
}
System.out.println("You got it correct !");
}
}
The error is in incrementing the number the user has gotten wrong AFTER printing "You got x wrong"
Just put ++wrong above System.out.println("The number of attemt is " + wrong);
while (num1 + num2 != answer) {
System.out.println("Wrong answer, Try again . " +
"What is " + num1 + "+" + num2 + "? ");
answer = input.nextInt();
++wrong;
System.out.println("The number of attemt is " + wrong);
}
Just change
wrong = 0
to
wrong = 1
wrong should probably be renamed to numberOfAttempts.
Initialize wrong to 1 instead of 0.
int wrong = 1;
A more appropriate name for the variable would be attempt if you take this approach.
You need to increment wrong before you display it:
import java.util.Scanner;
public class Add {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);
int num1 = (int)(Math.random() * 10);
int num2 = (int)(Math.random() * 10);
int wrong = 0 ;
System.out.println("What is " + num1 + "+" + num2 + "=" + "?");
int answer = input.nextInt();
while (num1 + num2 != answer){
wrong++ ;
System.out.println("Wrong answer, Try again . What is " + num1 +"+"+ num2 + "? " );
answer = input.nextInt();
System.out.println("The number of attempt is " + wrong);
}
System.out.println("You got it correct !");
}
}