I am fairly new to programming Java. I want to make a lotto program. Here is the code:
package me.nutella;
import java.util.Scanner;
public class Lotto {
#SuppressWarnings("resource")
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter A Number Between 1-20!");
int choice = scanner.nextInt();
if (choice > 20)
System.out.print("Please Only Pick Numbers Between 1-20!");
int b = (int) (Math.random() * 20) +1;
if (choice == b)
System.out.print("You Win!");
else
System.out.print("You Lost! The correct answer was " + b);
}
catch(Exception E) {
System.out.print("Your Answer Must Be Numeric!");
}
}
}
Now, this part if what I am mainly concerned about:
if (choice > 20)
System.out.print("Please Only Pick Numbers Between 1-20!");
I want to make it so if someone puts the number over 20, it will print that message. Now this part does work, but when I put the number over 20, it still plays the lotto game. I want to make it so if they put their number higher than 20, it will not play the game and enter that message.
How can this be done?
Can be most elegantly done using a do {...} while(); loop. At the beginning, the user must always enter a number, so the loop MUST execute at least once. This is where a do {...} while(); loop comes in handy. You can display your message at the beginning of the loop, then read in the users input. If it is in an acceptable range, the loop never re-executes, and the code moves on. But, if it is not acceptable, we re-execute the loop until we get an acceptable value.
Below is how I would approach this problem:
Scanner scanner = new Scanner(System.in);
int choice = 0;
do {
System.out.print("Please Pick A Number Between 1-20!");
choice = scanner.nextInt();
} while(choice > 20 || choice < 1);
It is also worth noting that your message states that "Number between 1-20", but your code only checks that choice < 20, so if a user enter anything LESS THAN 20, it would be accepted. This includes 0, negatives, and of course the valid number range. I added the || choice < 1 check in my example.
What you need is a loop to keep getting inputs if input is not valid:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter A Number Between 1-20!");
int choice = scanner.nextInt();
boolean validInput=false;
while(!validInput) {
int choice = scanner.nextInt();
if (choice > 20) {
System.out.print("Please Only Pick Numbers Between 1-20!");
} else {
validInput=true;
}
}
int b = (int) (Math.random() * 20) +1;
if (choice == b)
System.out.print("You Win!");
else
System.out.print("You Lost! The correct answer was " + b);
Related
trying to create a Random number generator within a while loop that controls the Number Guessing Game. The issue is the "too high" and "too low" hints will say one number (ex:35) is too low, but then say the nest input number (ex:36) is too high. Then when I move the call a random function in the nested while loop, it generates the same random number each time.
I have tried moving the call to random function to my most inner loop, but then it generates the same random number. Currently, it is in the outer while loop, but then the issue of the high/lows occurs
import java.util.Scanner;
import java.util.Random;
public class numberGuessingGame
{
public static void main (String[] args)
{
int randomNumber, userNumber = 0, guesses = 0, correct;
final int MAX = 100;
char playAgain, playGame = 'y';
//ask user if they wish to play
System.out.println("Would you like to play the Number Guessing Game? y / n");
Scanner scan = new Scanner (System.in);
playGame = scan.next().charAt(0);
Random generator = new Random();
//while loop to continue to exacute game as long as user enters 'y'
while (playGame == 'y'){
if (playGame != 'y')
break;
randomNumber = generator.nextInt(MAX) + 1;
//flag
correct = 0;
//loop to control the round
while (correct == 0) {
//get user number
System.out.println("Please pick a number between 1 and 100.");
userNumber = scan.nextInt();
//high and low sugguestion
if (userNumber > randomNumber)
System.out.println("Number is too high, try something lower.");
if (userNumber < randomNumber)
System.out.println("Number is too low, try something higher.");
if (userNumber == randomNumber){
System.out.println("That number is correct!");
System.out.println("Would you like to play again? y/n");
playGame = scan.next().charAt(0);
}
guesses++;
System.out.println("You have guessed " + guesses + " times!");
}
}
//break statement skips here when 'n' is entered in
// the game prompting question
System.out.println("Thanks for playing, have a nice day!");
}
}
I'd like to suggest some changes you might consider:
use a boolean for correct rather than an int
remove your if statement immediately after the while: it is redundant
use do-while when the loop must be executed at least once
use Integer.compareTo rather than separate comparisons
Your inner loop does not terminate that's why you have the same
randomNumber, change correct=0 value to terminate the inner while loop
if (userNumber == randomNumber){
System.out.println("That number is correct!");
System.out.println("Would you like to play again? y/n");
playGame = scan.next().charAt(0);
correct=1; //Just to remove correct=0 value
}
i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"
So I've written a test class to test a program that will allow me to take in number of courses, letter grades, and course credits and then calculate total weighted points, total credits, and GPA within a loop designed for 3 courses max.
However, I need to validate the number of courses and prove that it will run after both an invalid and valid input have been entered.
I've gotten it so that will prompt the user for a valid number of courses after an invalid response, but once the valid response is input the program just stops instead of running like it is supposed to. Can anyone tell me why?
Here's my code:
import java.util.*;
import java.lang.*;
public class ComputeGpa
{
public static void main(String [] args)
{
Gpa grades1 = new Gpa();
Scanner in = new Scanner (System.in);
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
if(courses > 0)
{
int i = 0;
while(i < 3)
{
System.out.println("Please enter a letter grade.");
String letter = in.next();
char result = letter.charAt(0);
System.out.println("How many credits was this class worth?");
int credits = in.nextInt();
grades1.addToTotals(result, credits);
i++;
}
System.out.printf("GPA: %.2f", grades1.calcGpa());
}
else
{
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
}
}
The output for that is as follows:
Enter number of courses:
-2
Number of courses must be greater than 0. Please enter a valid number of courses.
3
And then the program stops running. Where Am I going wrong? I thought the in.next() on the letter String would fix this problem but apparently I was wrong. Any ideas?
Your flow is currently if/else.
int foo = ...;
if(foo > 0) {
//your grade stuff
}
else {
//ask for reinput
}
What ends up happening is you catch the problem input once, but never give your flow the opportunity to check it again.
Instead, use a while loop over an if/else layout, to force re-entry until you get the exact information you want, then continue.
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
while(courses < 0) {
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
int i = 0;
//...
I'm working on a project that calculates the value of a bank account based on starting balance(b), interest rate(IR), and quarters to display. My entire code works perfectly, but the very last portion is to make sure the variables like interest rate are within the confines of the boundaries my professor gave me. I do need to display an error message if the user enters a value outside the boundaries and ask for the value again.
For example, the number of quarters to display needs to be greater than zero, and less or equal to 10.
As you can see, pretty much all of my program is in a do-while loop. I know I can have nested loops, but what would I be able to put in my do-while loop that would work in this situation? An if-else statement? Try and catch block? Another while loop?
If I used a try-catch, then could anyone give me an example of how I could do that? Thank you very much for your time, and all help is appreciated! The below is my code for reference.
import java.util.Scanner;
public class InterestCalculator
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
int quartersDisplayed;
double b, IR;
do
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
System.out.println("Next enter the starting balance. ");
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
System.out.println("Finally, enter the interest rate ");
System.out.println("which must be greater than zero and less than or equal to twenty percent: ");
IR = keyboard.nextDouble();
System.out.println("You have entered the following amount of quarters: " + quartersDisplayed);
System.out.println("You also entered the starting balance of: " + b);
System.out.println("Finally, you entered the following of interest rate: " + IR);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = b + (b * IR/100 * .25);
System.out.println("Your ending balance for your quarters is " + quarterlyEndingBalance);
System.out.println("Do you want to continue?");
String yes=keyboard.next("yes");
if (yes.equals(yes))
continue;
else
break;
}
while(true);
}
}
So here's some code to answer your questions and help get you started. However, there are problems with your logic that do not pertain to your question which I will address afterward.
Note: I have added comments to your code. Most of them start with "EDIT:" so that you can tell what I changed. I didn't use this prefix in all cases because some of it is new code and it's obviously my comment
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
// EDIT: you already have a scanner defined below with a more meaningful name so I removed this one
// Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//EDIT: defining userResponse outside the loop so we can use it everywhere inside
String userResponse = null;
do {
//EDIT: moved the variables inside the loop so that they are reset each time we start over.
//EDIT: initialize your variable to a value that is invalid so that you can tell if it has been set or not.
int quartersDisplayed = -1;
//EDIT: gave your variables more meaningful names that conform to java standards
double startingBalance = -1, interestRate = -1;
//EDIT: you don't need a second Scanner, just use the one you already have.
// Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try{
startingBalance = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(startingBalance <= 0){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try{
interestRate = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
//Note: I assume twenty percent is represented as 20.0 here
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
System.out.println("You have entered the following amount of quarters: "
+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "
+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "
+ quarterlyEndingBalance);
System.out.println("Do you want to continue?");
//EDIT: modified your variable name to be more meaningful since the user's response doesn't have to "yes" necessarily
userResponse = input.next();
// EDIT: modified the logic here to compare with "yes" or "y" case insensitively.
// if (userResponse.equals(userResponse))
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
} while (true);
Now to address other issues - your interest calculation doesn't seem correct to me. Your formula does not make use of the quartersDisplayed variable at all. I assume you're compounding the interest quarterly so you will definitely need to make use of this when calculating your results.
This may be beyond the scope of your project, but you should not use double or float data types to represent money. There is a stackoverflow question about this topic that has good information.
Possible improvements - since you're asking the user for two values of type double you could create a method to ask for a double value and call it twice instead of repeating the code. This is a better approach because it helps reduce the chance of mistakes and makes testing and maintenance easier.
You can do something like this in your do/while loop:
do
{
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
}
while (quartersDisplayed < 1 || quartersDisplayed > 10);
System.out.println("Next enter the starting balance. ");
do
{
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
}
while (b < 1);
// rest of code ...
}
With the Scanner#hasNextInt (and the equivalent for double), you can avoid having exceptions thrown, and thus don't need try-catch clauses. I think in general if you can avoid try-catch, it's good, because they are clumsy - but I might be wrong.
However, my approach is like this. Inside your outer do-while, have three other do-while-loops to get the three values. The reason is that you want to keep looping until you get a correct value. The explanation of why keyboard.nextLine() is important is covered here.
I didn't include all of your code, only the part in question. Here's my take on it:
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int quartersDisplayed = -1;
double b = -1.0;
double IR = -1.0;
do {
do {
System.out.println("Enter the number of quarters.");
if(keyboard.hasNextInt()) {
quartersDisplayed = keyboard.nextInt();
keyboard.nextLine(); //important
} else {
System.out.println("You need to enter an integer.");
continue;
}
} while(quartersDisplayed < 1 || quartersDisplayed > 10);
do {
System.out.println("Enter the starting balance.");
if(keyboard.hasNextDouble()) {
b = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(b <= 0);
do {
System.out.println("Enter the interest rate.");
if(keyboard.hasNextDouble()) {
IR = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(IR <= 0 || IR > 20.0);
//... rest of code
} while(true);
}
}
I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}