This question already has answers here:
Basic Java: While loop for basic quiz?
(5 answers)
Closed 8 years ago.
Really new to java and having some trouble with this assignment. The assignment was to:
Write a simple calculator program that prints a welcome
message, accepts a simple arithmetic expression from the user, and
performs the requested operation. Your program should repeat this
until both operands are 0 and then exit.
It's running fine but I'm not sure how to get a handle on the While Loop so that the calculator will continue until the answer is 0. Sorry if this is a really basic question. Any help would be appreciated.
import java.util.Scanner;
class Calculator{
public static void main(String[] args)
{
System.out.println("Welcome to CSC 210 Calculator by Bob the Builder!");
System.out.println("Enter an integer operation: ");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
String operation= input.next();
int y = input.nextInt();
while(x + y != 0){
if(operation.equals("+")){
System.out.println(x + y);
}
else if(operation.equals("-")){
System.out.println(x - y);
}
else if(operation.equals("*")){
System.out.println(x * y);
}
else if(operation.equals("/")){
System.out.println(x / y);
}
else if(operation.equals("%")){
System.out.println(x % y + y);
}
else {
System.out.println("Operation is invalid.");
}
System.out.println("Enter an integer operation: ");
if(x + y != 0);
break;
}
}
}
use switch case in place of if else statement
if(a !=0 && b!=0)
{
switch(ch)//ch is where you stored the operator
{
case '-': System.out.println(a - b);
break;
case ' +':System.out.println(a+b);break;
}
else
{
System.out.println("Enter an integer operation: ");}
To solve the problem you mentioned above.
Write a simple calculator program that prints a welcome message, accepts a simple arithmetic expression from the user, and performs the requested operation. Your program should repeat this until both operands are 0 and then exit.
you should pay much attention to the following tips:
"until both operands are 0", so you can just loop out on the condition "x+y != 0", for example, x=5,y=-5,you can't just loop out.
"repeat" means you should assign new int value to the x and y variable in the while loop.
here's the code, may help you
import java.util.Scanner;
class Calculator{
public static void main(String[] args){
System.out.println("Welcome to CSC 210 Calculator by Bob the Builder!");
System.out.println("Enter an integer operation: ");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
String operation= input.next();
int y = input.nextInt();
while(x != 0 && y != 0){
if(operation.equals("+")){
System.out.println(x + y);
}
else if(operation.equals("-")){
System.out.println(x - y);
}
else if(operation.equals("*")){
System.out.println(x * y);
}
else if(operation.equals("/")){
System.out.println(x / y);
}
else if(operation.equals("%")){
System.out.println(x % y + y);
}
else {
System.out.println("Operation is invalid.");
}
System.out.println("Enter an integer operation: ");
x = input.nextInt();
y = input.nextInt();
}
}
}
Related
This question already has answers here:
Java String Concatenation with + operator
(5 answers)
Closed last year.
I don't know why I am getting this error of -first type: java.lang.String
second type: int....
Its a basic calculator program using java
public static void main(String[] args){
System.out.println("Welcome to the calculator");
Scanner input = new Scanner(System.in);
System.out.println("Enter your first inter number: ");
String k = input.next();
System.out.println("Enter second inter number: ");
String l = input.next();
int a =Integer.valueOf(k);
int b =Integer.valueOf(l);
String prompt = "Enter 1 for addition, 2 for subtraction, 3 for multiplication," +
" 4 for division, 5 for remainder between two numbers";
System.out.println(prompt);
int z = input.nextInt();
if (z == 1){
System.out.println("Addition of two numbers: "+a + b);}
else if (z == 2){
System.out.println("Subtraction of two numbers: " +a - b);}
else if (z == 3){
System.out.println("Multiplication of two numbers: "+a * b); }
else if (z == 4){
System.out.println("Division of two numbers: "+a / b);}
else if (z == 5){
System.out.println("remainder of two numbers: "+a % b);}
else{
System.out.println("Invalid input");
}
}
The error is in :
else if (z == 2){
System.out.println("Subtraction of two numbers: " +a - b);}
When you do "Subtraction of two numbers: " +a, Java concatenates the String and integer to form a String. Then, when it reaches the - b segment, it thinks you're trying to subtract an integer... from a String. If you put your math operations in parenthesis like this: (a - b) your code should work.
I'm really new to java and I cannot find a way around this. I want to make a program that tells you that a number is either positive or negative, regardless if it is int or double. But after the program is executed, I want it to loop and ask again for input from the user, to execute the code again and again and again, as long as there is user input. Can I do that in java?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
}
}
Here is a one of the approach which is good start for you to understand what wonders pattern matching can do in Java and it can be improved by testing it against exhaustive data points.
This also shows how to use while-loop, overloading methods and ternary operator instead of nested if-then-else.
As you are learning, you should also use debugging feature of editors and also use system.out.println to understand what code is doing.
I am ending the program when user presses just enter (empty string).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String userInput = "Input your number: ";
System.out.print(userInput);
String input = scanner.nextLine();
// look for integer (+ve, -ve or 0)
if (input.matches("^-?[0-9]+$")) {
int z = Integer.parseInt(input);
System.out.println(display(z));
// look for double (+ve, -ve or 0)
} else if (input.matches("^-?([0-9]+\\.[0-9]+|[0-9]+)$")) {
double z = Double.parseDouble(input);
System.out.println(display(z));
// look for end of program by user
} else if (input.equals("")) {
System.out.println("Good Bye!!");
break;
// look for bad input
} else {
System.out.println("Hey! Only numbers!");
}
}
scanner.close();
}
// handle integer and display message appropriately
private static String display(int d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
// handle double and display message appropriately
private static String display(double d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
}
Sample Run:
Input your number: 0
0 is equal to 0
Input your number: 0.0
0.0 is equal to 0
Input your number: -0
0 is equal to 0
Input your number: -0.0
-0.0 is equal to 0
Input your number: 12
12 is positive
Input your number: -12
-12 is negative
Input your number: 12.0
12.0 is positive
Input your number: -12.0
-12.0 is negative
Input your number: 12-12
Hey! Only numbers!
Input your number: ---12
Hey! Only numbers!
Input your number:
Use this code!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Console console = new Console();
while(true) {
// Take your input
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
// Ask for exit
System.out.print("Want to quit? Y/N")
String input = console.readLine();
if("Y".equals(input))
{
break;
}
}
}
}
Before you ask, I have already looked at other questions, they just seem to be for slightly different things.
I'm new to java and currently learning, so I made this narcissistic program that I'm going to make into a multi-tool sort of thing. That part doesn't really matter.
Basically, I'm making a text input calculator, where you type in numbers and operations and stuff, but it's fairly simple. However, in the input area, I'm trying and catching in case the user types something that isn't a number. But, this makes the variables of x and y (user inputs) to be uninitialized and not readable when initializing the separate public void calculator(variables). This is my code (I've only included the calculator part, the rest is unrelated and all working fine, also I know x is differently handled to y, I was testing them both)
public void calculatorvariables() {
System.out.println("Please enter the first number in your calculation.");
double x = scanner.nextDouble();
if(x != (double) x) {
System.out.println("An error occurred! Did you input nothing or something other than a number? Returning to variable input screen!");
} else
System.out.println("Please enter the operator. Valid operators are: '+', '-', '*', '/'");
String operation = scanner.next();
System.out.println("Please enter the second number in your calculation.");
try {
double y = scanner.nextDouble();
} catch (NumberFormatException e) {
System.out.println("An error occurred! Error message: " + e.getMessage() + " Did you input nothing or something other than a number? Returning to variable input screen!");
}
new FirstClass().calculator(x, operation, y);
}
public void calculator(double x, String operation, double y) {
if(operation.equals("+")) {
System.out.println(x + y);
}
else if(operation.equals("-")) {
System.out.println(x - y);
}
else if(operation.equals("*")) {
System.out.println(x * y);
}
else if(operation.equals("/")) {
System.out.println(x / y);
}
else {
System.out.println("Unknown operation! Returning to input area!");
new FirstClass().calculatorvariables();
}
System.out.println("Do you want to do another calculation? Y/N");
doAnotherCalculation = scanner.next().equalsIgnoreCase("Y");
if (doAnotherCalculation == true) {
new FirstClass().calculatorvariables();
}
else {
new FirstClass().mainmenu();
}
}
Any help would be appreciated!
You should declare the variable outside of the try/catch bit, like this:
double y;
try {
y = scanner.nextDouble();
catch (Exception e) {
// Exception handling
}
This should work
import java.util.Scanner;
public class TestSo{
Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
new TestSo().calculatorvariables();
}
public void calculatorvariables() {
System.out.println("Please enter the first number in your calculation.");
double x = scanner.nextDouble();
if(x != (double) x) {
System.out.println("An error occurred! Did you input nothing or something other than a number? Returning to variable input screen!");
} else
System.out.println("Please enter the operator. Valid operators are: '+', '-', '*', '/'");
String operation = scanner.next();
System.out.println("Please enter the second number in your calculation.");
double y = scanner.nextDouble();
calculator(x, operation, y);
}
}
public void calculator(double x, String operation, double y) {
if(operation.equals("+")) {
System.out.println(x + y);
} else if(operation.equals("-")) {
System.out.println(x - y);
} else if(operation.equals("*")) {
System.out.println(x * y);
} else if(operation.equals("/")) {
System.out.println(x / y);
} else {
System.out.println("Unknown operation! Returning to input area!");
calculatorvariables();
}
System.out.println("Do you want to do another calculation? Y/N");
boolean doAnotherCalculation = scanner.next().equalsIgnoreCase("Y");
if (doAnotherCalculation == true) {
calculatorvariables();
} else {
System.out.println("Done! Exiting");
}
}
}
I have a problem with my program.
Program is a HILO game which requires the user to guess a number between a range of a generated number.
The problem is that once i press 0 on my keyboard, it reveals the random number, and essentially must end the loop and ask whether the user wants to continue or end the program. Instead, it continues the loop, and whenever I press a letter on the keyboard it shows me an Exception error which describes and input Miss Match. Can some one guide me on how to fix it?, maybe I wrote the program wrong, I tried multiple ways, it still doesn't work as it supposed to work.
Thank you.
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class HILOGAME
{
public static void firstGame()
{
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
for (int exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.nextLine();
if (!choice.equalsIgnoreCase("x"))
{
Loop = true;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
Loop = false;
System.out.print("END OF GAME");
exit = 11;
}
}
if (number > answer)
{
System.out.println("TOO HIGH");
}
if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
}
}
}
}
}
EDIT 1:
This code is working perfectly for me i have tried running it:
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
int exit;
for (exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.next();
// HERE YOU ARE DOING THE WRONG THING
// What is the meaning of "not(!)" here ? !choice.equalsIgnoreCase("x")
// Remove "NOT(!)" from here your program will work as expected
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
else if (number > answer)
{
System.out.println("TOO HIGH");
}
else if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
// MADE CHANGES HERE
choice = input.next();
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
}
}
Please do copy-paste the code. Because it is working perfectly without any Exception..!!
My sample outputs:
SAMPLE 1:
Guess a number between 1 and 50 : 1
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 27
Enter x to continue to play or y to endgame
y
END OF GAME
SAMPLE 2:
Guess a number between 1 and 50 : 20
TOO HIGH
Guess a number between 1 and 50 : 19
TOO HIGH
Guess a number between 1 and 50 : 15
Your guess was correct
The number was: 15
You guess the number with: 3 guesses
Enter x to continue to play or y to endgame
x
A new numberGuess a number between 1 and 50 : 20
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 42
Enter x to continue to play or y to endgame
y
END OF GAME
Do let me know if there is any problem.
Well, if you wish to end a loop, you could use the break; command. It jumps out of a while or for loop. So you could use this if the number is 0:
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter 'x' to continue to play or y to endgame");
choice = input.nextLine();
if(choice == "y")
{
break;
}
and add:
if(choice == "y") {break;} to the very end of the while(!Loop) loop.
And with the time when the answer is correct, you set Loop to false, which means !Loop would evaluate to true. You should change Loop = false to Loop = true when they decide to continue the game.
a small modification
public class HILOGAME {
public static void firstGame() {
final int range = 50;
int answer;
int number;
int guessNum = 0;
String choice = "";
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
if (number == answer) {
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
} else {
System.out.println("you entered a wrong value");
System.out.println("do you really want to try again? press y to continue or other alphabet to exit");
choice = input.next();
playAgain(choice);
}
}
public static void playAgain(String choice) {
if (choice.equalsIgnoreCase("Y")) {
firstGame();
} else {
System.out.println("you chose to quit");
System.exit(0);
}
}
import java.util.Random;
import java.util.Scanner;
public class HiLo {
/**
* Nick Jones
* 2/10/2015
* High or Low
*/
public static boolean high() {
int x;
boolean answer;
Random randomGenerator = new Random();
x = randomGenerator.nextInt(9 - 1) + 1;
System.out.println("number is " + x);
if (x > 6 && x < 14) {
System.out.println("You win!");
answer = true;
return answer;
} else {
System.out.println("You lose!");
answer = false;
return answer;
}
}
public static boolean low() {
int x;
boolean answer;
Random randomGenerator = new Random();
x = randomGenerator.nextInt(9 - 1) + 1;
System.out.println("number is " + x);
if (x > 0 && x < 7) {
System.out.println("You win!");
answer = true;
return answer;
} else {
System.out.println("You lose!");
answer = false;
return answer;
}
}
public static void main(String[] args) {
int points = 1000;
int risk;
int guess;
boolean answer;
int again;
do {
System.out.println("you have " + points + " points.");
Scanner input = new Scanner (System.in);
System.out.println ("Input number of points to risk: ");
risk = input.nextInt();
System.out.println ("predict <1-high, 0-low>: ");
guess = input.nextInt();
if (guess == 1) {
answer = high();
} if (guess == 0) {
answer = low();
}
if (answer = true) {
points = points + (risk*2);
**} if (answer = false) {
points = points - risk;**
}
System.out.println("You have " + points + " points.");
System.out.println("play again?<yes-1, no-0> ");
again = input.nextInt();
} while (again == 1);
}
}
This program is meant to start with the player having a score of 1000 points a number is then randomly generated and they chose a amount of their score to 'risk' then chose high or low (low - 1-6. high - 8-13) if their guess is correct their risk is doubled and added back into their score. If incorrect then risk is subtracted from score. my boolean statment seems to be stopping the program from
if (answer = false) {
points = points - risk;
this part, so my boolean never returns false is what I believe my problem is. because when run it only ever allows the player to win, never to lose, it will output that 'you lose' but still add the points as if they had won.
You are using the assignment operator =, so answer is always true. The comparison operator for equality is ==, as you have already used elsewhere in your code. But answer is already a boolean. There is no need to use == to compare it; just use it. Change
if (answer = true) {
points = points + (risk*2);
} if (answer = false) {
points = points - risk;
}
to
if (answer) {
points = points + (risk*2);
} else {
points = points - risk;
}