This question already has answers here:
If-else working, switch not [duplicate]
(9 answers)
Closed 6 years ago.
I started to learn Java some time ago and I thought that making a calculator that works in the terminal. Lately I added an Array list to store the history, and then something went wrong.
Calculator program:
import java.util.Scanner;
import java.util.ArrayList;
public class calc_case {
public static void main(String[] args) {
System.out.println("Welcom to The Calculator!");
double a;
double b;
double c;
Scanner input0;
int input = 0;
ArrayList<Double> history = new ArrayList<Double>();
while (input != 6) {
try {Thread.sleep(2000);} catch(InterruptedException ex) {Thread.currentThread().interrupt();}
a = 0; b = 0; c = 0; input = 0;
System.out.println("#################################################");
System.out.println("How can I help you?");
System.out.println("1-Add\n2-Subtrackt\n3-Devide\n4-Multiply\n5-Show history\n6-Exit");
input0 = new Scanner(System.in);
input = input0.nextInt();
switch (input) {
case 1: //add
System.out.println("Input two numbers:");
input0 = new Scanner(System.in);
a = input0.nextDouble();
input0 = new Scanner(System.in);
b = input0.nextDouble();
c = a + b;
System.out.println("Calculating... \nThe answer is: " + c );
break;
case 2: //subtrackt
System.out.println("Input two numbers:");
input0 = new Scanner(System.in);
a = input0.nextDouble();
input0 = new Scanner(System.in);
b = input0.nextDouble();
c = a - b;
System.out.println("Calculating... \nThe answer is: " + c );
break;
case 3: //devide
System.out.println("Input two numbers:");
input0 = new Scanner(System.in);
a = input0.nextDouble();
input0 = new Scanner(System.in);
b = input0.nextDouble();
c = a/b;
System.out.println("Calculating... \nThe answer is: " + c );
break;
case 4: //multiply
System.out.println("Input two numbers:");
input0 = new Scanner(System.in);
a = input0.nextDouble();
input0 = new Scanner(System.in);
b = input0.nextDouble();
c = a*b;
System.out.println("Calculating... \nThe answer is: " + c );
break;
case 5: //history
for (int x = 0; x < history.size(); x++) {
System.out.println(history.get(x));
}
case 6: //exit
System.out.println("Goodbye!\n Killing process... " + " OK");
default:
history.add(c);
}
}
}
}
After adding case 5 as 'Show history' and moving case 5 'Exit' to case 6 'Exit' after choosing option 5 ('Show history') I get this:
Goodbye!
Killing process... OK
I tried recompiling the program, deleting the class file, and pasting the program to a new file. What is wrong with my program?
OS: Ubuntu 16.04 Java version:
Java version: openjdk version "1.8.0_91"
Two things:
You forget the break after case 5; so you always fall through to the next case. So does the next case 6.
Your history is printed; but you never add a value to that history! There is not much sense in keeping a history, if that variable is only read from, but never written to.
And from a "clean coding" perspective: read about the "single layer of abstraction" principle. You really do not want to have so much code in one method; for example: each of your case blocks ... should go into its own method. You want to create small "units" that can be understood with one glance. Something that goes over 10 lines or more always requires more work than something smaller!
And you know; when each code would like this:
...
case 3:
divide();
break;
case 4:
multiply();
break;
dont you think you would have spotted your problem yourself?!
You do not have break in case 5, that is why it executes case 6 after finishing case 5
You are missing a break after your for loop in case 5:, so it falls through into case 6:.
Also, case 6: appears to be missing a break after the System.out statement.
Related
I’m trying to use Data that I saw from another post Creating a console menu for user to make a selection to create a menu in which the user selects an option. When I go to run my program it throws several errors.
Maybe I’m not importing it correctly but this is the only method
I can think of.
import java.util.Random;
import java.util.Data;
public class Main{
public static void main(String[] args) {
System.out.println("Please enter 1 if you'd like to guess the computer's number or enter 2 to have the computer guess your number. If 2, please enter a number between 1-100 after you enter 2. ");
Data data = new Data();
data.menu();
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
double r = (Math.random()*((100-1)+1))+min;
int win = 0;
while (win != 1);
System.out.println("The computer has guessed a number, please make a guess. ");
int u1 = scanner.nextInt();
if (r > u1)
System.out.println("Too low.");
else if (r < u1)
System.out.println("Too high.");
else if (r == u1){
System.out.println("You guessed it!!!!!!! Congratulations!!!!!!!!!!");
int win = win + 1 ;}
else
System.out.println();
break;
case 2:
System.out.println("You'd like myself, the computer to guess huh, well be prepared to get destroyed!");
int un = scanner.nextInt();
if (un == 36){
System.out.println("Chandler I told you not to!!!!!!");
break;}
else
System.out.println();
System.out.println("Your number is " + un);
break;
default:
System.out.println("You weren't supposed to do that!!!! Stop the program and run it again. Congrats! You broke it! Chandler, if you entered 36, ");
TimeUnit.SECONDS.sleep(5);
System.out.print("you've been banned!");
}
}
}
All your compiler errors in order.
import java.util.Data; // Does not exist, #MadProgrammer is correct, causes error
Data data = new Data(); // Error, Data cannot be resolved as to a type
Scanner scanner = new Scanner(System.in); // You did not import java.util.Scanner.
// Scanner cannot be resolved to a type.
double r = (Math.random()*((100-1)+1))+min; // min cannot be resolved to a variable
// You didn't define it
System.out.println("The computer has guessed a number, please make a guess. ");
int win = win + 1 ;} // win was a variable that was previously defined. Just change it
from "int win =" to "win = "
TimeUnit.SECONDS.sleep(5); // Did you mean to import java.util.concurrent.TimeUnit;
Also, if you want to "ban" someone from your program, then why not make a .txt file to read from, that helps your program remember if it has been "broken" before.
I am attempting to create two players in the program I am writing. The issue is that there are three types of players that can be created but in order to reference them later I want them named as player one and player two. The three classes: "Human", "Computer", and "Karen" are derived classes of "Player". I am wondering how to create an array Player that I can then put player1 and player2 objects in. Is this possible to do?
int playerType = 0;
int highestScore = 0;
Player[] player = new Player[2]; // This is the array of type Player, the master class
Scanner userInput = new Scanner (System.in);
for (int i = 1; i < 3; i++)
{
System.out.println ("Choose a type of player:");
System.out.println ("1: Human");
System.out.println ("2: Computer (Threshold = 20)");
System.out.println ("3. Computer (Custom)");
System.out.print ("? : ");
playerType = Integer.valueOf(userInput.nextLine()); // gets input choice from user
switch (playerType)
{
case 1:
Human player[i] = new Human();
case 2:
Computer player[i] = new Computer();
case 3:
Karen player[i] = new Karen();
}
}
There is another method I tried, using an if statement to make an object playerOne or playerTwo based on what iteration of the for loop we were on (i). Unfortunately it doesn't look like java will compile it because there are multiple declarations of the same variable, even though only one of the declarations should run.
if(playerNumber == 1){
switch (playerType)
{
case 1:
Human playerOne = new Human();
case 2:
Computer playerOne = new Computer();
case 3:
Karen playerOne = new Karen();
}
}
if(playerNumber == 2){
switch (playerType)
{
case 1:
Human playerTwo = new Human();
case 2:
Computer playerTwo = new Computer();
case 3:
Karen playerTwo = new Karen();
}
}
The solution suggested by OldProgrammer is below, it worked perfectly. However, I am now having an issue calling methods of: Human, Computer, and Karen. I get the following error when trying to execute:
System.out.println(player[i].getName() + ", your turn");
Error Msg:
Main.java:38: error: cannot find symbol
System.out.println(player[i].getName() + ", your turn");
^
symbol: method getName()
location: class Player
1 error
The method in each class looks like this:
public class Karen extends Player {
private String playerName = "Karen";
public String getName(){
return playerName;
}
}
Thanks to OldProgrammer:
Change "Human player[i] = new Human();" to "player[i] = new Human();", etc.
Understanding how derived classes is really important and I'm glad this is how it works. Thank you very much and I hope this might help someone in the future. Here is my updated code for full clarification:
int highestScore = 0;
Player[] player = new Player[2];
Scanner userInput = new Scanner (System.in);
for (int i = 0; i < 2; i++)
{
System.out.println ("Choose a type of player:");
System.out.println ("1: Human");
System.out.println ("2: Computer (Threshold = 20)");
System.out.println ("3. Computer (Custom)");
System.out.print ("? : ");
playerType = Integer.valueOf(userInput.nextLine());
switch (playerType)
{
case 1:
player[i] = new Human();
case 2:
player[i] = new Computer();
case 3:
player[i] = new Karen();
}
}
In my Java Program, I have used a Boolean variable 'decision' which should execute the actual calculator code in the 'do loop code block' only when the variable is true, but the do while loop is executed anyways even when the decision variable is false. I am using Eclipse IDE for Java and JDK 10 (both are recent versions). Please help me with a solution. The code is as below
import java.util.Scanner;
public class apples {
public static void main(String[] args) {
int option,a,b,c;
boolean decision;
System.out.println("We are here to create a calculator");
System.out.print("Do you want to switch on the calculator:");
Scanner yogi = new Scanner(System.in);
decision = yogi.nextBoolean();
do {
System.out.println("Following operations are available to perform:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter the operations do you want to perform:");
option = yogi.nextInt();
System.out.println("Choice of operation is:"+option);
switch(option) {
case 1:
System.out.println("Enter two numbers to be added:");
a = yogi.nextInt();
b = yogi.nextInt();
c = a + b;
System.out.print("Addition:"+c);
break;
case 2:
System.out.println("Enter two numbers to be subtracted:");
a = yogi.nextInt();
b = yogi.nextInt();
c = a - b;
System.out.print("subtracted:"+c);
break;
case 3:
System.out.println("Enter two numbers to be multiplied:");
a = yogi.nextInt();
b = yogi.nextInt();
c = a * b;
System.out.print("multiplied:"+c);
break;
case 4:
System.out.println("Enter two numbers to be divided:");
a = yogi.nextInt();
b = yogi.nextInt();
c = a / b;
System.out.print("divided:"+c);
break;
default:
System.out.println("This is a wrong choice");
break;
}
}while(decision==true);
}
}
the do while loop is executed anyways even when the decision variable
is false
A do...while will executes the body once before checking the condition.
Either modify your code for while or add an if-else enclosing do...while.
You can add another case 5 and in that write System.exit(0) for the successful termination of the program.
In the while part pass (option != 5). This should run the program.
You don't need decision variable.
This question already has answers here:
Simple Java calculator
(10 answers)
Closed 8 years ago.
Trying to make a simple calculator in Java but I keep getting errors when I try to compile it. Not sure if it's the coding or something I am doing when I compile it. Any help would be appreciated!
import java.util.Scanner;
class simple calculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double fnum,snum,ans;
System.out.print("Enter the first and second " +
"number : ");
a=bucky.nextFloat(); //assign the numbers
b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
Two compilation errors:
Your class name has whitespace in it: class simple calculator isn't valid, because "calculator" isn't a recognized token. Try: class SimpleCalculator. Also make it public and change the name of the file to match. (SimpleCalculator.java).
You declare variables a and b but don't give them types. Use float a = ... and double b = .... That one is a float and the other is a double is strange, but pressing on...
Other new-to-java issues to note:
You never close bucky, the scanner. This is a resource leak, and in a bigger application could be a major bug. Add bucky.close() after you read the last line from it, which is after operation = bucky.next()
the name bucky tells me absolutely nothing about what it is or what its use is. Try to use descriptive variable names. (The only main exception being single letter names for loop indices, etc).
fnum and snum are local variables that you declare but never use. Perhaps get rid of them?
Here's your code with edits made:
import java.util.Scanner;
public class SimpleCalculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double ans;
System.out.print("Enter the first and second " +
"number : ");
float a=bucky.nextFloat(); //assign the numbers
double b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
bucky.close();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
I was able to compile it in the terminal with no trouble.
After looking up numerous ways to restart a Java program within itself, a while loop seemed like the easiest option. Here's an example of a basic calculator program I'm trying this with:
import java.util.Scanner;
class a {
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done)
{
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
add addObject = new add();
addObject.getSum();
break;
case 2:
sub subObject = new sub();
subObject.getDifference();
break;
case 3:
times multObject = new times();
multObject.getProduct();
break;
case 4:
divide divObject = new divide();
divObject.getQuotient();
break;
case 5:
remain remObject = new remain();
remObject.getRemainder();
break;
case 6:
avg avgObject = new avg();
avgObject.getAvg();
break;
case 7:
interest intObject = new interest();
intObject.getInterest();
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
}
However, this seems to throw out a NoSuchElementException at the end of the first time through the loop, and crashes the program. The function of this class is to take the initial input from the user to determine which class to use, which will determine which mathematical operation to perform. Everything works fine without the while (!done) loop.
Example usage:
McMackins Calc v2.0 (Now with fewer crashes!)
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
1
How many addends?
1
Enter your numbers now.
1
You have entered 1 addend.
The sum is: 1.0
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
Enter a valid integer.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at a.main(a.java:13)
I've also tried just having the other classes refer back to this one, but since main is a static method, I cannot access it the way I intended.
Note that I'm a bit of a beginner at Java, which is why my program is pretty simple, so try to keep it simple if it can be, or post code and then in DETAIL explain what it means so I can not only fix this problem, but future ones as well.
Thank you!
EDIT:
The code is formatted better within my editor. The braces came out in odd positions when I posted it here.
Since apparently a is written correctly, this is my add class. Hopefully this will clear something up.
import java.util.Scanner;
public class add {
public void getSum(){
Scanner input = new Scanner(System.in);
double total, addend;
int entries, count;
total = 0;
count = 0;
System.out.println("How many addends?");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
entries = input.nextInt();
System.out.println("Enter your numbers now.");
while (count < entries){
while (!input.hasNextDouble()){
System.out.println("Enter a valid number.");
input.next();
}
addend = input.nextDouble();
total = total + addend;
count++;
if (count == 1){
System.out.println("You have entered " + count + " addend.");
}else if (count > entries){
System.out.println("You have entered too many addends! Contact program developer.");
}else{
System.out.println("You have entered " + count + " addends.");
}
}
System.out.println("The sum is: " + total);
input.close();
}
}
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done) {
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
case 3:
System.out.println("3");
break;
case 4:
System.out.println("4");
break;
case 5:
System.out.println("5");
break;
case 6:
System.out.println("6");
break;
case 7:
System.out.println("7");
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
This seemed to work for me so perhaps the error is something to do with your own classes (add, divide) etc.
Also, it's best to keep with convention when creating your own classes by capitalizing the first letter e.g. "add" should be "Add".
You could probably make this a little bit easier to read by building a general "Operations" class which holds an add method, a subtract method etc.
EDIT:
try this for your add method:
public static int add() {
Scanner s = new Scanner(System.in);
int counter = 0;
System.out.println("How many numbers to add?");
int numCount = s.nextInt();
for(int i = 0; i < numCount; i++) {
System.out.println("enter number");
counter += s.nextInt();
}
return counter;
}
Use bufferedreader and inputstream instead of Scanner class. This class creates a lot of bugs and errors, since sometimes it takes more arguments, that you expect it to take.
Also:
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
Your using hasNextInt method wrong, instead of it try to make simple while loop with Boolean and input.next() should be replaced with input.nextLine().
Another thing, you should check,if user typed integer instead of string or something in the while loop and it range. If everything is okay, you should change Boolean value to true and make him go out of the while loop.
For future users who are wondering how to fix this issue, through some reprogramming, I discovered that my problem was closing the input variable BEFORE the end of the loop. By having the program restart indefinitely and only close input when done, this program works fine.
Thanks to Benjamin's response, I am currently in the process of cleaning up and shortening my code by way of for loops.