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);
}
Related
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"
I have a question regarding loops. Basically the program rotates around prompting user to enter integers until three integers have been entered which are the same ones but the issue is if i enter a different integer at the beginning and then enter three same integer i am not able to make my program accept it as three similar integer in the row..
This is the actual question: Write a Java program that prompts the user to enter integers from the keyboard one at a time. The program stops reading integers once the user enters the same value three times consecutively (meaning three times in a row, one after the other). Once input is completed the program is to display the message “Same entered 3 in a row
output:
Enter an integer: 77
Enter an integer: 56
Enter an integer: 56
Enter an integer: 78
Enter an integer: 56
Enter an integer: 22
Enter an integer: 22
Enter an integer: 22
Same integer value entered thrice
I am not able to get the above output correctly. Can anyone please help me in this..
Here is the same program which i tried:
import java.util.Scanner;
public class Naim5c
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int count = 0;
int a,b,c;
do{
System.out.println("enter an integer");
a = input.nextInt();
System.out.println("enter an integer");
b = input.nextInt();
System.out.println("enter an integer");
c = input.nextInt();
if(a==b)
{
if(b==c)
{
System.out.println("Same integer entered thrice");
}
}
else if (b==c)
{
System.out.println("enter an integer");
a = input.nextInt();
if(c==a)
{
System.out.println("Same integer entered thrice");
}
}
//System.out.println("enter an integer");
//a = input.nextInt();
else if (c==a)
{
System.out.println("enter an integer");
b = input.nextInt();
if( a==b )
{
System.out.println("Same integer entered thrice");
}
}
}while(a!=b && b!=c);
}
}
By the look of it (at least according to you) you require the need to detect when a User enters three integer numbers of the same value three times in a row rather than throughout the entire entry cycle. All you really need is a counter variable and another integer variable to hold the previously entered value. Something like this:
Scanner input = new Scanner(System.in);
int a; // To hold User's current entry value.
int count = 0; // To hold the number of times the same value was entered.
int prevInt = 0; // To hold the value previously entered.
do{
// Since we're in a loop we only need to have
// a single prompt.
System.out.print("Enter an integer: --> ");
a = input.nextInt(); // Get User Input
// Is User entry equal to what what entered
// previously?
if (a == prevInt) {
// Yes it is...
count++; // Increment our counter
// if our counter reaches 3 then let's
// break out of our do/loop.
if (count == 3) { break; }
// Otherwise let's continue the loop from
// the start.
continue;
}
// Nope, not equal to the User's last entry so
// let's make prevInt hold the Users new entry.
prevInt = a;
// Let's reset our counter to 1. We need to set
// to 1 because the last User's input which is
// now held in prevInt is the actual first entry
// for the new integer value.
count = 1;
} while(count < 3); // Keep looping if our counter is less than 3
// Display that a triple entry was made.
System.out.println("Same integer (" + a + ") entered thrice");
You don't need three variables. Just one variable for remembering the last int and a counter variable for recording how many times you've seen the last integer.
int count = 0;
Integer prevInt = null;
do {
System.out.println("enter an integer");
int i = input.nextInt();
if (prevInt == null || i != prevInt) {
count = 1;
} else {
count++;
}
prevInt = i;
} while (count != 3);
System.out.println("Same integer value entered thrice");
You can try this.
Scanner input = new Scanner(System.in);
int num = 0; //holds the current input
boolean check = false; // checking for the input
ArrayList<Integer> number = new ArrayList<Integer>();
do {
System.out.println("Enter an integer");
num = input.nextInt();
number.add(num); // add the current input to the array list
if (number.size() >= 3) { // check if there's 3 or more values in the array
if (number.get(number.size() - 1) == number.get(number.size() - 2) && number.get(number.size() - 2) == number.get(number.size() - 3))
{ // check for input if the same
check = true;
System.out.println("\nSame integer value entered thrice");
}
}
} while(check == false);
// checking for loop to continue of no 3 consecutive input of number is the same
Hello if you want to make a loop you need the for command. And loops uses arrays
int[] I = new int[3]
for(j=0;j<3;j++)
{
System.out.println("enter an integer");
I[j] =input.nextInt();
}
if(I[0]==I[1] || I[1]==I[2]){
System.out.println("Same integer entered thrice");
continue;
}
Assume that code is inside your do while code. Feel free to reply if you have questions
You should simply loop everything back to inputing using "continue".
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);
I am trying my hand a few basic do-while codes, and am running into a couple of problems.
I want the code to ask the user to input 1 of 3 options (choosing which group they would like to add a number to, or to exit and total), give an error if they input an irrelevant option, and then total all ints at the end for each group.
public static void main(String[] args) {
String answer = "default";
int grp1 = 0;
int grp2 = 0;
int input1 = 0;
int input2 = 0;
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (answer.equals("A") || answer.equals("B"));
grp1 += input1;
grp2 += input2;
keyboard.close();
System.out.println("Group 1's total is: + grp1);
System.out.println("Group 2's total is: + grp2);
}
I need the to add a qualifier for if the user does not input a valid option, I tried using else:
else {
System.out.println("Invalid option - Try again.")
}
but this just skips to printing the totals, and does not ask the user for another input. How would I best achieve this?
Also,
grp1 += input1;
grp2 += input2;
Only counts the lasted entered int, is there a way to have it add all the entered ints?
Any help would be greatly appreciated, even outside of the questions I asked.
I think you have two confusions.
1) The "while" line in your code applies to the "do" block above it. That means that based on where the grp1 += and grp2 += lines are, they will only ever be run once. I suggest moving those calls to the end of the loop. You could move each line inside the relevant if block so that the code is run every time the user successfully enters a number after A or B.
2) The while condition is asking if the user entered "A" or "B". It's saying if they did, continue looping by going back to "do". If they entered literally anything else (any invalid answer), it will stop and run the code after the "while" line. I think what you really want is while (!answer.equals("X")), which will continue the loop until the user correctly enters an "X" character.
You'll also want to move those grp += lines up a bit.
Just change the condition inside while And also shift the totalling logic
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
grp1 += input1;
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
grp2 += input2;
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (!answer.equals("X"));
keyboard.close();
This will make your do while loop running i.e showing options to user until they wishes to exit. And also group total would be updated properly. I have updated answer based on answer by #Devin Howard
User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}