as you can probably see I am a newbie in java. Below is a simple calculator program which asks for the user to input a symbol such as + or -. The user then inputs 2 numbers and depending on the operator symbol chosen a method will be called. A do while loop allows the user to repeat the process. The problem is that after the program loops, the following line: "String symb = inp.nextLine();" is skipped. I have already tried searching for a solution however I only found a fix if the nextLine is called after nextInt. Thank you in advance for your patience.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp = new Scanner(System.in);
Methods operation = new Methods();
boolean loop = false;
do {
System.out.println("Enter an operator symbol - +, -, * or /");
String symb = inp.nextLine(); //this is the line which is skipped
System.out.println("Enter a number");
int num1 = inp.nextInt();
inp.nextLine();
System.out.println("Enter a second number");
int num2 = inp.nextInt();
inp.nextLine();
switch(symb) {
case "+" :
operation.setA(num1);
operation.setB(num2);
int totalAddition = operation.addNums(num1,num2);
System.out.println("The result is - " + totalAddition);
break;
case "-" :
operation.setA(num1);
operation.setB(num2);
int totalSubtract = operation.subtractNums(num1,num2);
System.out.println("The result is - " + totalSubtract);
break;
case "*" :
operation.setA(num1);
operation.setB(num2);
int totalMult = operation.multNums(num1,num2);
System.out.println("The result is - " + totalMult);
break;
case "/" :
operation.setA(num1);
operation.setB(num2);
int totalDiv = operation.divNums(num1,num2);
System.out.println("The result is - " + totalDiv);
break;
}
System.out.println("Would you like to exit? Y/N");
char ans = inp.next().charAt(0);
if(ans == 'Y' || ans == 'y') {
loop = true;
inp.close();
System.exit(0);
}
else {
loop = false;
}
}
while(loop == false);
}
}
Related
my questions are the following:
- why does eclipse want me to close the Scanners? Does it any harm to not close them? Do I profit if I close them?
- Is there beginner mistake in my code? What would an java expert solve different?
I have left out subtraction(), multiplication(), division() and modulo() from my code because they work almost the same like addition().
import java.util.InputMismatchException;
import java.util.Scanner;
class Calculator {
/**
* #param args
*/
static boolean invalid = true;
static void addition() throws InputMismatchException {
do {
try {
Scanner a = new Scanner(System.in);
Scanner b = new Scanner(System.in);
System.out.print("Enter a number: ");
double a1 = a.nextDouble();
System.out.print("Enter a number to add it to " + a1 + ": ");
double a2 = b.nextDouble();
System.out.println(a1 + " + " + a2 + " = " + (a1 + a2));
invalid = false;
} catch (InputMismatchException e) {
System.out.println("Oops! Please enter only numbers!");
invalid = true;
}
} while (invalid == true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int o;
boolean turnOff = false;
do {
System.out.print("Choose from one of the operation options.\n"
+ "Type 1 for addition\n" + " 2 for substraction\n"
+ " 3 for multiplication\n" + " 4 for division\n"
+ " 5 for modulo\n");
Scanner op = new Scanner(System.in);
o = op.nextInt();
switch (o) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
case 5:
modulo();
}
do {
System.out.print("Do you want to do more calculations? (n = no, y = yes) ");
Scanner c = new Scanner(System.in);
char input = c.next().charAt(0);
if (input == 'y') {
turnOff = false;
invalid = false;
} else if (input == 'n') {
turnOff = true;
invalid = false;
} else {
System.out.println("y or n is the only valid input. Try again.");
invalid = true;
}
} while (invalid == true);
} while (turnOff == false);
}
}
Normally not closing an AutoCloseable (e.g. a FileInputStream) is a mistake that would result in a resource leak, hence the warning.
But you're right to ask the question here. Say if you were to follow Eclipse's suggestion and close Scanner a, that would actually close the System.in that it's wrapping.
Stylewise I would be tempted to use a single Scanner instance all the way through, probably as an instance variable in the Calculator class. Firstly this would side step the Eclipse warning, but will also be (slightly) more efficient.
I am a newbie coder in Java and I am trying to make this calculator in java where a user can enter two numbers and select the operation to be done on those numbers. However when the code comes to selecting the operator it skips the user input and the if statement and directly implements the else statement.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Calc = new Scanner(System.in);
int n1;
int n2;
int Answer;
System.out.println("Enter the first number: ");
n1 = Calc.nextInt();
System.out.println("Enter the second number:" );
n2 = Calc.nextInt();
System.out.println("Select the order of operation: ");
char operator = Calc.nextLine().charAt(0);
if (operator == '+') {
Answer = (n1 + n2);
System.out.println("Answer:" + Answer);
}
if (operator == '-') {
Answer = (n1 - n2);
System.out.println("Answer:" + Answer);
}
if (operator == '*') {
Answer = (n1 * n2);
System.out.println("Answer:" + Answer);
}
if (operator == '/') {
Answer = (n1/n2);
System.out.println("Answer:" + Answer);
}
else {
System.out.println("not implemented yet. Sorry!");
}
}
}
Add Calc.nextLine(); after n2 = Calc.nextInt(); to consume the line feed.
You are also not using else if so all those if conditions will be checked even if previous if already matched (resulting in your final else being executed as long as operator not '/').
In this case you should probably just use a switch block.
I made some changes to the code, this should work with you, but I also recommend using a switch.
Scanner Input = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num1 = Input.nextInt();
System.out.print("Enter an operator: ");
char operator = Input.next().charAt(0);
System.out.print("Enter a second number: ");
int num2 = Input.nextInt();
// this part of decision, it doesn't work.
if ('+' == operator) {
System.out.println("Your result is " + (num1 + num2));
} else if ('-' == operator) {
System.out.println("Your result is " + (num1 - num2));
} else if ('*' == operator) {
System.out.println("Your result is " + (num1 * num2));
} else if ('/' == operator) {
System.out.println("Your result is " + (num1 / num2));
}else {
System.out.println("Your answer is not valid");
}
} catch (InputMismatchException e) {
System.out.println("similar to try and except in Python");
}
I have written a RPN Calculator in Java, but I am struggling to get my code to exit when the user enters a blank line instead of an equation. The program needs to loop until this blank line is entered.
Below is my source code.
$`import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
import java.io.FileNotFoundException;
public class Calculator {
private static Scanner input;
public static int invalidlines = 0;
public static int validlines = 0;
public static ArrayList<String> validList = new ArrayList<String>();
public void FileNotFoundException(){
System.out.println("Please enter a valid expression!");
}
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
}
catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
}
else
{
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
}
else
{
return false;
}
}
}
public static void main(String[] args) throws IOException {
input = new Scanner(System.in);
String keyboardInput = new String();
String currentLine = new String();
Scanner kbScan = new Scanner(System.in);
System.out.println("Please press the letter F for file input or K for keyboard input");
String inputString = new String(input.nextLine());
int answer = 0;
while (true){
if (inputString.equals("K") || inputString.equals("k")) {
System.out.println("Please enter an equation");
keyboardInput = kbScan.nextLine();
}
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
if (inputString.equals("") || inputString.equals(""));
{
System.exit(0);
}
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch(equation[2]) { // This case switch checks the third position of the string to decide which operator is being used. It then works out the answer and breaks to the next instruction
case("+"):
answer = num1 + num2;
break;
case("-"):
answer = num1 - num2;
break;
case("/"):
answer = num1 / num2;
break;
case("*"):
answer = num1 * num2;
break;
}
System.out.println("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
System.out.println("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
}
else{
System.out.println("The equation you entered is invalid");
}
if (inputString.equals("f") || inputString.equals("F")) {
try{
//Open the file
System.out.println("Enter File Name: ");
FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
String strLine; // create string vars
//loop to read the file line by line
while ((strLine = br.readLine()) != null) { // Whilst the buffered readers read line method is not null, read and validate it.
currentLine = strLine;
if(isValidLine(currentLine))
{
validList.add(currentLine);
validlines++;
String[] filearray = new String[3];
filearray = currentLine.split(" ");
int val1 = Integer.parseInt(filearray[0]);
int val2 = Integer.parseInt(filearray[1]);
System.out.println("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
switch(filearray[2]) {
case("+"):
answer = val1 + val2;
break;
case("-"):
answer = val1 - val2;
break;
case("/"):
answer = val1 / val2;
break;
case("*"):
answer = val1 * val2;
break;
}
System.out.println("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Please Enter a valid file name");
}
}
}
}
}
Just use following code to check the variable in which you are taking the user input,whether it's empty or not?
I am assuming you are taking in a variable called inputString,then the code should be-
if(inputString.isEmpty())
{
System.exit(0);
}
maybe you should use break instead of System.exit(0).
Also, I would check for empty input as soon as I read the input.
I already posted the question about my example, it was different problem. I came up to another problem. When i choose option 3(multiply) i get result to be zero. And if i choose option 4, cannot divide by zero(zero is my sentinel). How can i make sentinel to be string or char when i use int to input numbers to be calculated? Here is the code.
import java.util.Scanner;
public class SwitchLoopNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numbers = 0;
int result = 0;
int option;
boolean quit = true;
String done = "";
do {
System.out.println("CALCULATOR MENU");
System.out.println("********** ****");
System.out.println("\n1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
while (quit) {
switch (option) {
case 1:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result += numbers;
break;
case 2:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result = numbers - result;
break;
case 3:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result *= numbers;
break;
case 4:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result = result / numbers;
break;
}
}
System.out.println("The total is: " + result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
numbers = 0;
result = 0;
quit = true;
} while ("y".equalsIgnoreCase(done));
System.out.println("Thank you for using calculator");
}
}
Your main problem was that you have initialized result to zero, and it's a good approach for addition and subtraction, but when it comes to multiplication it is not going to work. So, as a solution for that problem you have to set the variable as an Integer, so you can change it as you want inside the loop depending on what operation you are trying to do. Also, it's better because the class Integer allows you to assign its variable to null, which can be so handy in this kind of situations(e.g. better than using 0). Another problem you had was the way you declared an end of your current operation and get the result back. You used 0 as a way of stoping your loop, however, 0 can be used as a number within your calculation. Therefore, you should scan the input as a string then if the user entered = sign, the loop ends and it gives back the result. Then, you can also use the feature that is given to us by the Integer class which allows us to parse integer from a string and use them as regular numbers. Along with that, you had some syntax "errors" and declarations that you could've come with a better way of writing it.
In overall, if you wanted to make a real calculator, this is absolutely not the best approach to do it, because you may face many mathematical problems and exceptions, but its not very bad as a start.
This fix most of your problems:
import java.util.Scanner;
public class SwitchLoopNumbers {
public static void main(String[] args) {
String number;
String process = "";
Integer result = null;
int option = 0;
boolean startOver = true;
while (true) {
Scanner scan = new Scanner(System.in);
if (startOver) {
System.out.print("CALCULATOR MENU" + "\n"
+ "****************" + "\n"
+ "1. Add" + "\n"
+ "2. Substract" + "\n"
+ "3. Multiply" + "\n"
+ "4. Divide" + "\n"
+ "****************" + "\n"
+ "Enter your option >> ");
option = scan.nextInt();
}
switch (option) {
case 1:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ + \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " + ";
option = 1;
startOver = false;
continue;
} else {
result = result + Integer.parseInt(number);
process += number + " + ";
option = 1;
startOver = false;
continue;
}
case 2:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[- \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " - ";
option = 2;
startOver = false;
continue;
} else {
result = result - Integer.parseInt(number);
process += number + " - ";
option = 2;
startOver = false;
continue;
}
case 3:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ * \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " * ";
option = 3;
startOver = false;
continue;
} else {
result = result * Integer.parseInt(number);
process += number + " * ";
option = 3;
startOver = false;
continue;
}
case 4:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ / \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " / ";
option = 4;
startOver = false;
continue;
} else {
result = result / Integer.parseInt(number);
process += number + " / ";
option = 4;
startOver = false;
continue;
}
}
System.out.println("The result of " + process.replace("+ 0 ", "") + result);
System.out.print("Back to main menu? [y/n]: ");
if (scan.next().equalsIgnoreCase("y")) {
process = "";
result = null;
startOver = true;
} else if (scan.next().equalsIgnoreCase("n")) {
System.out.println("Thank you for using calculator.");
break;
} else {
System.out.println("Wrong input!");
break;
}
}
}
}
For some reason my calculator won't wait for user input to finish the do while loop. I'm very new to java coding (currently only been doing it for a few hours). I want the user to be able to do more math before the program closes instead of having to reopen it every time they want to use it (obviously I don't mean anything serious by this I just want to learn and I think this will help.
heres my code
import java.util.Scanner;
public class calculator {
public static void main(String[] args){
double Answer;
String op;
double num1;
double num2;
String again;
boolean yesorno = true;
Scanner input = new Scanner(System.in);
while (yesorno = true){
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);
} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);
} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);
} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);
}
System.out.println("Would you like to do any more math?");
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");
}
} while (yesorno = true);
}
}
please ignore the akward formatting at the beggining and end of this code.
1) while(yesorno = true ) you are doing assignation
change to
while(yesorno == true) to prevent this thing you can use yoda style while(true = yesorno) then a compile error would throw cause you can't assign something to a value.
Or even more simpler just use while(yesorno)
2) Follow Java Code Convention , variable names are in lower case.
3)if this block get executed while (yesorno = true); you will have an infinite loop.
4) If you are using java 7 , you can do switch over strings
switch(op){
case "+":answer = num1 + num2;break;
case "-":answer = num1 - num2;break;
case "*":answer = num1 * num2;break;
case "/":answer = num1 / num2;break;
default: throw new IllegalArgumentException("Invalid operation "+ op);
}
System.out.println(answer);
You are assigning, not testing for equality in while (yesorno = true){. You should use while (yesorno == true){, since the double equals (==) tests for equality.
There were many errors, I have fixed it and commented it for you. Hope it helps:
import java.util.Scanner;
// KK: by general convention class names should always start with an upper case letter
public class calculator {
public static void main(String[] args) {
double Answer; //KK: local variable should be lower case
String op;
double num1;
double num2;
String again;
boolean yesorno = true;
Scanner input = new Scanner(System.in);
//KK: for comparing you need the double-equals
//KK: the loop will be executed as long as the expression is true, so for a boolean you don't need it at all
//KK: you can use either of the following:
// while (yesorno == true)
// while (yesorno)
while (yesorno) {
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);
} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);
} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);
} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);
}
System.out.println("Would you like to do any more math?");
//KK: you need to call nextLine twice because you printed 2 lines here
//KK: otherwise again will be empty, so yesorno will always be true and you have an endless loop
again = input.nextLine();
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");
}
}
// KK: the following line was an empty loop, that didn't do anything, so I commented it
// while (yesorno = true);
}
} //KK: this one was missing at the end too ;)
(I started my comments with KK, so you see them and can remove them later.)
Try this....
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean status = true;
while(status){
String answer = "";
String choise = "";
System.out.println("\"WELCOME TO JAVA CALCULATOR\"");
Scanner scn = new Scanner(System.in);
Scanner cal = new Scanner(System.in);
Scanner cho = new Scanner(System.in);
System.out.println("Enter the numers one by one that you want to calculate..");
int numA = scn.nextInt();
int numB = scn.nextInt();
int result = 0;
System.out.println("What you want to calculate...?");
answer = cal.nextLine();
if(answer.equals("+")){
result = numA+numB;}
if(answer.equals("-")){
result = numA-numB;}
if(answer.equals("*")){
result = numA*numB;}
if(answer.equals("/")){
result = numA/numB;}
System.out.println( "The result of " + numA + " and " + numB + " is : " + result);
System.out.println("Do you want to continue.....(y) or (n)?");
choise = cho.nextLine();
if(choise.equalsIgnoreCase("y")){
System.out.println("Welcome back.....:)\n\"Make By Saikat Halder\"");
status = true;}
if(choise.equalsIgnoreCase("n")){
System.out.println("Good bye....Thanks for useing java Calculator......:)");
System.exit(0);
}
}
}
}