I'm supposed to create an array/list of 10 doubles and allow the user to type '99999' to quit. I'm also supposed to give the user an error if no doubles are entered, i.e. if the user types '99999' before any double values.
I know I could put an if (doubleList.isEmpty()) at the end of the while loop and just end the program that way, but I want to keep prompting the user for values if they enter 99999 first.
I tried entering a if(doubleList.isEmpty())" in the while(true) loop but couldn't get it to work.
The code below somewhat works.
import java.util.*;
public class DistanceTesting
{
public static void main(String[] args)
{
//Almost works, but not quite. I can't figure out how to reprompt the user if the list is empty
List<Double> doubleList = new ArrayList<>();
int count = 0;
double sum;
double average;
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter up to 10 doubles: ");
number = input.nextDouble();
if (number == 99999)
{
System.out.println("Error: you must enter at least one double.");
}
while (true)
{
count++;
System.out.println("Enter a double(or press 99999 to quit): ");
number = input.nextDouble();
if (number == 99999)
{
break;
}
if (count == 10)
{
break;
}
else
{
doubleList.add(number);
}
}
}
}
If I understand your question correctly, you will want to put if(doubleList.isEmpty()) inside the if (number == 99999) block, and delete the lines before the while loop and just handle it inside the loop.
if (number == 99999)
{
if(doubleList.isEmpty())
{
System.out.println("Error: you must enter at least one double.");
count--;
continue;
}
else
{
break;
}
}
What this does is when the user inputs 99999, it then checks if the list is empty. If it is, print the error, subtract count (since they didn't input a double you wanted), and continue starts again from the beginning of the loop, prompting them again
Related
I'm writing a number guessing game in java.
Number guessing game is a numeric version of famous hangman, where computer picks a
number between a prespecified range and user has to guess that number.
Requirements:
User must guess a number between 0-1000 and tells the user the range of guessed
number.
User has max 10 guesses.
Every time user makes a guess, total guesses reduce by one.
Computer keeps track of all the numbers user has guessed so far and shows this
information before next guess.
If the guess is correct, game ends in a win. In case of incorrect guess, computer gives a
hint to the user. If the user guess is greater than the picked number, then client tell the
user that ‘your guess is bigger’ and in case of being smaller appropriate message is
shown.
In case of invalid guess (alphabets, symbols and repeated guesses) one warning is given
and on next warning user loses a guess
The following code is running fine but it always shows the same number after guesses number. I think its not adding the new input in the arrraylist rather the first one everytime.
import java.util.*;
import java.lang.*;
public class NumberGuess {
public static void main(String[] args) {
int tries = 10;
ArrayList<Integer> guessed = new ArrayList();
int warnings = 2;
int i = 0;
Random rand = new Random();
int random = rand.nextInt(1000);
private void StartMenu () {
System.out.println("\" Welcome to the Number guessing game!\n I am thinking of a number between 0-1000\n You have 1 warning.\n You have 1 warning.\n ------------ ");
}
public char[] ToCharacterArray (String input){
char arr[] = new char[input.length()];
arr = input.toCharArray();
return arr;
}
public boolean CheckInput ( char arr[]){
if (Character.isDigit(arr[0])) {
return true;
} else {
return false;
}
}
String input;
while (tries > 0 && warnings > 0) {
System.out.println("You have " + tries + " guesses left.");
if (tries == 10) {
System.out.println("guessed number: ");
} else {
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(guessed.get(i));
}
}
System.out.println("Please guess a number:");
Scanner sc = new Scanner(System.in);
input = sc.next();
char InputString[] = ToCharacterArray(input);
if (CheckInput(InputString)) {
int intInput = Integer.parseInt(input);
guessed.add(intInput);
if (intInput > random) {
System.out.println("Your guess is greater");
}
if (intInput < random) {
System.out.println("Your guess is smaller");
}
if (intInput == random) {
System.out.println("Congrats! You win.");
System.out.println("The guessed number is: " + intInput);
tries = -1;
}
}
tries--;
}
}
}
The problem is because you iterate over the guessed numbers, and then print out the item of index i from that list. The number i at that point will always be zero, so it will always print just the first element from that list. Instead, you can just print the a, that is the element itself, after the iteration on guessed. Here is how it will look like:
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(a);
}
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".
Good day guys, I am new in this. I am doing an assignment for my prog unit, so please bear with me.
So what I have to do is to write up a code that can input people's ages, from integers between 1 to 120 inclusive. The user then have to calculate the average age, and should be calculated as a real number. But the user has to input age values until the user enters 0, which is to stop the program then output the average. If the user enters an age that is invalid, then the program should continue to re-prompt the user until they enter a valid age.
So I did my part. I created a code and I come up with this:
public static void main(String[] args)
{
int ageValue = 0;
double getAge;
getAge = inputAge();
System.out.println("Average age is: " + getAge);
}
public static double inputAge()
{
int ageValue = 0;
double avgAge = 0;
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 120; i++)
{
System.out.println("Enter age");
ageValue += sc.nextInt();
avgAge = ageValue / (double) i;
if (ageValue == 0)
{
System.out.println("Average age is: " + avgAge);
System.exit(0);
}
while (ageValue < 0 || ageValue > 120)
{
System.out.println("Invalid input. Try again!");
ageValue = sc.nextInt();
}
}
return avgAge;
}
Now I laid down my code and I got my average formula somehow working. Now, the problem is that when I press 0, it doesn't prompt the "if" statement. However, when the first "Enter your age" prompt comes up and I pressed 0, the "if" statement worked. But for each iteration, the program won't let me execute the statement.
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks. What I wanted is when I press 0, it should exit the loop and output the average, like what the task said.
I don't know if you guys can get it.. Is the code right? Am I on the right track? Am I missing something???
Cheers
You could consider a do while loop approach. This would allow your code to naturally run once, and exit once the user enters 0:
int ageValue = 0, numOfAges = 0, sumOfAges = 0;
do {
System.out.println("Enter age");
ageValue = sc.nextInt();
if (ageValue < 0 || ageValue > 120)
System.out.println("Bad value... try again");
else if (ageValue != 0) {
sumOfAges += ageValue;
numOfAges++;
}
} while (ageValue != 0);
return ((double)sumOfAges / numOfAges);
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks.
You can have another condition in your for loop like this
boolean finished = false;
for (int i = 1; i <= 120 && finished == false; i++)
and replace
System.exit(0)
with
finished = true;
However, I would question why using "break" will score you zero marks. This is exactly the sort of scenario break was intended for.
you can try this approach.
i've corrected a bit the exit condition and the way averaging is done.
the "for" loop you show in your code is limiting the number of sample to 120, but the question don't say so, so i took the liberty to generalise you question to any number of sample to average.
first thing is you should look up "if-else" conditionnal structure, as that was the main point missing in your code.
https://en.wikipedia.org/wiki/Conditional_(computer_programming)
you can think the way the problem is expressed as :
calculate the average in a serie
the serie is keyboard inputted
when zero is inputted, exit the loop and return the current average
when any value out of bound [0,120] is inputted, give a message and continue the loop without changing anything to the serie
when any value inside the bound [1,119] is inputted add the value to the serie and recalculate the average
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Final Average age is: "+inputAge());
}
private static double inputAge()
{
int ageValue=0;
double avgAge=0;
boolean shouldExit=false;
Scanner sc=new Scanner(System.in);
List<Integer> samples=new ArrayList<Integer>();
// loop until flag is true
while(!shouldExit)
{
System.out.println("Enter age");
ageValue=sc.nextInt();
if(ageValue==0)
{
shouldExit=true;
}
else if(ageValue<0||ageValue>120)
{
System.out.println("Invalid input. Try again!");
}
else
{
// add current input in the samples and calculate average over all the samples
samples.add(ageValue);
avgAge=getAvg(samples);
System.out.println("Current Average age is: "+avgAge);
}
}
sc.close();
return avgAge;
}
private static double getAvg(List<Integer> samples)
{
double avgAge=0;
for(Integer tmp:samples)
{
avgAge+=tmp;
}
return avgAge/(double) samples.size();
}
}
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);
}