Error in simple java program - java

I am working on teaching myself java and while working on a code using classes I ran into this error
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at StateCalculator.getOperand(StateCalculator.java:29)
at StateCalculator.main(StateCalculator.java:77)
Below is my code:
import java.util.Scanner;
public class StateCalculator {
private double currentValue = 0;
//Initialize to 0
public StateCalculator() {
}
public static int displayMenu() {
Scanner keyboard = new Scanner(System.in);
int menuChoice = 0;
do {
System.out.print("Menu\n 1. Add\n 2. Subtract\n 3. Multiply\n 4. Divide\n 5.Clear\n 6. Quit\n What would you like to do?: ");
menuChoice = keyboard.nextInt();
} while(menuChoice < 1 || menuChoice > 6);
keyboard.close();
return menuChoice;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
double operand = 0;
System.out.print(prompt);
operand = input.nextDouble();
input.close();
return operand;
}
public double getCurrentValue() {
return currentValue;
}
public void add(double operand) {
currentValue += operand;
}
public void subtract(double operand) {
currentValue -= operand;
}
public void multiply(double operand) {
currentValue *= operand;
}
public void divide(double operand) {
if(operand == 0) {
currentValue = Double.NaN;
}
else {
currentValue /= operand;
}
}
public void clear() {
currentValue = 0;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StateCalculator calculator = new StateCalculator();
int option;
double operand;
do{
System.out.println("The current value is " + calculator.currentValue);
option = StateCalculator.displayMenu();
switch(option) {
case 1:
operand = getOperand("What is the second number?: ");
calculator.add(operand);
break;
case 2:
operand = getOperand("What is the second number?: ");
calculator.subtract(operand);
break;
case 3:
operand = getOperand("What is the second number?: ");
calculator.multiply(operand);
break;
case 4:
operand = getOperand("What is the second number?: ");
calculator.divide(operand);
break;
case 5:
calculator.clear();
break;
}
}while(option != 6);
keyboard.close();
}
}
I tried running the debug feature in eclipse and discovered the problem occurs on line 29 in my getOperand method when I attempt to set operand = input.nextDouble. However, I don't understand why this would be an issue.

Don't call keyboard.close(); when you close keyboard (which you defined)
Scanner keyboard = new Scanner(System.in);
it closes System.in, and then your other methods can't work (because the console will not re-open). You can have multiple scanners on System.in (as long as you don't close them), or pass one (or, but please don't, use a global).
Per the javadoc,
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

Related

Java program skips an input?

Hello,
I was trying to build a simple calculator using basic Java code and understand OOP better, so, I wrote this:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr;
opr = input.nextLine();
if(opr == "+") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
} else if (opr == "-") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
} else if (opr == "*") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
} else if (opr == "/") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
} else {
System.out.println("Please, Enter a valid operation!");
}
}
}
and another Class for math operations:
import java.util.Scanner;
public class Operation {
static int Num1;
static int Num2;
Scanner input = new Scanner(System.in);
public Operation(int x, int y) {
x = Num1;
y = Num2;
}
public void addition() {
System.out.println(Num1 + Num2);
}
public void subtraction() {
System.out.println(Num1 - Num2);
}
public void multiplication() {
System.out.println(Num1 * Num2);
}
public void division() {
System.out.println(Num1 / Num2);
}
}
but it doesn't take input for the operation, and it goes straight to the next line of code, like so:
Enter a number:
4
Enter an operation:
Please, Enter a valid operation!
Could anyone, please point my mistake?
Note: I'm a newbie in Java and programming in general. so, please don't mind me if my code isn't the best, I'm still learning.
Hello you had a couple of problems. The nextLine() will return an empty line the first time since nextInt consumes the integer only after receiving a new line char but leaves the new line char in the buffer. Additionally the equals comparison needs to be using opr.equals("+") or a switch statement. And finally your Operation class constructor had the variable assignment backwards. I have also modified the Operation private member variables to follow standard naming conventions and scoping practices. You generally want to make member variables private since if not explicitly defined they will be protected. I would recommend using a good IDE since it can catch a lot of those errors for you, try using the free IntelliJ. Here is an updated version of your code.
public class Operation {
private final int num1;
private final int num2;
public Operation(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public void addition() {
System.out.println(num1 + num2);
}
public void subtraction() {
System.out.println(num1 - num2);
}
public void multiplication() {
System.out.println(num1 * num2);
}
public void division() {
System.out.println(num1 / num2);
}
}
And your main class
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr = null;
while(opr == null || opr.length() == 0){
opr = input.nextLine();
}
switch (opr) {
case "+": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
break;
}
case "-": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
break;
}
case "*": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
break;
}
case "/": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
break;
}
default:
System.out.println("Please, Enter a valid operation!");
break;
}
}
}
Use
input.next
rather than
input.nextLine
as nextInt accepts a number and the new line character \n.
In the switch ts checking for the new line character.

Java first attempt on simple calculator (what's happened?) [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 4 years ago.
Improve this question
Main.java (Main Class)
package com.indie;
import java.util.InputMismatchException;
import java.util.Scanner;
import static com.indie.Operations.*;
public class Main {
private static double Number1;
private static double Number2;
private static double Total;
private static String Symbol;
private static boolean noError;
private static boolean exceptioncaught;
public static void main(String[] args) throws InterruptedException{
noError = false;
while (!noError) {
exceptioncaught = false;
while (!exceptioncaught) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your number:");
try {
Number1 = scanner.nextDouble();
} catch (InputMismatchException ex) {
System.out.println();
System.out.println("TypeERROR: You didn't input a vaild number!");
exceptioncaught = true;
System.out.println();
Thread.sleep(3000);
break;
}
System.out.println("What do you want to do:");
Symbol = scanner.next();
if (!Symbol.contains("+") && !Symbol.contains("-") && !Symbol.contains("*") && !Symbol.contains("x") && !Symbol.contains("/") && !Symbol.contains("÷")) {
System.out.println();
System.out.println("TypeERROR: You didn't input a valid symbol!");
exceptioncaught = true;
System.out.println();
Thread.sleep(3000);
break;
}
System.out.println("Enter your second number:");
try {
Number1 = scanner.nextDouble();
} catch (InputMismatchException ex) {
System.out.println();
System.out.println("TypeERROR: You didn't input a vaild number!");
exceptioncaught = true;
System.out.println();
Thread.sleep(3000);
break;
}
System.out.println();
if (Symbol.contains("+")) {
Total = Add(Number1, Number2);
noError = true;
break;
} else if (Symbol.contains("-")) {
Total = Subtract(Number1, Number2);
noError = true;
break;
} else if (Symbol.contains("*") || Symbol.contains("x")) {
Total = Multiply(Number1, Number2);
noError = true;
break;
} else if (Symbol.contains("/") || Symbol.contains("÷")) {
Total = Divide(Number1, Number2);
noError = true;
break;
}
}
}
System.out.println(String.valueOf(Number1)
+Symbol+String.valueOf(Number2)
+"="+String.valueOf(Total));
}
}
Operations.java (2nd Class)
package com.indie;
public class Operations {
public static double Add(double x, double y) { return x+y; }
public static double Subtract(double x, double y){ return x-y; }
public static double Multiply(double x, double y){ return x*y; }
public static double Divide(double x, double y){ return x/y; }
}
Got this result
Any way of fixing it? How did it end up with 2.0+20.0=2.0? Please Help.
Any way of preventing it from giving that type of results?
Other results:
result 1:
Enter your number:
2
What do you want to do:
+5
Enter your second number:
56
56.0+50.0=56.0
result 2:
Enter your number:
1
What do you want to do:
+1
Enter your second number:
1
1.0+10.0=1.0
On this part of the code, you should change this:
...
System.out.println("Enter your second number:");
try {
Number1 = scanner.nextDouble();
}
...
to this:
...
System.out.println("Enter your second number:");
try {
Number2 = scanner.nextDouble();
}
...
You never change the value of Number2 in your code.
Something it is goood to have a second pair of eyes
In your code you never assign value to Number2
System.out.println("Enter your second number:");
try {
Number2 = scanner.nextDouble();

Methods in subclass aren't working

I have an assignment that was to make a subclass which adds on to the existing super class, and this is run by a third class with a main method which creates an object of the subclass and calls appropriate methods.
My problem is that calling methods in the super class works correctly, but calling the two additional methods I have written in the subclass gets ignored.
I've checked, and the main method IS getting to the if statement which calls the new method in the subclass, but this method is not executing.
Specifically the superclass is a memory calculator with basic add, subtract, divide, and multiply options, as well as an option to clear the current value.
The subclass is a scientific memory calculator that overrides the menu method in the superclass to include options for power and logarithm, and has methods for both.
When I choose the option for power, it is simply returning the current value and not raising that power to the number specified.
Superclass:
import java.util.Scanner;
public class MemoryCalc {
private double currentValue = 0;
public static int displayMenu() {
Scanner input = new Scanner(System.in);
System.out.print("Menu\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Clear\n6. Quit\nWhat would you like to do? ");
int menuChoice = input.nextInt();
while (menuChoice < 1 || menuChoice > 6) {
System.out.print("Please enter a valid option.\n\n");
System.out.print("Menu\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Clear\n6. Quit\nWhat would you like to do? ");
menuChoice = input.nextInt();
}
return menuChoice;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
System.out.print(prompt);
double operand = input.nextDouble();
return operand;
}
public double getCurrentValue() {
return currentValue;
}
public void add(double operand2) {
currentValue = currentValue + operand2;
}
public void subtract(double operand2) {
currentValue = currentValue - operand2;
}
public void multiply(double operand2) {
currentValue = currentValue * operand2;
}
public void divide(double operand2) {
if (operand2 == 0) {
currentValue = Double.NaN;
}
else currentValue = currentValue / operand2;
}
public void clear() {
currentValue = 0;
}
}
Subclass:
import java.util.Scanner;
public final class ScientificMemCalc extends MemoryCalc {
private double currentValue = 0;
public static int displayMenu() {
Scanner input = new Scanner(System.in);
int menuChoice = -1;
while (menuChoice < 1 || menuChoice > 8) {
System.out.println();
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Power");
System.out.println("6. Logarithm");
System.out.println("7. Clear");
System.out.println("8. Quit");
System.out.println();
System.out.print("What would you like to do? ");
menuChoice = input.nextInt();
if (menuChoice < 1 || menuChoice > 8) {
System.out.println(menuChoice + " wasn't one of the options");
}
}
return menuChoice;
}
public void power(double operand2) {
currentValue = Math.pow(currentValue, operand2);
}
public void logarithm() {
currentValue = Math.log(currentValue);
}
}
Main Method:
public class ScientificCalcDriver {
public static void main(String[] args) {
ScientificMemCalc calculator1 = new ScientificMemCalc();
int menuChoice = 0;
while (menuChoice != 8) {
System.out.print("The current value is " + calculator1.getCurrentValue() + "\n");
menuChoice = ScientificMemCalc.displayMenu();
if (menuChoice < 6) {
double Operand2 = ScientificMemCalc.getOperand("What is the second number? ");
if (menuChoice == 1) {
calculator1.add(Operand2);
}
if (menuChoice == 2) {
calculator1.subtract(Operand2);
}
if (menuChoice == 3) {
calculator1.multiply(Operand2);
}
if (menuChoice == 4) {
calculator1.divide(Operand2);
}
if (menuChoice == 5) {
calculator1.power(Operand2);
}
}
else if (menuChoice == 6) {
calculator1.logarithm();
}
else if (menuChoice == 7) {
calculator1.clear();
}
else if (menuChoice == 8) {
System.out.print("Goodbye!");
System.exit(0);
}
}
}
}
You've got two different currentValue variables, both private, one in the superclass and one in the subclass. The methods in your superclass are changing the value of its variable, and the methods of the subclass are changing the value of its variable.
Make currentValue protected in the superclass, and remove it from the subclass.
Update:
Based on the "must be private" comment: You still need to remove the extra currentValue variable in the subclass, but as Oleg points out, you can obtain and update the value of a private variable in a superclass using get and set methods defined in the superclass.

A Memory Calculator Program

I have this program that asks user to enter a value and it calculates it as the user like to initial value of zero, then it ask the user what process to do again and ask the user to enter a value again and it calculates it to the last value of the instance, the problem is every time it asks the user to enter value it calculates it to zero not to the last entry. Please help me find the bug:
The program has to has two classes, one for the calculator and the other for the methods:
FIRST CLASS
public class MainClass {
public static void main(String[] args) {
MemoryCalculator calc = new MemoryCalculator();
calc.getCurrentValue();
displayMenu();
}
public static int displayMenu() {
Scanner input = new Scanner(System.in);
int choice;
do {
System.out.println("Menu");
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Clear");
System.out.println("6.Quit");
System.out.println("");
System.out.println("What would you like to do?");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
return displayMenu();
}
} while (choice > 6 || choice < 1);
MemoryCalculator calc = new MemoryCalculator();
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
return displayMenu();
}
public static double getOperand(String prompt) {
return 0;
}
}
SECOND CLASS
public class MemoryCalculator {
private double currentValue;
public double getCurrentValue() {
System.out.println("The current value is " + currentValue);
return 0;
}
public void add(double operand2) {
currentValue = currentValue + operand2;
getCurrentValue();
}
public void subtract(double operand2) {
currentValue -= operand2;
getCurrentValue();
}
public void multiply(double operand2) {
currentValue *= operand2;
getCurrentValue();
}
public void divide(double operand2) {
if (operand2 == 0) {
System.out.println("Sorry, you can not divide by 0");
}
currentValue /= operand2;
getCurrentValue();
}
public void clear() {
currentValue = 0;
getCurrentValue();
}
}
You probably want to keep the last value stored in "calc". I see 3 bugs.
Move this line before the start of your "do" loop. This will keep it from reseting the value inside this variable/class.
MemoryCalculator calc = new MemoryCalculator();
Move your ending "while" loop line to the bottom of your method(right before the return statement). It only appears to be working because in your return statement you are calling your method again...see #3. Also you will want to change the "or" to the "and" operator in the while statement "choice>6 && choice<1"
}while(choice>6 && choice<1);
In you displayMenu method change the return statement, because you don't want it to call itself in an infinite loop... now that the do while loop is fixed.
return displayMenu();
to this
return choice;

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