Creating a calculator but can't exit - java

I need help with my coding. I am practicing again with my java programming and today I am creating a calculator that has the same function as the real calculator but again I run into errors and unable to figure out again.
Okay, the way I wanted my calculator to works is instead of getting line by line input from the user like this:-
In code output
Enter Number: 1
Enter Operator (+,-, /, *, ^ (Power) or s (Square): +
Enter Number: 2
Ans: 3
I wanted it to calculate when the user press enter like this:-
The Output that I want
enter number: 1+2*4
Ans: 12
So they can add as many long numbers as they want before they hit enter calculate. The users are supposed to be able to reset the number to when using the calculator while in the loop of the calculation.
at the beginning of the code, it will ask the user for an input to continue or exit the calculator. Then if continue it will run the calculation. The calculator will be looping until the users press E to exit the calculator and if exit it will exit the code.
This is where I have errors. First, I can't figure out how to break from the loop inside the looping calculator and second at the beginning of the code when the user press E it was supposed to exit the calculator but it didn't. The third error is when the user using the square to calculate I want it to get straight to show the answer instead of asking another number.
and I want to simplify the code in public static void main(String[] args)for the calculation part. Is it possible to put the switch case in method and call it inside the main? or do you have a suggestion on how to simplify the calculation part?
Please help me:(
public class TestingCalculator {
public static void main(String[] args){
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
String a = ans.next();
activateCalc = a.charAt(0);
while (activateCalc != 'E' || activateCalc != 'e') {
Scanner input = new Scanner(System.in);
System.out.print("Enter number: ");
String n =input.next();
numA = Double.parseDouble(n);
while (calculator = true) {
//User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); //User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA,numB);
break;
case '-':
answer =subtract(numA,numB);
break;
case '*':
answer = multiply(numA,numB);
break;
case '/':
answer = divide(numA,numB);
break;
case '^':
answer = power(numA, numB);
break;
case 's':
case 'S':
answer = Math.pow(numA, 2);
break;
}
//The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator: ");
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
}
}
ans.close();
}
//Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
}

Instead of trying to identify the problems with your application, I decided to focus on producing a program that works the way you want (with the input you specified). The code was a little big, but I tried to leave it well commented for you to understand what I did. I know that some things may still be a little confusing, so I will simulate running the program to try to make it clearer how it works.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestingCalculator
{
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Evaluates a mathematical expression.
*
* #param line Mathematical expression. This line cannot have blank
* spaces
* #return Result of this mathematical expression
*/
public static String calc(String line)
{
while (!hasOnlyNumbers(line)) {
// Checks if line has parentheses
if (line.contains("(")) {
// Get index of the most nested parentheses
int parentheses_begin = line.lastIndexOf("(");
int parentheses_end = line.substring(parentheses_begin).indexOf(")");
String ans = calc(line.substring(parentheses_begin+1, parentheses_end));
// Replaces content of parentheses with the result obtained
if (line.length()-1 >= parentheses_end+1)
line = line.substring(0,parentheses_begin)+ans+line.substring(parentheses_end+1);
else
line = line.substring(0,parentheses_begin)+ans;
}
// Checks if line has potentiation operator
else if (line.contains("^")) {
int opIndex = line.indexOf("^");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = power(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has square operator
else if (line.contains("s")) {
int opIndex = line.indexOf("s");
String n1 = extractFirstNumber(line, opIndex);
double ans = square(Double.valueOf(n1));
line = calc(parseLine(line, n1, opIndex, ans));
}
// Checks if line has multiplication operator
else if (line.contains("*")) {
int opIndex = line.indexOf("*");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = multiply(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has division operator
else if (line.contains("/")) {
int opIndex = line.indexOf("/");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = divide(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has sum operator
else if (line.contains("+")) {
int opIndex = line.indexOf("+");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = add(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has subtraction operator
else if (line.contains("-")) {
int opIndex = line.indexOf("-");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = subtract(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
}
// Returns line only when it has only numbers
return line;
}
/**
* Checks if a line contains only numbers.
*
* #param line Line to be analyzed
* #return If a line contains only numbers
*/
private static boolean hasOnlyNumbers(String line)
{
return line.matches("^[0-9.]+$");
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param n2 Number to the right of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, String n2, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
int lenSecondNumber = n2.length();
if (line.length()-1 >= opIndex+lenSecondNumber+1)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+lenSecondNumber+1);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
if (line.length()-1 >= opIndex+2)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+2);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Extracts the first number from an operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 2 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the left of the operator
*/
private static String extractFirstNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex-1;
while (i>=0 && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i--;
}
// Reverses the result, since the number is taken from the end to the
// beginning
num = num.reverse();
return num.toString();
}
/**
* Extracts the second number from a math operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 3 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the right of the operator
*/
private static String extractSecondNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex+1;
while (i<line.length() && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i++;
}
return num.toString();
}
// Method for the operators.
private static double add(double numA, double numB)
{
double answer = numA + numB;
return answer;
}
private static double subtract(double numA, double numB)
{
double answer = numA - numB;
return answer;
}
private static double multiply(double numA, double numB)
{
double answer = numA * numB;
return answer;
}
private static double divide(double numA, double numB)
{
double answer = numA / numB;
return answer;
}
private static double power(double numA, double numB)
{
int answer = (int) Math.pow(numA, numB);
return answer;
}
private static double square(double num)
{
int answer = (int) Math.pow(num, 2);
return answer;
}
//-------------------------------------------------------------------------
// Main
//-------------------------------------------------------------------------
public static void main(String[] args) throws IOException
{
char option;
String inputLine = "";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
option = input.readLine().charAt(0);
while (option != 'E' && option != 'e') {
// Gets user input
System.out.print("Enter mathematical expression: ");
inputLine += input.readLine();
// Processes input
inputLine = inputLine.replaceAll(" ", "");
inputLine = inputLine.replaceAll("S", "s");
// Evaluates input
System.out.println("Evaluating...");
String ans = TestingCalculator.calc(inputLine);
// Displays answer
System.out.println("Ans: "+ans);
// Checks if the user wants to continue running the program
System.out.print("Press E to Exit the calculator: ");
inputLine = input.readLine();
if (inputLine.length() > 0)
option = inputLine.charAt(0);
}
input.close();
}
}
Output
Enter mathematical expression: (1+2*4)/3
Evaluating...
Ans: 3.0
Output 2
Enter mathematical expression: 1+2*9/3
Evaluating...
Ans: 7.0
Desk checking
Input: (1+2*4)/3
calc( (1+2*4)/3 )
not hasOnlyNumbers( (1+2*4)/3) ) ? true
( (1+2*4)/3) ) contains '(' ? true
int parentheses_begin = 0
int parentheses_end = 6
String ans = calc( 1+2*4 )
calc( 1+2*4 )
not hasOnlyNumbers( 1+2*4 ) ? true
( 1+2*4 ) contains '(' ? false
( 1+2*4 ) contains '^' ? false
( 1+2*4 ) contains 's' ? false
( 1+2*4 ) contains '*' ? true
int opIndex = 3
int n1 = 2
int n2 = 4
String ans = n1 * n2 = 2 * 4 = 8
line = calc( 1+8 )
calc( 1+8 )
not hasOnlyNumbers( 1+8 ) ? true
( 1+8 ) contains '(' ? false
( 1+8 ) contains '^' ? false
( 1+8 ) contains 's' ? false
( 1+8 ) contains '*' ? false
( 1+8 ) contains '/' ? false
( 1+8 ) contains '+' ? true
int opIndex = 1
int n1 = 1
int n2 = 8
String ans = n1 + n2 = 1 + 8 = 9
line = calc( 9 )
calc( 9 )
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
ans = 9
(9-1 >= 6+1) ? true
line = 9/3
not hasOnlyNumbers( 9/3 ) ? true
( 9/3 ) contains '(' ? false
( 9/3 ) contains '^' ? false
( 9/3 ) contains 's' ? false
( 9/3 ) contains '*' ? false
( 9/3 ) contains '/' ? true
int opIndex = 1
String n1 = 9
String n2 = 3
double ans = 9 / 3 = 3
line = calc( 3 )
calc( 3 )
not hasOnlyNumbers( 3 ) ? false
return 3
line = 3
not hasOnlyNumbers( 3 ) ? false
return 3
Some observations
No checks are made to see if the user-provided input is valid
It is important to maintain the order of operations that are verified in the calc method, in order to maintain precedence between operators (exponentiation / radication must be done first, followed by multiplication / division and finally addition / subtraction operations)
I had problems with the Scanner class, so I used BufferedReader to read the input
Square operation must be done as follows: <num>s or <num>S
Hope this helps. If you don't understand something, tell me I can explain it to you.

try below code and one suggestion try to handle the negative scenarios as well.
public static void main(String[] args) {
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
Scanner input = new Scanner(System.in);
activateCalc = input.next().charAt(0);
while (true) {
if (activateCalc != 'E' && activateCalc != 'e') {
System.out.print("Enter number: ");
String n = input.next();
numA = Double.parseDouble(n);
// User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); // User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA, numB);
break;
case '-':
answer = subtract(numA, numB);
break;
case '*':
answer = multiply(numA, numB);
break;
case '/':
answer = divide(numA, numB);
break;
case '^':
answer = power(numA, numB);
break;
case 'S':
case 's':
answer = Math.pow(numA, 2);
break;
default:
answer = 0;
}
// The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator or Y to continue : ");
activateCalc = input.next().charAt(0);
if(activateCalc != 'E' && activateCalc != 'e')continue;
}
System.out.println("Thank you for using the calculator. By :) ");
ans.close();
break;
}
}
// Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}

This question requires debugging details so here we go:
Your code does not seem to compile because of the error:
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
where you had to use comparison == operator instead of assignment =.
Similar issue is in your inner loop while (calculator = true) - and there's a warning that this value is never used - but this does not affect much.
You cannot exit the loop because you never check the input for exit, it should be:
System.out.println("Press E to Exit the calculator: ");
activateCalc = input.next().charAt(0);
But even if you updated activateCalc, you'd get into endless loop anyway because of the error in this condition while (activateCalc != 'E' || activateCalc != 'e') -- even if user presses 'e', or 'E' this condition is always true.

Related

java.lang.StringOutOfBoundsException can't figure it out

This code is supposed to get check whether a number is a palindrome.
Whenever I run the method check Palindrome its comes up with a java.lang.StringOutOfBoundsException.
Please help.
import java.util.*;
/**
* Lab 1 .
* #author Kevin Rasquinha
* #version 30 July 2016
*/
public class Lab1
{
private Scanner scan = new Scanner(System.in);
/**
* count the number of digits in a number
* #param num the number to analyse
* #return the number of digits it has
*/
public int numDigits (int num)
{
int nDigits = 0;
int digit;
while (num>0)
{
digit = num % 10; // take off the last digit
num = num /10; // reduce the number
nDigits = nDigits + 1; // increment count of digits
}
return nDigits;
}
/**
* Read a number from the keyboard, and report how many digits it has.
* Ensure the number is within a desired range.
*/
public void countDigits ()
{
int num=0;
while (num<1 || num > 1000)
{
System.out.print("What number (1 to 1000)? ");
num = scan.nextInt();
scan.nextLine();
System.out.println("Num = " + num);
if (num<1 || num > 1000)
System.out.println("1 to 1000, please");
}
System.out.println (num + " has " + numDigits(num) + " digits");
}
/**
* method used to if a number is the sum of the cube of its digits
* #param args (not used)
*/
public void sumCubesDigits ()
{
for (int initial = 1; initial < 1000; initial ++)
{
int num = initial;
int thirddig = num%10;
num = num / 10;
int secdig = num%10;
num = num / 10;
int firstdig = num%10;
int sum = (thirddig*thirddig*thirddig) + (secdig*secdig*secdig) + (firstdig*firstdig*firstdig);
if (sum == initial)
{
System.out.println ("The number " + initial + " is equal to the sum of the cube of its digits.");
}
}
}
/**
* Recieves an int and writes the same int backwards
* #param args (not used)
*/
public int backwards(int num)
{
int rev = 0;
int value = num;
while (value != 0)
{
rev = rev*10;
rev = rev + value%10;
value /= 10;
}
return rev;
}
/**
* Receives digit from method backwards
* Asses whether backwards = the original number
* #param args (not used)
*/
public boolean palindrome (int num, int digit)
{
boolean a = false;
int normal = num;
int reversed = digit;
if( reversed == digit)
{
a = true;
}
return a;
}
/**
* Recieves int from user - num
* Sends num to backwards
* Sends num to palindrome
* Recieves boolean from palindrome
* Outputs message to user
*/
public void checkPalindrome ()
{
System.out.println ("Enter number to be see if it is a palindrome");
int num = scan.nextInt();
int digit = backwards(num);
boolean check = palindrome (num, digit);
if (check = true)
{
System.out.println("Your number is a palindrome");
}
}
/**
* Present a menu to the user, and obtain their selection. If they
* type an erroneous value, report it and try again. Either upper
* case or lower case input is accepted.
* #return an upper case character showing the user's choice
*/
public char menuChoice ()
{
System.out.println("");
System.out.println("What do you want to do?");
System.out.println("(c) Count the digits in a number");
System.out.println("(g) Find out the numbers where the the sum of the cube of its digits is equal to it");
System.out.println("(p) Find out if a number is a palindrome");
System.out.println("(q) Quit");
System.out.print("Your choice? ");
char answer = ' ';
boolean ok = false;
while (! ok)
{
answer = scan.nextLine().trim().toUpperCase().charAt(0);
ok = (answer == 'C' || answer == 'Q' || answer == 'G' || answer == 'P');
if (! ok)
{
System.out.println("Please type one of c,C,q,Q,g,G,p,P");
System.out.print("Your choice? ");
}
}
return answer;
}
/**
* test driver for the program
*/
public void test()
{
char answer = ' ';
while (answer != 'Q')
{
answer = menuChoice();
switch (answer)
{
case 'C': countDigits(); break;
case 'G': sumCubesDigits(); break;
case 'P': checkPalindrome();break;
case 'Q': break;
}
}
}
/**
* main program: create a test driver and let it loose
* #param args (not used)
*/
public static void main (String [] args)
{
Lab1 l1 = new Lab1();
l1.test();
}
}
A StringIndexOutOfBoundsException is mostly thrown when you use charAt to select a character from a string that isn't there.
I guess your issue is here:
answer = scan.nextLine().trim().toUpperCase().charAt(0);
because that is the only charAt in your code.
What would that line do if the user entered nothing? Throw an Exception of course!
You should change if (check = true) to if (check == true) and answer = scan.nextLine().trim().toUpperCase().charAt(0); to answer = scan.nextLine();
if(answer != null)
answer = answer.trim().toUpperCase().charAt(0);

How to use math operators from commandline in program?

I try to calculate digits (in my calculator) in args from commandline. Example:
args[0] = 2*3;
String result = method(args[0]);
System.out.println(result) // should be 6
I don't know how to use my char between two digits example "+", "-". I can't use loops. My method idea is use charAt like:
char a = arg.charAt(0);
char b = arg.charAt(1);
char c = arg.charAt(2);
But I don't know to change my b char (*) to do calculation.
You are not passing the value correctly. Your input is a String, right? Your code shows an integer expression.
args[0] = "2*3"; //note that this changed to a string
double result = parse(args[0]);
System.out.println(result) // should be 6
Then you can parse your string in your method:
double parse(String str){
int num1 = Integer.valueOf(str.substring(0,1));
char operator = str.charAt(1);
int num2 = Integer.valueOf(str.substring(2,3));
switch(operator){
case '+': return num1+num2;
case '-': return num1-num2;
case '*': return num1*num2;
case '/': return num1/num2;
default: throw new IllegalArgumentException();
}
}
Running System.out.println(parse("2*3")); prints 6.0 with my code.
Of course this only works with operands that have exactly one digit. But that's a restriction that comes from your charAt idea.
I'm not normally using JAVA, but..
You will get the input as a string, if you run a process like this:
> MyCalculator 2*3
now, you want to separate this string into three parts:
Number1, Operation, Number2
for this you can do something like:
String[] parts = args[0].split("\\*");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
now, you may notice that you'll be missing the operator..
so you want locate it and fetch it, or you can do something like this:
if( args[0].indexOf("*") > -1)
{
System.out.println(Number1 * Number2);
}
edit:
for more flexibillity, you may want to do it the opposite way around:
if( args[0].indexOf("*") > -1)
{
String[] parts = args[0].split("\\*");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
System.out.println(Number1 * Number2);
}
if( args[0].indexOf("/") > -1)
{
String[] parts = args[0].split("/");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
System.out.println(Number1 / Number2);
}
etc...
notice that "-" will be especially annoying
Its not the best solution but it works, you can enter numbers of any length.
String[] number = args[0].split("[*]|[/]|[+]|[-]");
int stringLength = args[0].length();
int operatorBeginning = number[0].length();
int operatorEnd = stringLength - number[1].length();
String operator = args[0].substring(operatorBeginning,operatorEnd);
double answer = 0;
switch(operator) {
case "*":
answer = Integer.valueOf(number[0]) * Integer.valueOf(number[1]);
break;
case "/":
answer = Integer.valueOf(number[0]) / Integer.valueOf(number[1]);
break;
case "+":
answer = Integer.valueOf(number[0]) + Integer.valueOf(number[1]);
break;
case "-":
answer = Integer.valueOf(number[0]) - Integer.valueOf(number[1]);
break;
default:
System.out.println("Wrong operator");
break;
}
System.out.println(answer);

Try-Catch option does not run in Java

I am trying to write a Decimal & Binary converter in Java. I am trying to use try & catch option for error handling. Such as, if any one input "a" as binary number, it will print "Wrong Input". I have used parse and try-catch for this function. But it is not working. I am trying to find out the problem, but I am failed to find it. Could anyone help me in this code? When I write "1" for binary to decimal conversion, it goes to the end of the code.
The whole code is here:
package binary.with.decimal;
import java.util.Scanner;
public class RiaJava {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int binaryp = 0;
int n;
int base = 2;
int result = 0;
int multiplier = 1;
System.out.println("1.Binary to Decimal \n 2.Decimal to Binary");
System.out.println("Enter Your Option Number:");
n = scan.nextInt();
switch (n) {
case 1:
System.out.println("Input Binary Number:");
String binary = scan.nextLine();
scan.close();
try {
binaryp = Integer.parseInt(binary);
}
catch (NumberFormatException e) {
System.out.println("Wrong Input!!!");
}
while (binaryp > 0) {
int residue = binaryp % base;
binaryp = binaryp / base;
result = result + residue * multiplier;
multiplier = multiplier * 10;
}
System.out.println("Decimal....." + result);
break;
case 2:
System.out.println("Input Decimal Number:");
int decimal = scan.nextInt();
scan.close();
while (decimal > 0) {
int residue = decimal % base;
decimal = decimal / base;
result = result + residue * multiplier;
multiplier = multiplier * 10;
}
System.out.println("Binary....." + result);
break;
default:
System.out.println("you have selected wrong option number");
break;
}
}
}
scan.nextLine() should be scan.next()
nextLine() doesn't wait for user input, but reads the remaining buffer until the next end of line.

Input a Special Character then use in a switch case [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a calculator between fractions and that if the user inputs a +,-,*, or / it will correspond in the case. This is the code I have so far:
import java.util.Scanner;
public class calculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String x,y;
System.out.println("Enter first fraction in a / b form: ");
x = input.nextLine();
System.out.println("Enter operation: ");
char z = input.next().charAt(0);
System.out.println("Enter second fraction in c / d form: ");
y = input.nextLine();
String aString = x.substring(0,1);
String bString = x.substring(4,5);
String cString = x.substring(0,1);
String dString = x.substring(4,5);
int a = Integer.parseInt(aString);
int b = Integer.parseInt(bString);
int c = Integer.parseInt(cString);
int d = Integer.parseInt(dString);
int answer = 0;
switch (z)
{
case '+':
answer = (a/b) + (c/d);
break;
case '-':
answer = (a/b) - (c/d);
break;
case '*':
answer = (a/b) * (c/d);
break;
case '/':
answer = (a/b) /(c/d);
break;
default:
System.out.println("ERROR");
break;
}
System.out.println("Answer = " + answer);
}
}
OUTPUT SHOULD BE
Enter first fraction in a / b form:
1 / 2
Enter operation:
+
Enter second fraction in c / d form:
2 / 5
answer = 9/10
The problem is here
String aString = x.substring(0,1);
String bString = x.substring(4,5);
String cString = x.substring(0,1);
String dString = x.substring(4,5);
a=c and b=d
These two line
String cString = x.substring(0,1);
String dString = x.substring(4,5);
should be
String cString = y.substring(0,1);
String dString = y.substring(4,5);
Before switch print the values of a b c d z then you will come to know about your correctness.
One more thing is, you are doing division of int variables so the result will be in int only.
I suggest you to change the types of a b c d and answer to double and use Double.parseDouble() for converting string to double.
This problem is so suited for OOP, an extra class:
public class Q {
public final int numerator;
public final int denominator;
public static Q valueOf(String representation) {
Pattern pattern = Pattern.compile("([-]?\\d+) *[/:] *([-]?\\d+)");
Matcher matcher = pattern.matcher(representation.trim());
if (!matcher.matches()) {
throw new IllegalArgumentException(
"Not a quotient (like '3/4'): " + representation);
}
int num = Integer.parseInt(matcher.group(1));
int den = Integer.parseInt(matcher.group(2));
return new Q(num, den);
}
public Q(int num, int den) {
if (den < 0) {
den = -den;
num = -num;
}
int c = gcd(Math.abs(den), Math.abs(num));
denominator = den / c;
numerator = num / c;
}
#Override
public String toString() {
return numerator + "/" + denominator;
}
public Q add(Q rhs) {
int c = gcd(denominator, rhs.denominator);
int den = (denominator / c) * rhs.denominator;
int num = numerator * (rhs.denominator / c)
+ rhs.numerator * (denominator / c);
return new Q(num, den);
}
public Q mult(Q rhs) {
int den = denominator * rhs.denominator;
int num = numerator * rhs.numerator;
return new Q(num, den);
}
public static int gcd(int x, int y) {
assert x >= 0 && y >= 0;
while (x != y) {
if (x > y) {
x -= y;
} else {
y -= x;
}
}
return x;
}
}
Using this class several small problematic code parts disappear.

Need help making a random math generator

What I am supposed to do is this:Write a program that gives the user 10 random math problems, asks for the answer each time, and then tells the user if they were right or wrong. Each problem should use 2 random numbers between 1 and 20, and a random operation (+, -, *, or /). You will need to re-randomize the numbers for each math problem. You should also keep track of how many problems they get right. At the end, tell the user how many problems they got right and give them a message based on their result. For example, you may say “good job” or “you need more practice.”
So far I am at a loss
import java.util.Scanner;
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
if (operator == 1)
System.out.println("+");
if (operator == 2)
System.out.println("-");
if (operator == 3)
System.out.println("*");
if (operator == 4)
System.out.println("/");
}
}
I mostly need to know how to turn these random numbers and operators into a problem, and how to grade each question to see if they are wrong.
Well, what you need to add is:
to count answers:
a variable that counts correct answers (increment it every time the user answers correctly);
a variable to store current correct answer;
a variable to store current user answer (refresh it every next problem, no need to store it forever, cause in your case only statistics is needed);
a function (let it be called e.g. gradeTheStudent() ) which uses several conditions to decide what to print out according to number of correct answers;
to create a problem:
put problem generation and answer evaluation into a cycle, which repeats 10 times;
in your switch (i.e. when you choose operators) also calculate the correct answer:
switch(operator){
case 1: {
operation = "+";
correctResult = number1 + number2;
break;
}
case 2: ....
case 3: ....
case 4: ....
default: break;
}
don't forget to check if the user entered a number or something else (you could use either an Exception or a simple condition).
So, a "pseudocode"solution for your problem would look something like this:
String[] reactions = ["Awesome!","Not bad!","Try again and you will get better!"]
num1 = 0
num2 = 0
operator = NIL
userScore = 0
userAnswer = 0
correctAnswer = 0
def function main:
counter = 0
for counter in range 0 to 10:
generateRandomNumbers()
correctAnswer = generateOperatorAndCorrectAnswer()
printQuestion()
compareResult()
gradeStudent()
def function generateRandomNumbers:
# note that you have already done it!
def function generateOperatorAndCorrectAnswer:
# here goes our switch!
return(correctAnswer);
def function printQuestion:
print "Next problem:" + "\n"
print num1 + " " + operator + " " + num2 + " = " + "\n"
def function compareResult(correctAnswer):
# get user result - in your case with scanner
if(result == correctAnswer)
print "Great job! Correct answer! \n"
userScore++
else print "Sorry, answer is wrong =( \n"
def function gradeStudent (numOfCorrectAnswers):
if(numOfCorrectAnswers >= 7) print reactions[0]
else if(numOfCorrectAnswers < 7 and numOfCorrectAnswers >= 4) print reactions[1]
else print reactions[2]
General advice: don't try to solve the problem all at once. A good approach is to create small functions, each doing its unique task. The same with problem decomposition : you just should write down what you think you need in order to model the situation and then do it step by step.
Note: as far as I can see from your current function, you are not familiar with object oriented programming in Java. This is why I am not providing any tips about how great it would be to use classes. However, if you are, then please let me know, I will add info to my post.
Good luck!
For example you can use something like that:
public class Problem {
private static final int DEFAULT_MIN_VALUE = 2;
private static final int DEFAULT_MAX_VALUE = 20;
private int number1;
private int number2;
private Operation operation;
private Problem(){
}
public static Problem generateRandomProblem(){
return generateRandomProblem(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);
}
public static Problem generateRandomProblem(int minValue, int maxValue){
Problem prob = new Problem();
Random randomGen = new Random();
int number1 = randomGen.nextInt(maxValue + minValue) + minValue;
int number2 = randomGen.nextInt(maxValue + minValue) + minValue;
prob.setNumber1(number1);
prob.setNumber2(number2);
int operationCode = randomGen.nextInt(4);
Operation operation = Operation.getOperationByCode(operationCode);
prob.setOperation(operation);
return prob;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public Operation getOperation() {
return operation;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
And another class for holding operations:
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE;
public double operationResult(int n1, int n2) {
switch (this) {
case PLUS: {
return (n1 + n2);
}
case MINUS: {
return n1 - n2;
}
case MULTIPLY: {
return n1 * n2;
}
case DIVIDE: {
return n1 / n2;
}
}
throw new IllegalArgumentException("Behavior for operation is not specified.");
}
public static Operation getOperationByCode(int code) {
switch (code) {
case 1:
return PLUS;
case 2:
return MINUS;
case 3:
return MULTIPLY;
case 4:
return DIVIDE;
}
throw new IllegalArgumentException("Operation with this code not found.");
}
}
But you not must throw IllegalArgumentException, there are another options for handling unexpected arguments.
Printout the numbers and the operation , read the user input using file IO , and perform your logic of keeping a track of answered questions
Code :
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
if (operator == 1)
operation="+";
if (operator == 2)
operation="-";
if (operator == 3)
operation="*";
if (operator == 4)
operation="/";
System.out.println("Question "+number1+operation+number2);
}
}
Keep a track of result and compare with the user input and verify its right or wrong
public static void main(String[] args) throws IOException{
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
int result=0;
if (operator == 1){
operation="+";
result=number1+number2;
}
if (operator == 2) {
operation="-";
result=number1-number2;
}
if (operator == 3){
operation="*";
result=number1*number2;
}
if (operator == 4){
operation="/";
result=number1/number2;
}
System.out.println("Question "+number1+operation+number2);
String result1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
if(result==Integer.parseInt(result1))
System.out.println("Right");
else
System.out.println("Wrong");
}
Since I do not want to hand you a full solution to this problem, and you seem to have some knowledge in the Java language I will just write down how I would continue/change what you have as a start.
First I would store the result in your operator if statements. Result is an int.
if (operator == 1) {
operation="+";
result=number1+number2;
}
After this I would print the math question and wait for the user to answer.
System.out.println("What is the answer to question: " +number1+operation+number2);
userResult = in.nextLine(); // Read one line from the console.
in.close(); // Not really necessary, but a good habit.
At this stage all you have to do is compare the result with the user input and print a message.
if(Integer.parseInt(userResult) == result) {
System.out.println("You are correct!");
} else {
System.out.println("This was unfortunately not correct.");
}
This solution is more or less psudo code and some error handling (if user enters test in the answer for example) is missing, also I would split it up into methods rather than have it all in main(). Next step would be to make it object oriented (Have a look at the answer from demi). Good luck in finalizing your program.
In regard to generating random math operations with +, -, * & / with random numbers your can try the following;
import java.util.*;
public class RandomOperations{
public static void main(String[] args){
Random `mathPro` = new Random();
//for the numbers in the game
int a = mathPro.nextInt(50)+1;
int b = mathPro.nextInt(50)+1;
//for the all the math operation result
int add = a+b;
int sub = a-b;
int mult = a*b;
int div = a/b;
//for the operators in the game
int x = mathPro.nextInt(4);
/*
-so every random number between 1 and 4 will represent a math operator
1 = +
2 = -
3 = x
4 = /
*/
if(x == 1){
System.out.println("addition");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(add);
}else if(x == 2){
System.out.println("subtraction");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(sub);
}else if(x == 3){
System.out.println("multiplication");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(mult);
}else{
System.out.println("division");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(div);
}
//This os for the user to get his input then convert it to a numbers that the program can
//understand
Scanner userAnswer = new Scanner(System.in);
System.out.println("Give it a try");
int n = `userAnswer.nextInt();

Categories

Resources