Recently I started programming in java so I don't know too much but I need some help. I wrote a calculator (if you can even call it that...) there isn't a gui or anything yet but I wanted to revise my code into a loop so it would take the users first number, second number and what they wanted to do (add subtract ect) and solve it and then re-loop so it would do it again. I tried a do-while loop but I couldn't get it to work.
import java.util.Scanner;
public class Calculator {
public static void main(String [] args){
Scanner in=new Scanner(System.in);
long sum = 0;
long num1 = 0;
long num2 = 0;
char s=' ';
String answer="yes";
border();
System.out.println("Acara's Calculator™ V_.01");
border();
System.out.println("What is your first number? ");
num1=in.nextInt();
System.out.println("What is your second number? ");
num2=in.nextInt();
System.out.println("What operation would you like to do?");
System.out.println("Press '+' for addition, '-' for subtraction, '/' for division or '*' for multiplication.");
s=in.next().charAt(0);
if (s=='/'){
sum=num1/num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='*'){
sum=num1*num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='+'){
sum=num1+num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='-'){
sum=num1-num2;
System.out.println("Your answer is : " + sum);
}
border();
}
public static void border(){
System.out.println("***** ***** ***** ***** ***** ***** ***** ***** ***** *****");
}
}
Try this
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long sum = 0;
long num1 = 0;
long num2 = 0;
char s = ' ';
String answer = "yes";
while (true) {
border();
System.out.println("Acara's Calculator™ V_.01");
System.out.println("What operation would you like to do?");
System.out.println("Press '+' for addition, '-' for subtraction, '/' for division or '*' for multiplication and 'q' for quit.");
s = in.next().charAt(0);
if (s == 'q') {
break;
}
border();
System.out.println("What is your first number? ");
num1 = in.nextInt();
System.out.println("What is your second number? ");
num2 = in.nextInt();
if (s == '/') {
sum = num1 / num2;
System.out.println("Your answer is : " + sum);
} else if (s == '*') {
sum = num1 * num2;
System.out.println("Your answer is : " + sum);
} else if (s == '+') {
sum = num1 + num2;
System.out.println("Your answer is : " + sum);
} else if (s == '-') {
sum = num1 - num2;
System.out.println("Your answer is : " + sum);
}
border();
}
}
public static void border() {
System.out.println("***** ***** ***** ***** ***** ***** ***** ***** ***** *****");
}
}
Here is the kind of loop you needed.
import java.util.Scanner;
public class Calculator {
public static void main(String [] args){
Scanner in=new Scanner(System.in);
long result = 0;
long num1 = 0;
long num2 = 0;
char s=' ';
String token = "";
border();
System.out.println("Acara's Calculator™ V_.01");
border();
while (true){
System.out.println("What is your first number? ... Or press ! to quit.");
token = in.next();
if ("!".equalsIgnoreCase(token.trim())){
break;
}
num1 = Integer.parseInt(token);
System.out.println("What is your second number? ... Or press ! to quit.");
token = in.next();
if ("!".equalsIgnoreCase(token.trim())){
break;
}
num2 = Integer.parseInt(token);
System.out.println("What operation would you like to do?");
System.out.println("Press '+' for addition, '-' for subtraction, '/' for division " +
"or '*' for multiplication... Or press ! if you want to quit.");
token = in.next();
if ("!".equalsIgnoreCase(token.trim())){
break;
}
s=token.trim().charAt(0);
if (s=='/'){
result=num1/num2;
System.out.println("Your answer is : " + result);
}
else if (s=='*'){
result=num1*num2;
System.out.println("Your answer is : " + result);
}
else if (s=='+'){
result=num1+num2;
System.out.println("Your answer is : " + result);
}
else if (s=='-'){
result=num1-num2;
System.out.println("Your answer is : " + result);
}
border();
}
}
public static void border() {
System.out
.println("***** ***** ***** ***** ***** ***** ***** ***** ***** *****");
}
}
This is probably what you want - it encloses your code in a while loop, but does so without making one huge main() function:
import java.util.Scanner;
public class Calculator {
private static final Scanner in = new Scanner(System.in);
public static void main(String [] args){
singleLoop();
while(shouldContinue()) {
singleLoop();
}
}
private static boolean shouldContinue() {
System.out.println("Run again? (yes/no)");
return (in.next().equalsIgnoreCase("yes"));
}
private static void singleLoop() {
long sum = 0;
long num1 = 0;
long num2 = 0;
char s=' ';
String answer="yes";
border();
System.out.println("Acara's Calculator™ V_.01");
border();
System.out.println("What is your first number? ");
num1=in.nextInt();
System.out.println("What is your second number? ");
num2=in.nextInt();
System.out.println("What operation would you like to do?");
System.out.println("Press '+' for addition, '-' for subtraction, '/' for division or '*' for multiplication.");
s=in.next().charAt(0);
if (s=='/'){
sum=num1/num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='*'){
sum=num1*num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='+'){
sum=num1+num2;
System.out.println("Your answer is : " + sum);
}
else if (s=='-'){
sum=num1-num2;
System.out.println("Your answer is : " + sum);
}
border();
}
public static void border(){
System.out.println("***** ***** ***** ***** ***** ***** ***** ***** ***** *****");
}
}
Related
I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}
I'm a total beginner and am working on a practice assignment. I need to be able to re-print the same addition problem if the user has answered incorrectly, but I'm not sure how to do that. All my attempts have lead to a new random addition problem appearing or adding another new random to the original, which is also not desired. I'm sure it's simple, but I am lost. Thanks in advance for any tips!
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do {
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b)) {
System.out.println("CORRECT!");
} else if (ans==0) {
System.out.println("Good bye!");
} else if (ans!=(a+b)) {
System.out.println("Incorrect, try again.");
}
} while (ans!=0);
}
}
Just simplify your code a little bit, don't overthink. You generate answers every time you get into the loop, generate your numbers outside so they stay consistent, also, a do-while, isn't necessary, just break your loop if the answer is correct or they placed 0. Also, you need to make sure that the user entered a number, so a try-catch should be placed while getting the input.
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
int ans;
while (true) {
System.out.printf("%d + %d = ?%n", a, b);
try {
ans = Integer.parseInt(input.next());
} catch (NumberFormatException e) {
System.out.println("Please enter a number!");
continue;
}
if (ans == 0) {
System.out.println("Goodbye!");
break;
} else if (ans == a + b) {
System.out.println("Correct!");
break;
} else {
System.out.println("Incorrect!");
}
}
Please see modification inline:
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
// here you keep asking the user over and over
//until they give the right result
do{
System.out.println("Incorrect, try again.");
//show again the equation to the user
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
}while(ans!=(a+b));
}
}
while (ans!=0);
}
}
Use this simple source code and similar to you (minor change):
try (Scanner input = new Scanner(System.in)) {
Random rand = new Random();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans, a, b;
ans = a = b = 0;
do {
a = rand.nextInt(10) + 1;
b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b + " = ");
try{
//Getting input as String and casting to Integer
ans = Integer.parseInt(input.nextLine());
if (ans == 0) {
System.out.println("Good bye!");
} else if (ans == (a + b)) {
System.out.println("CORRECT!");
} else if (ans != (a + b)) {
System.out.println("Incorrect, try again.");
}
}catch (NumberFormatException nfe){
System.out.println(nfe);
}
} while (ans != 0);
}
class generateNum{
Random rand = new Random ();
int a=rand.nextInt(10)+1;
int b=rand.nextInt(10)+1;
public void generate(){
System.out.print(a + " + " + b +" = ");
}
public int getsum(){
return a+b;
}
}
public class Test02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
generateNum gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
int com=gnum.getsum();
do
{
if (ans==com)
{
System.out.println("CORRECT!");
gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
com=gnum.getsum();
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=com)
{
System.out.println("Incorrect, try again.");
gnum.generate();
ans = input.nextInt();
}
}
while (ans!=0);
}
}
There are few changes in your condition. Update your else-if(ans!=(a+b)) block.
import java.util.Random;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
boolean flag = false;
do{
System.out.println("Incorrect, try again.(0 for skip)");
int againAns = input.nextInt();
if(againAns == (a+b)){
System.out.println("CORRECT!");
flag = true;
}else if(againAns == 0){
System.out.println("You skip the answer..");
flag = true;
}
}while(flag != true);
}
}while (ans!=0);
}
}
I need to create a loop from user input. For example they have to enter how many times they want to shuffle the cards. And then it will run the loop of the cards being drawn as many times as the user input states. I will apply my entire code.
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class stringVariables {
private static boolean isValid;
public static void main (String[]args) throws NumberFormatException, IOException {
//user inputs their name in this section
Scanner user_input = new Scanner (System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next ();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next ();
String full_name;
full_name = first_name + " " + last_name;
System.out.println( full_name + " Is Now Playing");
//this is the shuffle portion as well as something to see if a number is not inputed
boolean testing = false;
String pos = "";
while(true)
{
testing = false;
Scanner sc = new Scanner(System.in);
System.out.println("How many times do you want the numbers shuffled: ");
pos = sc.next();
for(int i=0; i<pos.length();i++)
{
if(!Character.isDigit(pos.charAt(i)))
testing = true;
}
if(testing == true)
{
System.out.print("Enter only numbers.. ");
continue;
}
else
{
int key = Integer.parseInt(pos);
break;
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay after completing their name fields
delay(2000);
System.out.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/* end of explanation of the game, next i will create a new screen
with the user's name and numbers */
delay(4000);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rn = new Random();
int ch=1;
while(ch==1){
// get two random numbers between 7 and 13
Random r = new Random();
int num1 =7 + (int)(Math.random()*(7));
int num2 = 7 + (int)(Math.random()*(7));
int num3 = 7 + (int)(Math.random()*(7));
System.out.println(num1 + " + " + num2 + " + " + num3+ " = " + (num1 + num2 + num3 ));
int i = 0 ;
{
System.out.println( num1 + num2 + num3 );
i++ ;
}
if(num1 + num2 + num3 == 31){
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
}
else
System.out.println("Better Luck Next Time");
//the play again menu. this blocks any input besides 1 or 0
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
ch=Integer.parseInt(br.readLine());
}
}}
}
//delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
//delay field
}
}
}
what I need to do is loop the user input from
boolean testing = false;
String pos = "";
while(true)
{
testing = false;
Scanner sc = new Scanner(System.in);
System.out.println("How many times do you want the numbers shuffled: ");
pos = sc.next();
for(int i=0; i<pos.length();i++)
{
if(!Character.isDigit(pos.charAt(i)))
testing = true;
}
if(testing == true)
{
System.out.print("Enter only numbers.. ");
continue;
}
else
{
int key = Integer.parseInt(pos);
break;
And make it replay this loop
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rn = new Random();
int ch=1;
while(ch==1){
// get two random numbers between 7 and 13
Random r = new Random();
int num1 =7 + (int)(Math.random()*(7));
int num2 = 7 + (int)(Math.random()*(7));
int num3 = 7 + (int)(Math.random()*(7));
System.out.println(num1 + " + " + num2 + " + " + num3+ " = " + (num1 + num2 + num3 ));
int i = 0 ;
{
System.out.println( num1 + num2 + num3 );
i++ ;
}
To make it loop to the desired user input after the completion of their name
Although it's not entirely clear what you're trying to achieve I have tried to modify your code from your original post to make it more readable and function the way you want. Please see my comments in the code below, I tried to prefix all of my comments with "EDIT" so you could easily identify which are mine.
//EDIT: added new import to help with validating user input
import java.util.InputMismatchException;
import java.util.Scanner;
//EDIT: removed import that is no longer needed, see code changes below
//import java.io.BufferedReader;
import java.io.IOException;
//EDIT: removed import that is no longer needed, see code changes below
//import java.io.InputStreamReader;
import java.util.Random;
//EDIT: changed class name to java standard naming convention using uppercase for first letter.
public class StringVariables {
// EDIT: this variable is not used, I removed it
// private static boolean isValid;
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
// is not inputed
// EDIT: removed this variable as it is no longer used in the code that
// follows.
// boolean testing = false;
// EDIT: Removed this variable in favor of using Scanner.nextInt() in
// the code below
// String pos = "";
// EDIT: Added this variable and initialized to an invalid value so that
// we can loop until a valid value is entered.
int numShuffles = -1;
while (numShuffles < 0) {
// EDIT: This variable is not needed with the new logic
// testing = false;
// EDIT: This is not needed, you already have a Scanner object above
// called user_input
// Scanner sc = new Scanner(System.in);
System.out
.println("How many times do you want the numbers shuffled? ");
try {
// EDIT: modified the lines below to fix infinite loop, forgot
// about certain Scanner behavior so switched back to
// Integer.parseInt
String inputText = user_input.next();
numShuffles = Integer.parseInt(inputText);
} catch (NumberFormatException inputException) {
System.out.print("Please enter a valid number. ");
}
} // EDIT: added closing bracket here
// EDIT: none of the code commented out below is needed when using
// the new code above.
// for(int i=0; i<pos.length();i++)
// {
// if(!Character.isDigit(pos.charAt(i)))
// testing = true;
// }
// if(testing == true)
// {
// System.out.print("Enter only numbers.. ");
// continue;
// }
//
// else
// {
// int key = Integer.parseInt(pos);
//
//
// break;
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(2000);
System.out
.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// EDIT: rather than repeating the same code over and over just use a
// loop if you want to print 25 blank lines.
for (int i = 0; i < 25; i++)
System.out.println(" ");
// EDIT: see previous comment, removed duplicate code
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
// EDIT: This BufferedReader is not needed with changes to code below
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
Random random = new Random();
// EDIT: removed the following two lines to simplify the looping logic
// int ch = 1;
// while (ch == 1) {
while (true) {
// EDIT: your comment is wrong, you're creating 3 numbers here not 2
// get two random numbers between 7 and 13
// EDIT: no need to create a new Random inside the loop, you can
// re-use a single instance.
// Random r = new Random();
// EDIT: This approach is fine, but I think using the Random class
// is easier to read so I replaced your code with code that uses
// Random
// int num1 = 7 + (int) (Math.random() * (7));
// int num2 = 7 + (int) (Math.random() * (7));
// int num3 = 7 + (int) (Math.random() * (7));
// EDIT: based on your replies it seems like you want to give the user
// several changes for each run of the game and this is what you meant
// by "shuffle". I have implemented that feature below with the for loop.
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = "
+ (num1 + num2 + num3));
// EDIT: you never use the variable i so I removed this code.
// int i = 0;
// {
// System.out.println(num1 + num2 + num3);
// i++;
// }
if (num1 + num2 + num3 == 31) {
isWinner = true;
System.out
.println("Congratulations !! You are the Lucky Winner !!!!");
break;
}
}
if (!isWinner)
System.out.println("Better Luck Next Time");
// the play again menu. this blocks any input besides 1 or 0
// EDIT: again, re-use the existing scanner
// Scanner sc = new Scanner(System.in);
// EDIT: There is a much simpler and easier-to-read way to do this
// so I have removed your code and added new code after.
// EDIT: Also this code does not work correctly, it fails to exit
// properly when the user enters a letter.
// while (true) {
// System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
// String input = user_input.next();
// int intInputValue = 0;
// try {
//
// intInputValue = Integer.parseInt(input);
// Integer.parseInt(input);
// break;
// } catch (NumberFormatException ne) {
// System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
//
// ch = Integer.parseInt(br.readLine());
// }
//
// }
// EDIT: here is the new code, see previous comment.
System.out
.println("Do you want to play again? (If you do enter y or yes) ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// EDIT: close the scanner when you're finished with it.
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
Why not just use
while(true) {
try{
pos = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Use only numbers.");
}
}
for(int i = 0; i < pos; i++) {
//do the shuffling
}
I have done some altering in your code and I feel this is what you are looking for. Just copy paste the code and it should work ideally.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException, IOException {
//user inputs their name in this section
Scanner sc = new Scanner(System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = sc.next();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = sc.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
//this is the shuffle portion as well as something to see if a number is not inputed
int ch = 1;
while (ch == 1) {
int pos = 0;
System.out.println("How many times do you want the numbers shuffled: ");
while (true) {
sc = new Scanner(System.in);
try {
pos = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Use only numbers.");
}
}
// we are now going to generate their random number and add a delay after completing their name fields
delay(2000);
System.out.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/* end of explanation of the game, next i will create a new screen
with the user's name and numbers */
delay(4000);
for (int i = 0; i < 100; i++) {
System.out.println(" ");
}
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num1 = 0, num2 = 0, num3 = 0;
boolean isWinner = false;
for (int j = 0; j < pos; j++) {
num1 = 7 + (int) (Math.random() * (7));
num2 = 7 + (int) (Math.random() * (7));
num3 = 7 + (int) (Math.random() * (7));
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
if (num1 + num2 + num3 == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
isWinner = true;
}
}
if(!isWinner){
System.out.println("Better Luck Next Time");
}
//the play again menu. this blocks any input besides 1 or 0
while (true) {
System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
ch = Integer.parseInt(br.readLine());
}
}
}
}
//delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
//delay field
}
}
}
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'm trying to create a basic calculator in Java. I'm quite new to programming so I'm trying to get used to it.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation == "+");
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation == "-");
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation == "/");
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation == "*")
{
System.out.println("your answer is" + (num1 * num2));
}
}
}
This is my code. It prompts for the numbers and operation, but displays the answers all together ?
Remove the semi-colons from your if statements, otherwise the code that follows will be free standing and will always execute:
if (operation == "+");
^
Also use .equals for Strings, == compares Object references:
if (operation.equals("+")) {
Here is simple code for calculator so you can consider this
import java.util.*;
import java.util.Scanner;
public class Hello {
public static void main(String[] args)
{
System.out.println("Enter first and second number:");
Scanner inp= new Scanner(System.in);
int num1,num2;
num1 = inp.nextInt();
num2 = inp.nextInt();
int ans;
System.out.println("Enter your selection: 1 for Addition, 2 for substraction 3 for Multiplication and 4 for division:");
int choose;
choose = inp.nextInt();
switch (choose){
case 1:
System.out.println(add( num1,num2));
break;
case 2:
System.out.println(sub( num1,num2));
break;
case 3:
System.out.println(mult( num1,num2));
break;
case 4:
System.out.println(div( num1,num2));
break;
default:
System.out.println("Illigal Operation");
}
}
public static int add(int x, int y)
{
int result = x + y;
return result;
}
public static int sub(int x, int y)
{
int result = x-y;
return result;
}
public static int mult(int x, int y)
{
int result = x*y;
return result;
}
public static int div(int x, int y)
{
int result = x/y;
return result;
}
}
CompareStrings with equals(..) not with ==
if (operation.equals("+")
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
System.out.println("your answer is" + (num1 * num2));
}
And the ; after the conditions was an empty statement so the conditon had no effect at all.
If you use java 7 you can also replace the if statements with a switch.
In java <7 you can test, if operation has length 1 and than make a switch for the char [switch (operation.charAt(0))]
import java.util.Scanner;
public class AdditionGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter The First Number");
num1 = input.nextInt();
System.out.println("Please Enter The Second Number");
num2 = input.nextInt();
Scanner op = new Scanner (System.in);
System.out.println("Please Enter The Operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("Your Answer is "+(num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("Your Answer is "+(num1 - num2));
}
else if (operation.equals("*"))
{
System.out.println("Your Answer is "+(num1 * num2));
}
else if (operation.equals("/"))
{
System.out.println("Your Answer is "+(num1 / num2));
}
}
}
Java program example for making a simple Calculator:
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
float a, b, res;
char select, ch;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("(1) Addition\n");
System.out.print("(2) Subtraction\n");
System.out.print("(3) Multiplication\n");
System.out.print("(4) Division\n");
System.out.print("(5) Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(select)
{
case '1' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a - b;
System.out.print("Result = " + res);
break;
case '3' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a * b;
System.out.print("Result = " + res);
break;
case '4' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a / b;
System.out.print("Result = " + res);
break;
case '5' : System.exit(0);
break;
default : System.out.print("Wrong Choice!!!");
}
}while(choice != 5);
}
}
maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
public class SwitchExample {
public static void main(String[] args) throws Exception {
System.out.println(":::::::::::::::::::::Start:::::::::::::::::::");
System.out.println("\n\n");
System.out.println("1. Addition");
System.out.println("2. Multiplication");
System.out.println("3. Substraction");
System.out.println("4. Division");
System.out.println("0. Exit");
System.out.println("\n");
System.out.println("Enter Your Choice ::::::: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int usrChoice = Integer.parseInt(str);
switch (usrChoice) {
case 1:
doAddition();
break;
case 2:
doMultiplication();
break;
case 3:
doSubstraction();
break;
case 4:
doDivision();
break;
case 0:
System.out.println("Thank you.....");
break;
default:
System.out.println("Invalid Value");
}
System.out.println(":::::::::::::::::::::End:::::::::::::::::::");
}
public static void doAddition() throws Exception {
System.out.println("******* Enter in Addition Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Addition : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Addition : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 + no2;
System.out.println("Addition of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doSubstraction() throws Exception {
System.out.println("******* Enter in Substraction Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Substraction : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Substraction : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 - no2;
System.out.println("Substraction of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doMultiplication() throws Exception {
System.out.println("******* Enter in Multiplication Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Multiplication : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Multiplication : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 * no2;
System.out.println("Multiplication of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doDivision() throws Exception {
System.out.println("******* Enter in Dividion Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Dividion : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Dividion : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
float result = no1 / no2;
System.out.println("Division of " + no1 + " and " + no2 + " is ::::::: " + result);
}
}
we can simply use in.next().charAt(0); to assign + - * / operations as characters by initializing operation as a char.
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char operation;
int num1;
int num2;
System.out.println("Enter First Number");
num1 = in.nextInt();
System.out.println("Enter Operation");
operation = in.next().charAt(0);
System.out.println("Enter Second Number");
num2 = in.nextInt();
if (operation == '+')//make sure single quotes
{
System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
System.out.println("your answer is " + (num1 * num2));
}
}
}
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
int x,
int y;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number 1");
x=input.nextInt();
System.out.println("Enter Number 2");
y=input.nextInt();
System.out.println("Please enter operation + - / or *");
Scanner op=new Scanner(System.in);
String operation = op.next();
if (operation.equals("+")){
System.out.println("Your Answer: " + (x+y));
}
if (operation.equals("-")){
System.out.println("Your Answer: "+ (x-y));
}
if (operation.equals("/")){
System.out.println("Your Answer: "+ (x/y));
}
if (operation.equals("*")){
System.out.println("Your Answer: "+ (x*y));
}
}
}