Restarting While Loop after false boolean in Java - java

I'm doing an assignment for school that requires us to find the largest of ten numbers. The numbers are between 0-9. I believe I got that part down. My problem is I'm trying to add an extra feature that is not required for the assignment. I am trying to get the loop to completely restart after the boolean statement is false and gives an error message. After I type the invalid value in, it gives the error message, but after I press "ok" it continues on to the next number. I want it to start back at the beginning of the loop.
Here's the code:
package Largest;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class LargestMain {
public static void main(String[] args) {
int number = 0;
String numStr = "";
int []myArray = new int[10];
int count = 1;
int largest = 0;
boolean valid = false;
while(valid == true); { // Loop to check validity
for(int i = 0; i < myArray.length; i++) {
myArray[i] = i + 1;
numStr = JOptionPane.showInputDialog("Please enter number " + count++ + ":");
number = Integer.parseInt(numStr); // Converts string value to integer
if(number >= largest) {
largest = number;
}
// If-Else if statements checks if values entered are equal to 0-9
if(number >= 0 && number <= 9) {
valid = true;
}
else if ((!(number >= 0 && number <= 9))) {
valid = false;
}
if (valid == false) {
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
continue;
}
}
JOptionPane.showMessageDialog(null, "The Largest Number Is: " + largest, "Results", JOptionPane.PLAIN_MESSAGE);
}
}
}
I could just end the loop here by adding return:
if (valid == false) {
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
return;
}
I just really want to learn how to restart the loop from the beginning. I tried search different topics, but none helped me solve my problem. Thanks for the help in advance!

To restart a loop, you would use the continue keyword. continue will skip to the next loop iteration.
When using a while loop, it'll simply restart the loop, since the loop doesn't end til valid is true. When using a for loop, itll skip to the next iteration (so if you're currently on index 5 and use continue, it'll move onto index 6 instead of staying at 5).
For nested loops, you can label the loop to specify which loop the statement is for:
firstloop:
while(valid) {
secondloop:
while(true) {
continue firstloop;
}
}
Also, no need for == true when checking a boolean. It could be represented as
while(valid) {
}
As for checking for false, valid == false, you'd use
while(!valid) {
}

Since you're a beginner and trying to learn, I have done a review of your code and enclosed some comments that might help you. I have posted updated code below.
Declarations: You should declare a variable in the innermost closure that requires it. Except largest, all other can go inside the for.
Your array variable did not make sense to have. Since you're keeping track of the largest as you go and not finding it at the end.
Control: Your /loop to check validity/ needs to be strictly around the input part, not your whole program, so you can repeat just the input statements till you're satisfied.
public static void main(String[] args)
{
int largest = 0;
for(int i = 1; i <= 10; i++)
{
boolean valid = false;
while (!valid)
{
String numStr = JOptionPane.showInputDialog("Please enter number " + i + ":");
int number = Integer.parseInt(numStr); //Converts string value to integer
if (number >= 0 && number <= 9)
{
valid = true;
}
else
{
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
}
}
if (number > largest)
{
largest = number;
}
}
JOptionPane.showMessageDialog(null, "The Largest Number Is: " + largest, "Results", JOptionPane.PLAIN_MESSAGE);
}

You can use a labeled continue:
firstloop:
while(valid){
secondloop:
for(int i=0; i<10; i++{
//something
if(something){
continue firstloop;
}
}
}
See the documentation for more details.
UPDATE: Also... there is no need for the condition in the else part of your if/else statement. Just doing a else{ valid=false } would be equivalent to what you're doing right now. Another option would be to simplify it even further and skip the if/else part alltogether and just have:
valid = number >= 0 && number <= 9

Write a recursive function, that is, a function that calls itself.
public static void DoSomething()
{
// optionally ask the user for input at this point before processing begins.
while(yourCondition)
{
// do your stuff.
}
// when execution reaches here the condition is no longer valid; start over.
if(conditionToStartOver)
DoSomething(); // start again
}

Your logic is almost right but you shouldn't be looping on valid in the outer loop. Remember, you want to stop the inner loop when an input is invalid. Normally the outer loop would give the user an option to exit the program.
So for example:
while(true) {
boolean valid = true;
for(...; ...; ...) {
...
if(number < 0 || 9 < number) {
valid = false;
break;
}
}
if(valid) {
// show largest input dialog
} else {
// show invalid input dialog
}
// optionally ask the user if they want to exit
// if so, break
}

Related

How to type correct answer in the last try without showing the game over text

I am a beginner and as you can see I made a simple Java game.
The user has 5 tries to guess a number between 1 and 20.
If the user wins a congratulations message will show.
If the user didn't succeed a game over message will pop up.
Issue
When the user enters the right answer on the 5th try both congratulations and game over messages will pop up.
Code
package org.meicode.Loops;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome");
System.out.println("Enter your name please ");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
System.out.println("Hello " + name);
System.out.println("Type 1 to start the game");
int yes = scanner.nextInt();
while (yes != 1) {
System.out.println("Type 1 to start the game");
yes = scanner.nextInt();
}
System.out.println("Guess the number in my mind,It is between 1 and 20 and you got 5 tries");
int timestried = 0;
Random random = new Random();
int x = random.nextInt(20) + 1;
while (timestried < 5) {
timestried++;
Scanner scanner1 = new Scanner(System.in);
int answer = scanner.nextInt();
if (x == answer) {
System.out.println("Well done, you did it");
} else if (x > answer) {
System.out.println("Try again,hint:the value is bigger than what you typed");
} else if (x < answer) {
System.out.println("Try again,hint:the value is smaller than what you typed");
}
}
System.out.println("Game over, the number was " + x);
}
}
How can I fix it?
Here is my attempt. I have added some comments in the code to help you.
Note that I have changed some of the file names to, so you may need to change them back for it to run, or just copy the main code section:
package com.misc;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
public class GameTest {
public static void main(String[] args) {
System.out.println("Welcome");
System.out.println("Enter your name please ");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
System.out.println("Hello " + name);
System.out.println("Type 1 to start the game");
int yes = scanner.nextInt();
//We initialize the answer variable here to use it later on.
int answer = 0;
while (yes != 1) {
System.out.println("Type 1 to start the game");
yes = scanner.nextInt();
}
System.out.println("Guess the number in my mind,It is between 1 and 20 and you got 5 tries");
int timestried = 0;
Random random = new Random();
int x = random.nextInt(20) + 1;
//Print out the randomly generated number so we can test it. We answer wrong 4 times then put in the right answer to see if the message is fixed.
System.out.println("Testing: the answer is " + x);
while (timestried < 5) {
timestried++;
Scanner scanner1 = new Scanner(System.in);
answer = scanner.nextInt();
if (x == answer) {
System.out.println("Well done, you did it");
} else if (x > answer) {
System.out.println("Try again,hint:the value is bigger than what you typed");
} else if (x < answer) {
System.out.println("Try again,hint:the value is smaller than what you typed");
}
}
//This is the conditional that uses the answer variable we declared earlier above to avoid printing out the Game Over message in a success scenario.
if (x != answer) {
System.out.println("Game over, the number was " + x);
}
}
}
Here is proof that it works. I made the program print out the real answer, answered wrong 4 times and correctly the 5th time.
Simple fix
There are 2 things I would add to your code to achieve the desired behavior:
break or exit the loop on correct answer
set a flag signaling the question was solved to later build the message upon it
Basics: How to break loops and why
You can achieve this by two ways:
break the loop when the user typed the correct answer
add an exit-condition to the loop
return from the whole method prematurely
throw an exception that can either be caught outside or will also exit the method
I will explain (1) and (2) here in this answer (3) in a separate answer.
(1) Breaking the loop
The loop shall continue until:
the maximum number of tries has been reached
the correct answer was given
Use a break; statement to break the loop if correct answer:
if (x == answer) {
System.out.println("Well done, you did it");
break;
}
Note: contrary a continue; will skip further loop-body and jump to the next iteration.
(2) add a flag signaling premature exit (e.g. correct answer)
You can add a flag that is set to true if the user types the correct answer:
boolean userHasAnsweredCorrect = false;
while (timesTried < 5) { // here the flag can be added instead breaking
if (x == answer) {
System.out.println("Well done, you did it");
userHasAnsweredCorrect = true;
break;
}
}
// omitted some lines .. then at the end
if (userHasAnsweredCorrect) {
System.out.println("You beat the game!")
} else {
System.out.println("Game over, the number was " + x);
}
See how you define the flag before the loop, set it inside the loop (together with a break;) and then test on the flag after the loop.
Combined: set flag and add exit-condition
boolean userHasAnsweredCorrect = false;
while (timesTried < 5 && !userHasAnsweredCorrect) { // here the break happens instead
if (x == answer) {
System.out.println("Well done, you did it");
userHasAnsweredCorrect = true;
// break;
}
}
Find 2 more simpler ways of breaking the loop in my other answer, here follows the 3rd way:
Put the whole game into a method like startGame() and exit from that. Either exit after loop with max-tries has finished or inside the loop (prematurely) if answered guess was correct.
(3) Exiting the loop and method using return
That premature method-exit can be achieved by inserting a return; inside the loop.
public void startGame() {
// rest of preparation
// starting the game-loop
for (int i = 1; i <= maxTries; i++) { // for-i is indexed and safer (no infinite-loop)
// read input
// score or evaluate answer against x
if (x == answer) {
System.out.println("Well done, you did it");
return; // exit the method, not reaching "game-over" after the loop
}
// continue the iteration
}
// game-over (if not previously exited because of victory)
}
To have an exit-condition for the for loop, define int maxTries = 5 either as local variable, class field or constant.

While loop is endless because the break point doesn't work

I'm trying out the code below but I'm getting a endless loop. The break point doesn't seem to help at all.
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter ID Number: ");
int studentSn = keyboard.nextInt();
System.out.print("Enter your Marks: ");
int Score = keyboard.nextInt();
Scanner scan = new Scanner(System.in);
boolean stop = false;
String answer = "";
String Grade = "";
String msg = "";
int counter = 0;
while (!stop) {
if (Score < 50) {
Grade = "F";
} else if (Score <= 64) {
Grade = "P";
} else if (Score <= 74) {
Grade = "C";
} else if (Score <= 84) {
Grade = "D";
} else if (Score <= 100) {
Grade = "HD";
} else {
msg = "Invalid Input";
}
if (Grade != null) {
System.out.println("Student Serial Number: " + studentSn);
System.out.println("Your Grade is: " + Grade);
System.out.println("Do you want to continue (yes/no): " + answer);
} else {
System.out.println("Student Serial Number: " + studentSn);
System.out.println(msg);
System.out.println("Do you want to continue (yes/no): " + answer);
}
while (answer.equalsIgnoreCase("YES"));
{
counter++;
if (answer.equalsIgnoreCase("NO")) {
break;
}
}
}
}
}
There are multiple infinite loops in this scenario. With
while (!stop) {
// ...
}
you never set "stop" to true, meaning that the loop would end. The break statement in
while (answer.equalsIgnoreCase("YES"));
{
counter++;
if (answer.equalsIgnoreCase("NO")) {
break;
}
}
would only break out of that loop, not the !stop loop. If you wanted to break out of both loops, you'd need to do
MY_LABEL: while (!stop) {
// ...
while (answer.equalsIgnoreCase("YES"));
{
counter++;
if (answer.equalsIgnoreCase("NO")) {
break MY_LABEL;
}
}
or otherwise write stop = true; at some point. However, that is not the only endless loop in your code. In
while (answer.equalsIgnoreCase("YES"));
{
// loop body ^ problem here
}
your loop statement is followed by a semicolon! This should be
while (answer.equalsIgnoreCase("YES"))
{
// loop body
}
since your code right now is the same as writing
while (answer.equalsIgnoreCase("YES"))
; // do nothing
// loop body
because of how Java's syntax works. Your current code compiles because you can have a block without any loops or if statements
// do some stuff
{ // begin new scope
int x = 10;
} // end scope
int y = x; // error because x is not in scope!
but this is clearly not what you intended.
Beyond that, you never read anything into answer meaning it always equals ""-- it never equals "YES" or "NO" at all! At least somewhere you should be saying
answer = scan.nextLine();
to read input.
The entire program is a bit wonky though. Here's how I would lay it out:
// Instead of using "stop", we can just break out of the loop when we're done
while(true) {
// ...
// Prompt for input. I use "print" instead of "println" so that the user's answer will be on the same line as the question, e.g.
// Do you want to continue (yes/no): YES
// instead of
// Do you want to continue (yes/no):
// YES
// and so forth
System.out.print("Do you want to continue (yes/no): ");
// This is how we actually read input.
String answer = scan.nextLine();
// If the user doesn't say "YES" (this could be "NO" or "q" or "asdf" or anything else), break out of the loop
if(!answer.equalsIgnoreCase("YES"))
break;
}
I think you're a bit confused about how loops and input work. Just because you write System.out.println("my question: " + answer) doesn't mean that Java will read the rest of the line into answer. It'll actually write whatever is already in answer, for example
answer = "abc"
System.out.println("Question? " + answer);
// "Question? abc" will be printed, and no input will be read
// answer still equals "abc"
and additionally, if you want to ask a question repeatedly, you have to put all of that questioning into the loop. Java will not read anything new into answer until you readLine() again, so I think that's where the confusion about the while loop comes from. In your answer.equalsIgnoreCase("YES") loop, nothing new will be read unless you put answer = scan.readLine() in it.
You have two while loops going on, your attempt to break has not been executed correctly, is only exiting the inner loop.
Let strip your loop logic back to only describing the variables and logic that will affect the loop itself: I have replaced your other code with method calls to simplify the demo, assume that you already implemented these methods and that they do what the names infer.
This is a good technique for transitioning form pseudo code to actual code but just as useful for evaluating loop constructs that aren't going the way you planned
int studentSn = ReadInt("Enter ID Number: ");
int Score = ReadInt("Enter your Marks: ");
string answer = "";
boolean stop = false;
while(!stop) { // this is never ending, nothing ever sets stop to true
Grade = DetermineGrade(score);
if (Grade != null) {
ShowGrade(studentSn, Grade);
answer = ReadContinuePrompt();
} else {
ShowError(studentSn, "Invalid Input");
answer = ReadContinuePrompt();
}
while (answer.equalsIgnoreCase("YES"));
{
counter++;
if (answer.equalsIgnoreCase("NO")) {
break;
}
// If this user's input was not NO, then this loop is infinite and should run into a stack overflow error when the value of counter exceeds the max value of int
}
}
Your outer loop is based on a stop variable:
while (!stop)
So inside your loop logic, instead of using a break statement, all you need to do is set the value of stop to true. A carefully placed break statement could also do this, but coding a deliberate stop parameter the way you have is a good design that makes the intent very clear.
Now your inner loop is just wrong, I don't want to over analyse it, because you ask for the user input outside of the loop, there is no way to change the answer. So lets replace the inner loop with a simple conditional statement
if(answer.equalsIgnoreCase("NO"))
stop = true; // or break;
else
counter++;
Now we need to go back to how you have coded your outer loop. Again, because the main input is outside of the loop, there is no amount of times with this code where we can say "YES" that will give a different answer, we need to ask the score input inside the loop so the result can be changed
That now gives us this logic:
int studentSn = ReadInt("Enter ID Number: ");
string answer = "";
boolean stop = false;
while(!stop) {
// read the score inside the loop.
int Score = ReadInt("Enter your Marks: ");
Grade = DetermineGrade(score);
if (Grade != null) {
ShowGrade(studentSn, Grade);
answer = ReadContinuePrompt();
} else {
ShowError(studentSn, "Invalid Input");
answer = ReadContinuePrompt();
}
if(answer.equalsIgnoreCase("NO"))
stop = true; // or break;
else
counter++;
}

java do while loop keeps looping after condition is met

I am a new java programmer and I am writing a program that sets 3 model numbers for 3 printers. If user inputs wrong values I want it to continue asking user for the model number. I got it to work but only if the first value the user inters the the number for one of the 3 printers. if the first value is not one of the possible values and the second input is it still keeps repeating the loop.
package printing;
import java.util.Scanner;
public class newClass {
public static void main(String[] args) {
int count = 0;
String machine1 = "546";
String machine2 = "892";
String machine3 = "127";
Scanner s = new Scanner(System.in);
System.out.print("Model Number:");
String modelNumber = s.nextLine();
// increment count if first input value is wrong
if (!s.equals(machine1) || !s.equals(machine2) || !s.equals(machine3))
count++;
// if user inputs right value
while (true) {
if (modelNumber.equals(machine1)) {
System.out.println("Machine 1 is online");
break;
}
if (modelNumber.equals(machine2)) {
System.out.println("Machine 2 is online");
break;
}
if (modelNumber.equals(machine3)) {
System.out.println("Machine 3 is online");
break;
}
// keep looping if user does not input values for machine1, machine2 or machine3
do {
System.out.println("Try again");
System.out.print("Model Number:");
String modelNumberFalse = s.nextLine();
/* each time user gets value wrong the count variable goes up by 1 and
the loop breaks when count reaches 3 */
count++;
if (count == 3)
break;
} while (!s.equals(machine1) || (!s.equals(machine2)) || (!s.equals(machine3)) && (count < 2));
}
}
}
Also each time the user inputs the wrong value I want the count variable to increment until it reaches 3 and the do while loop breaks but it keeps asking for the model number after I've entered the wrong values more than 3 times.
There are several problems. This line is wrong:
while(!s.equals(machine1) || (!s.equals(machine2)) || (!s.equals(machine3)) && (count < 2));
s is a Scanner, not a String, this isn't a valid comparison. Substituting modelNumber for s gives:
while(!modelNumber.equals(machine1) || (!modelNumber.equals(machine2)) || (!modelNumber.equals(machine3)) && (count < 2));
This can't be false unless modelNumber, machine1, machine2, and machine3 are all the same value.
Also testing count is messing this up and is redundant since you're testing it and breaking within the loop.
It should be
while(!modelNumber.equals(machine1)
&& (!modelNumber.equals(machine2))
&& (!modelNumber.equals(machine3)));
See DeMorgan's Laws. Applying this rule gives
while(!(modelNumber.equals(machine1)
|| modelNumber.equals(machine2)
|| modelNumber.equals(machine3)))
which may be easier to read.
Also, if you substitute "return" for "break;" along with making the change to the do-while condition, it works. So there is something else going on. Calling break in the inner do-while causes control to return to the top of the outer while loop. Adding a boolean flag that is set before you break and which is tested in the outer while loop would be one way to solve this. Or just use return.
import java.util.Scanner;
public class newClass
{
public static void main(String[] args)
{
int count = 0;
String machine1 = "546";
String machine2 = "892";
String machine3 = "127";
Scanner s = new Scanner(System.in);
while (true)
{
System.out.print("Model Number:");
String modelNumber = s.nextLine();
// increment count if first input value is wrong
if ((!modelNumber.equals(machine1)) || (!modelNumber.equals(machine2)) || (!modelNumber.equals(machine3)))
count++;
if (count == 3)
{
System.out.println("You have utilized your maximum number of try's");
break;
}
if (modelNumber.equals(machine1))
{
System.out.println("Machine 1 is online");
break;
}
if (modelNumber.equals(machine2))
{
System.out.println("Machine 2 is online");
break;
}
if (modelNumber.equals(machine3))
{
System.out.println("Machine 3 is online");
break;
}
System.out.println("Try again");
}
}
}
Hope this solves your question
First: you use NOT OR when you need NOT AND
Second: You are repeating
the test for no good reason
In your code, you end up having the same test repeated. This means, as you add machines, you will have to update your code in multiple places.
First rule of software is to not repeat yourself. When the next guy is asked to chance the conditions, he/she will find the first block of code and edit it and probably never notice the repeated block. Copy pasted code is the root or many future bugs.
You could simplify your code to having each check only once like this:
import java.util.Scanner;
public class newClass {
public static void main(String[] args) {
int count = 0;
// for extra credit, try to make this an ArrayList
// so you can keep adding models as needed
// then you would adjust your tests to leverage the ArrayList
// search functions
String machine1 = "546";
String machine2 = "892";
String machine3 = "127";
Scanner s = new Scanner(System.in);
// when using a while loop, it is good practice to use a boolean
// as your logic expands, multiple tests in the loop may set the
// boolean to true or false
// it is cumbersom to have large blocks of code in your while check
boolean keepOnTrucking = true;
System.out.print("Enter Model Number:");
while (keepOnTrucking) {
String modelNumber = s.nextLine();
// when using multiple tests, it is good
// to give each test its own line and end the line
// with the logical operator that joins it to the next
// it makes it easier to read
// and easier to edit (add or remove tests)
// Logical operator note:
// Your test was: not A OR not B OR not C
// This would NEVER work, as A != B != C
// If a user entered machine2, the check would
// fail for !(machine1), OR !(machine2) OR !(machine3)
// because while (!s.equals(machine2)) would say false
// (!s.equals(machine1)) would say true, and the OR
// chain would stop and count it as an error.
// Instead you want:
// !(machine1) && !(machine2) && !(machine3)
// Thus to to error, it has to not any of the machines.
// If it is true for all three nots, then you have an error
if (!machine1.equals(modelNumber) &&
!machine2.equals(modelNumber) &&
!machine3.equals(modelNumber)) {
// you only increment on failure
count++;
// nice developers give meaningful feed back to users
if (count>=3) {
System.out.print("Out of guesses! Go Away!"); // even when it is mean
// since you are nested in one while loop,
// this will break you out
break;
} else {
System.out.print("Not a valid model number, please re-enter:");
}
} else {
// the found a machine, so exit the while loop
keepOnTrucking = false;
if (machine1.equals(modelNumber)) {
System.out.println("Machine 1 is online");
} else if (machine1.equals(modelNumber)) {
System.out.println("Machine 2 is online");
} else { // since this ins the only one left, you don't need an if clause
System.out.println("Machine 3 is online");
}
}
}
}
}

Error checking duplicate user-input array values

I am self-learning Java and am stuck on a simple project. I'd like to receive 6 unique 'lottery' numbers from a user.
User will be asked to input an integer.
Each user input will be placed into an array.
If the user inputs a previously input number, I want to prompt to reenter the number again.
Recheck the new input. If unique, continue the for loop. If non-unique, run step 3 again.
So far, all I have is:
public static int[] userLottoInput()
{
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < userNums.length; i++ ) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
for (int k=i; k<userNums.length; k++) {
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}
}
}
Any help is appreciated!!
Try and keep you logic simple.
While the user hasn't enter 6 numbers, loop
Ask the user for a value
Check to see if it's a duplicate
If it is, ask the user to re-enter the value
If it's not (a duplicate) increment the counter to the next element...
For example...
public static int[] userLottoInput() {
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
int i = 0;
// Keep looping until we fill the array, but
// allow the control to fall somewhere else
while (i < userNums.length) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
// Check for duplicates
boolean duplicate = false;
// We only need to check up to i - 1, as all the
// other values are defaulted to 0
// We also don't need to check for the last number entered ;)
for (int k = 0; k < i; k++) {
// Check for duplicated
if (userNums[k] == userNums[i]) {
System.out.println("No duplicates allowed, please try again");
duplicate = true;
// Break out of the loop as we don't need to check any more..
break;
}
}
// If no duplicates where found, update i to the next position
if (!duplicate) {
i++;
}
}
return userNums;
}
With this, there is only one point at which you prompt the user. Everything else is used to control the element position (i) to meet your requirements.
Now, I'm sure that there are other ways to do this and this is just a simple example ;)
Move the asking of number outside loop, when received the number loop over the numbers array to find a match. If match found re-ask for number (outside the for loop used for finding the match), else if match not found, then add the number to array.
Don't you think your for loop is little complicated. Anyways, you can try this :
for (int k=0; k<i-1; k++) { //Start k=0 means from the first stored value
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}

Simple Java Query - Getting a Result from a Integer

I have been set an assignment where I must find the average of a list of positive numbers enterd by the user, the amount of numbers entered is unknown. So far I have got the program to add all numbers that have been entered (the entry teminates when a user enters 0). I do not want the answer to this question on here because I am really trying to learn this fast!
I am having trouble with the while statement,
I wanted to say
WHILE ( numberentered = 0 );
......
but this doesnt seem to work
I originally did it like so:
while ( numberentered >= 1 );
System.out.print (numbersum);
but this still jumps out of the do loop when a negative number is entered.
Any idea guys.... If you understand my question but it is still worded very badly... please edit.
Thank you.
while (numberentered != 0) { < read new number and add it to total and ... (but you didn't want the answer...) > }
Shouldn't you be doing this?
while(numberEntered != 0) {
// add it up
}
It seems like maybe you meant to do:
while (numberentered != 0) {
//do stuff
}
Note that no semicolon is needed on the 'while' line itself.
This is what I interpreted the problem statement:
"User is allowed to enter the numbers as many times but when it enters 0, the program would display the average of the numbers being entered prior to 0 and exit"
You may go this way:
public static void main(String args[]) {
float no = 0;
float average = 0;
int count = 1;
if(args.length == 0) {
printf("No number being entered...program exits");
System.exit(0);
}
if(args[0] == 0) {
displayAverage(average);
return;
}
for(count;count<args.length;count++){
try {
no = Float.parseFloat(args[count]);
if(no == 0 ) {
break;
}
average = average + no;
}
catch(NumberFormatException nfe) {
printf("Please enter only numbers");
}
}
average = average/count;
printAverage(average);
}
private void displayAverage(float average){
System.out.println("average is: "+ average);
}
hope this may helps..

Categories