i cant get my calculator to work - java

i want to input a int to get first number then use a string to get the operator and another int for the second number. user should input some thing like 10+20.
but as soon as i enter the "+" then i get an error why?
cuz it works if i manually add the values into the sum.calc(); myself like sum.calc(12, "+", 24); then it works ill get 36
PART 1:
import java.util.Scanner;
public static void main(String[] args) {
math sum = new math();
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
String b = input.nextLine();
double c = input.nextDouble();
sum.calc(a, b, c);
input.close();
}
PART 2:
public class math {
public void calc(double a, String b, double c){
double t;
switch(b){
case "+":
t = a + c;
System.out.println(a+" + "+c+" = "+t);
break;
case "-":
t = a - c;
System.out.println(a+" - "+c+" = "+t);
break;
case "*":
t = a * c;
System.out.println(a+" * "+c+" = "+t);
break;
case "/":
t = a / c;
System.out.println(a+" / "+c+" = "+t);
break;
}
}
}

Try using input.next(); instead of input.nextLine(); Because input.nextLine(); advances this scanner past the current line and returns the input that was skipped. so if your input was 20, +, and 24, your method calc would get 20,24,null.

input.next() works instead of input.nextLine() for strings.Try it out

Related

Java - How do I ask input from user to continue or stop at his/her wish? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am a beginner, and I would like to know on how do I get this program out of bugs-
public class Calculator
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("*******************************************");
System.out.println("MC MR MS M+ M-");
System.out.println("<- CE C +- √");
System.out.println("7 8 9 / %");
System.out.println("4 5 6 * 1/x");
System.out.println("1 2 3 - ");
System.out.println(" 0 . + ");
System.out.println(" = ");
System.out.println("*******************************************");
System.out.println("");
boolean stop = false;
do {
System.out.println("Please type the number you want to operate upon:");
double x = sc.nextDouble();
System.out.println("Please type the number you want to use to operate:");
double y = sc.nextDouble();
System.out.println("Type the operators. Available operators:\n1. +\n2. -\n3. *\n4. /\n5. %\n6. ^");
char ch = sc.next().charAt(0);
switch(ch) {
case '+':
double a = x + y;
System.out.println("Result of adding the two numbers: " + a);
break;
case '-':
double s = x - y;
System.out.println("Result of subtracting two numbers: " + s);
break;
case '*':
double m = x * y;
System.out.println("Result of multiplying two numbers: " + m);
break;
case '/':
double d = x / y;
System.out.println("Result of dividing two numbers: " + d);
break;
case '%':
double mod = x % y;
System.out.println("Result of the remainder when dividing two numbers: " + mod);
break;
case '^':
double p = Math.pow(x,y);
System.out.println("Result of squaring the number: " + p);
break;
default:
System.out.println("Invalid operator.");
break;
}
System.out.println("Continue? Type Y to continue or N to end: ");
String st = sc.nextLine();
if(st.equals("n")) {
stop = true;
}
else {
stop = false;
}
} while(!stop);
}
}
There are no errors at all, these are my wrong-doings in the program. After all the calculations are done, it puts me through a loop, and I don't seem to quite figure it out, on how to get the user input. It comes back to the start.
This is all I can put up, since I really don't have much to tell, if anything, I will edit this questions as users ask questions.
Thanks:)
Replace String st = sc.nextLine() by String st = sc.next().
At this point the scanner has a line break in its buffer (remaining from reading the operator).
nextLine() returns whatever is left in the buffer, it does not wait for additional user input.
By calling next() instead you tell the scanner that you want to read another token. The line break is less than a token, so Scanner waits for additional user input.
You should put a nextLine(); after every nextFoo(); to consume the new line character
Also change to sc.nextLine().charAt(0); as suggested in the comments
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("*******************************************");
System.out.println("MC MR MS M+ M-");
System.out.println("<- CE C +- √");
System.out.println("7 8 9 / %");
System.out.println("4 5 6 * 1/x");
System.out.println("1 2 3 - ");
System.out.println(" 0 . + ");
System.out.println(" = ");
System.out.println("*******************************************");
System.out.println("");
boolean stop = false;
do {
System.out.println("Please type the number you want to operate upon:");
double x = sc.nextDouble();
sc.nextLine();//consume next line character
System.out.println("Please type the number you want to use to operate:");
double y = sc.nextDouble();
sc.nextLine();//consume next line character
System.out.println("Type the operators. Available operators:\n1. +\n2. -\n3. *\n4. /\n5. %\n6. ^");
char ch = sc.nextLine().charAt(0);//change
switch(ch) {
case '+':
double a = x + y;
System.out.println("Result of adding the two numbers: " + a);
break;
case '-':
double s = x - y;
System.out.println("Result of subtracting two numbers: " + s);
break;
case '*':
double m = x * y;
System.out.println("Result of multiplying two numbers: " + m);
break;
case '/':
double d = x / y;
System.out.println("Result of dividing two numbers: " + d);
break;
case '%':
double mod = x % y;
System.out.println("Result of the remainder when dividing two numbers: " + mod);
break;
case '^':
double p = Math.pow(x,y);
System.out.println("Result of squaring the number: " + p);
break;
default:
System.out.println("Invalid operator.");
break;
}
// better check
String st ="";
do {
System.out.println("Continue? Type Y to continue or N to end: ");
st = sc.nextLine();
}while (!st.equals("N") || !st.equals("Y"));
if(st.equals("N")) {
stop = true;
}
else if (st.equals("Y")) {
stop = false;
}
} while(!stop);
}
}
Note that you didn't do a very good check to see if user wants to continue
I just suggest using something like this
More info about your problem

Clumsy Java Calc that won't compile

I'm a newbie at programming, so that this piece of code keeps me scratching my head as it won't compile. Net Beans suggests to add return 0 and afterwards the code compiles successfully. However, the part after the printing to console Anything else to calculate? couldn't handle the input properly, displaying Please, enter a valid answer regardless of the input data.
package calc;
import java.util.Scanner;
public class Calc {
public static void main(String[] args){
Calculator();
}
static double sum (double val1, double val2){
return val1 + val2;
}
static double substract (double val1, double val2) {
return val1 - val2;
}
static double multiply (double val1, double val2) {
return val1 * val2;
}
static double divide (double val1, double val2) {
return val1 / val2;
}
public static double Calculator(){
Scanner reader = new Scanner(System.in);
System.out.println(" Enter the first number, please");
double x = reader.nextDouble();
System.out.println("Enter the second number, please");
double y = reader.nextDouble();
System.out.println("Enter desired operation, please");
char z = reader.next().charAt(0);
switch(z)
{
case '+':
double a = sum(x,y);
System.out.println(a);
break;
case '-':
double b = substract(x,y);
System.out.println(b);
break;
case '*':
double c = multiply(x,y);
System.out.println(c);
break;
case '/':
double d = divide (x,y);
System.out.println(d);
break;
}
System.out.println("Anything else to calculate?");
Scanner reader2 = new Scanner(System.in);
String Answer = reader2.nextLine();
if (Answer == "yes") {
Calculator();
} else if (Answer == "no") {
System.out.println("Thank you for using our Calculator app");
} else {
System.out.println("Please, enter a valid answer");
}
}
You don't compare strings using == instead you use equals() or even better in this case equalsIgnoreCase
if (Answer.equalsIgnoreCase("yes")) {
Calculator();
} else if (Answer.equalsIgnoreCase("no")) {
System.out.println("Thank you for using our Calculator app");
}
Dear as the function Calculator is having a double return type so any how it should return a double value.But as per your code you are not returning anything
and simply printing the result in console so no need of defining the return type of function to double mark it as void.I hope this will make you understand the concept.

Calculate and equation with a operator the user put in - Java

i am new to java and have been trying to learn it for a while now. This program that i am making is a basic calculator, but with the user inputting their choice of operation. I am having trouble finding out a way to put the 3 variables/operators together.
Here is what I've got.
package calulator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String first;
String second;
String operator;
int numone;
int numtwo;
int answer;
System.out.println("Enter first number.");
first = scanner.nextLine();
numone = Integer.parseInt(first);
System.out.println("Enter operator.");
operator = scanner.nextLine();
//also don't know if i should convert this to a char or a string.
System.out.println("Enter Second number.");
second = scanner.nextLine();
numtwo = Integer.parseInt(second);
answer = numone + operator + numtwo;
//I need a way so ^^^^ that you can implement the operator.
System.out.println(answer);
}
}
switch(operator) {
case "+": answer = numone + numtwo; break;
case "-": answer = numone - numtwo; break;
case "*": answer = numone * numtwo; break;
case "/": answer = numone / numtwo; break;
// any other operators you want go here
default: throw new RuntimeException(operator+" isn't a valid operator!");
}
There is not a shorter way.

Why does my calculator automatically answer "0" before i can put my sign in?

Somewhere around line 15 it gives me issues.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes= sc.nextLine();
if(yes.equalsIgnoreCase("yes")) {
return;
}
}
}
it answers "0" whatever I enter before I can put in my sign
Enter your first number
9
Enter your second number
9
Enter your sign (+ , - , /, *)
0
To continue type yes
please tell me what I did wrong and possibly correct it so I can understand further
Try changing your sc.nextInt() lines to Integer.parseInt(sc.nextLine()). This should make your code work correctly.
EDIT: updated the code to include a while loop to make it so you can do multiple runs per your comment. This would also require you changing your last if statement to break; instead of return;
Scanner sc = new Scanner(System. in ); //scanner object created
while (true) {
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if (anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
} else if (anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
} else if (anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
} else if (anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes = sc.nextLine();
if (!yes.equalsIgnoreCase("yes")) {
break;
}
}
Change
String anvin = sc.nextLine();
to
String anvin = sc.next();
Also keep in mind that you might divide through zero ;-)
Edit:
also change
String yes= sc.nextLine();
to
String yes= sc.next();
Instead of sc.nextLine(); use sc.next();
I would suggest you this, you can not only learn using objects but learn a better way of writing managed codes too,
Calculator.java -> a class
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Instantiate
Scanner input = new Scanner(System.in);
Calculations calc = new Calculations();
// Variable declarations
double answer = 0, entry1 , entry2 ;
char operator;
// Start
System.out.println("***** Welcome to the Command line calculator program *****");
System.out.print("Please enter the first number :");
entry1 = input.nextDouble();
System.out.print("Please enter the second number:");
entry2 = input.nextDouble();
System.out.println("Please enter the operation : ");
System.out.println("***** Operations :- + -> Add ; - ->Substract ; / -> Divide ; * -> Multiply ; ^ : Power *****");
operator = input.next().charAt(0);
// Switch case
switch (operator){
case '+' : answer = calc.add(entry1, entry2);
break;
case '-' : answer = calc.substract(entry1, entry2);
break;
case '/' : answer = calc.divide(entry1, entry2);
break;
case '*' : answer = calc.multiply(entry1, entry2);
break;
case '^' : answer = calc.power(entry1, entry2);
break;
}
System.out.println(entry1 + " " + operator + " " + entry2 + " = " + answer);
}
}`
Calculations.java -->another class holding calculations
import java.math.*;
public class Calculations {
// Addition Method
double add (double first, double second){
double answer = first + second;
return answer;
}
// Substraction Method
double substract (double first, double second){
double answer = first - second;
return answer;
}
// Multiplication Method
double multiply (double first, double second){
double answer = first * second;
return answer;
}
// Division Method
double divide (double first, double second){
double answer = first / second;
return answer;
}
// Power Method
double power(double a, double b){
double answer =Math.pow(a, b);
return answer;
}
}

How to efficiently use arguments within methods in java?

Im fairly new to Java , and OOP in general hence many concepts in Java dont make complete sense even though the API is thorough. I have made a small calculator code , however I want to learn how to achieve the same product using arguments within method, samples would be prime.
import java.io.IOException;
import java.util.Scanner;
public class Ga {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
switch (s) {
case '+':
System.out.println("Result= "+(i+z));
System.in.read();
break;
case '-':
System.out.println("Result= "+(i-z));
System.in.read();
break;
case '*':
System.out.println("Result= "+(i*z));
System.in.read();
break;
case '/':
System.out.print("Result= "+(i/z));
System.in.read();
break;
}
}
}
To start with OOP, you could write an abstract class representing an operation:
public abstract class Operation {
public abstract float getResult(float a, float b);
}
Then, try to write concrete operation like Addition, Division:
public class Addition extends Operation {
#Override
public float getResult(float a, float b) {
return a + b;
}
}
public class Division extends Operation {
#Override
public float getResult(float a, float b) {
return a / b;
}
}
Then, rewrite your main method like that:
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
Operation op = null;
switch (s) {
case '+':
op = new Addition();
break;
case '-':
op = new Subtraction();
break;
...
}
System.out.println("Result= " + op.getResult(i, z));
System.in.read();
}
As Richard mentions it, you could also rewrite the switch with an HashMap:
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
Map<String, Operation> operationMap = new HashMap<String, Operation>();
operationMap.put("+", new Addition());
operationMap.put("-", new Substraction());
...
Operation op = operationMap.get(s);
System.out.println("Result= " + op.getResult(i, z));
System.in.read();
}

Categories