not sure why while loop isn't looping - java

I am trying to prompt the user to enter 5 integers but it won't loop more than once. I don't know why this is happening and couldn't resolve the error by myself
Code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int counter= 0;
Boolean inputOK;
int iInput;
int data[]= new int[5];
// while (counter<5);
do {
System.out.println(" Please enter an integer");
while (!s.hasNextInt()) {
System.out.println("Invalid input");
System.out.println("Please Enter an integer value");
s.next();}
iInput=s.nextInt();
if (iInput < -10 || iInput > 10) {
System.out.println("Not a valid integer. Please enter a integer between -10 and 10");
inputOK = false;
} else {
inputOK = true;
}
System.out.println("before while loop"+ inputOK);
} while (!inputOK);
counter++;
System.out.println("counter value is"+ counter);
}
}

If you follow your code, you can see that when inputOK is true, there is no loop to get back to. It looks like you had some counter in mind, but you ended up not using it. The following code does what I think you intended with your code:
Scanner sc = new Scanner(System.in);
int[] data = new int[5];
for(int i = 0; i < data.length; i++) {
System.out.println("Please enter an integer.");
// Skip over non-integers.
while(!sc.hasNextInt()) {
System.out.println("Invalid input: " + sc.next());
}
// Read and store the integer if it is valid.
int nextInt = sc.nextInt();
if(nextInt < -10 || nextInt > 10) {
// Make the for loop repeat this iteration.
System.out.println("Not a valid integer. Please enter an integer between -10 and 10.");
i--;
continue;
}
data[i] = nextInt;
}
for(int i = 0; i < data.length; i++) {
System.out.println("data[" + i + "] = " + data[i]);
}

Related

How do you create a continuous loop for a Coin tossing game in Java?

I am having issues trying to make my code loop back and do the program over again until the user asks them to stop by inputting zero. I have tried a while statement but I am not sure if I implemented it correctly since all I got back was errors. I appreciate any and all the help that can be given. I have included my code below.
public class CoinTossing {
public static void main(String[] args) {
//Scanner method
Scanner input = new Scanner(System.in);
int choice;
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
Random rand = new Random();
// Simulate the coin tosses.
for (int count = 0; count < number; count++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
return;
}
}
}
Your main method could look something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
while (true) {
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
if (number == 0) { break; }
Random rand = new Random();
// Simulate the coin tosses.
for (int i = 0; i < number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
}
}
Here, the while loop is entered after the welcome message and will only exit the simulation when the user inputs a 0.
After the user input is retrieved, it will check if the user input 0. If the user inputs 0, it will break the while loop before the program simulates flipping the coin:
if (number == 0) { break; }
Place your code into a while loop with the exception of these two lines:
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
At the end of the Coin Toss Game the natural order of things would be to ask the User if he/she wants to play again. This allows the User to quit the application rather than being stuck in a continuous loop:
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
The whole application may look something like this:
public class CoinTossing {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
java.util.Random rand = new java.util.Random();
System.out.println("Welcome to the Coin Toss Program");
System.out.println("================================");
System.out.println();
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
}
}

Java loop goes 4 times for some reason

So I have this assignment where I need to loop user's input 6 times. the loop, after finishing, looped again for 3 more times. I didn't add a for lop before it so I don't know how to handle it.
Here's the code for the method:
public static int[] getPlayerNumbers(int[] playNums) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < playNums.length; i++) {
System.out.println("Please enter numbers from 1-9: " + i);
playNums[i] = input.nextInt();
while (playNums[i] < 1 || playNums[i] > 9) {
System.out.println("Invlaid input. Please only enter 1-9. ");
playNums[i] = input.nextInt();
}
}
return playNums;
}
I placed i to see the index and it goes 0 to 5 then returns to 0. I ran out of ideas, please help.
it seems your playNums has more than 6. try
public static int[] getPlayerNumbers(int[] playNums) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
System.out.println("Please enter numbers from 1-9: " + i);
playNums[i] = input.nextInt();
while (playNums[i] < 1 || playNums[i] > 9) {
System.out.println("Invlaid input. Please only enter 1-9. ");
playNums[i] = input.nextInt();
}
}
return playNums;}
I've tested your code and it seems to work for me. The playsNums contains certainly more than 6 values.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] playNums ={1, 2, 3, 4, 5, 6};
getPlayerNumbers(playNums);
for (int playNum: playNums) {
System.out.println(playNum);
}
}
public static int[] getPlayerNumbers(int[] playNums)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < playNums.length; i++) {
System.out.println("Please enter numbers from 1-9: " + i);
playNums[i] = input.nextInt();
while (playNums[i] < 1 || playNums[i] > 9) {
System.out.println("Invalid input. Please only enter 1-9. ");
playNums[i] = input.nextInt();
}
}
return playNums;
}
}
Try this
public static int[] getPlayerNumbers(int[] playNums)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 6; i++)
{
playNums[i] = input.nextInt();
if(playNums[i] < 1 || playNums[i] > 9){
System.out.println("Invlaid input. Please only enter 1-9. ");
getPlayerNumbers(playNums);
} else{
System.out.println("Please enter numbers from 1-9: " + i);
playNums[i] = input.nextInt();
}
}
return playNums;

How do I get my program (Lottery game) to check the tips again?

I am trying to write a lottery program (based on a hungarian game, 5 numbers from 1 to 90), it works almost fine, the first time i give it faulty numbers (more than 90 or 0) it tells me that I did wrong. But the second time it doesn't. It keeps on executing the game with the invalid numbers. What were your tips, and what would you Guys do differently?
Thank you for your time.
The code:
import java.util.*;
class Lottery {
static int hits = 0;
Integer[] tippek = new Integer[5];
Random rand = new Random();
ArrayList<Integer> nums = new ArrayList<Integer>();
static Lottery lot = new Lottery();
public static void main (String[] args){
lot.wnums();
lot.tipread();
lot.tipcheck();
lot.wincheck();
lot.result();
}
public void wnums () {
// GENERATING THE WINNER NUMBERS
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; set.size() < 5; i++){
int x = rand.nextInt(90) + 1;
set.add(x);
}
nums.addAll(set);
}
public void tipread (){
// READING THE TIPS
System.out.println("Please write 5 different number from 1 to 90.");
try{
Scanner scan = new Scanner(System.in);
tippek[0] = scan.nextInt();
tippek[1] = scan.nextInt();
tippek[2] = scan.nextInt();
tippek[3] = scan.nextInt();
tippek[4] = scan.nextInt();
}catch (InputMismatchException ex){
System.out.println("Error.");
}
}
public void tipcheck() {
int fault = 0;
List<Integer> tips = Arrays.asList(tippek);
try{
for(int tipp : tippek){
System.out.println(tipp);
if(tipp == 0 || tipp > 90){
fault++;
}
}
if(fault == 1){
System.out.println("One of your tips is invalid ");
System.out.println("Write other numbers");
lot.tipread();
}
if(fault > 1){
System.out.println(fault + " of your tips are invalid ");
System.out.println("Write other numbers");
lot.tipread();
}
for(int tipp : tips){
for(int i = 0; i < tips.size(); i++){
if(tips.indexOf(tips.get(i)) != tips.lastIndexOf(tips.get(i))){
System.out.println("You can write a number only once");
lot.tipread();
}
}
}
}catch (NullPointerException ex){
System.out.println("Error.");
}
}
public void wincheck () {
// CHECKING THE TIPS
try{
for(int tipp : tippek){
for(int i = 0; i < 5; i++){
if(nums.get(i) == tipp){
hits++;
}
}
}
}catch(Exception ex){
System.out.println(" ");
}
}
public void result() {
try{
Arrays.sort(tippek);
Collections.sort(nums);
String tippeksor = Arrays.toString(tippek);
System.out.println("Your tips in ascending order: " + tippeksor);
System.out.println("You have " + hits + " hits.");
System.out.println("The winning numbers are: " + nums);
}catch(Exception ex){
lot.tipread();
}
}
}
Include lot.tipcheck() as the last statement inside tipread():
public void tipread (){
// READING THE TIPS
System.out.println("Please write 5 different number from 1 to 90.");
try{
Scanner scan = new Scanner(System.in);
tippek[0] = scan.nextInt();
tippek[1] = scan.nextInt();
tippek[2] = scan.nextInt();
tippek[3] = scan.nextInt();
tippek[4] = scan.nextInt();
lot.tipcheck();
}catch (InputMismatchException ex){
System.out.println("Error.");
}
}
so to ensure that every time the user inputs valid numbers they will be checked.
Other modifications:
remove lot.tipcheck(); from main()
After every lot.tipread(); in tipcheck() add a return;
instead of calling tipread directly from tipcheck
tipcheck returns true if everything is ok, false otherwise
and use do-while in main.
public static void main (String[] args){
lot.wnums();
do {
lot.tipread();
} while(!lot.tipcheck());
lot.wincheck();
lot.result();
}
and
public boolean tipcheck() {
int fault = 0;
List<Integer> tips = Arrays.asList(tippek);
try{
for(int tipp : tippek){
System.out.println(tipp);
if(tipp < 1 || tipp > 90){
fault++;
}
}
if(fault == 1){
System.out.println("One of your tips is invalid ");
System.out.println("Write other numbers");
// lot.tipread();
return false;
}
if(fault > 1){
System.out.println(fault + " of your tips are invalid ");
System.out.println("Write other numbers");
// lot.tipread();
return false;
}
for(int tipp : tips){
for(int i = 0; i < tips.size(); i++){
if(tips.indexOf(tips.get(i)) != tips.lastIndexOf(tips.get(i))){
System.out.println("You can write a number only once");
// lot.tipread();
return false;
}
}
}
}catch (NullPointerException ex){
System.out.println("Error.");
return false;
}
return true;
}
like this.

Scanner example loop

Values are entered until a 0 is entered. Then the program ends, but before that happens the sum of all values are given if they were Integral numbers.
This is what I have tried so far but I'm stuck.
public class Aufgabe2 {
public static void main(String[] args) {
/* TODO: add code here */
int n;
int sum = 0;
boolean exit = true;
Scanner input = new Scanner(System.in);
while (true) {
n = input.nextInt();
if (n == 0) {
exit = true;
} else {
sum += n;
System.out.println(sum);
}
}
}
}
There is some good doco on Scanner on the oracle website: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner will throw an error in the event that the token you are expecting is not there. I would recommend you check for an integer input.hasNextInt() before you attempt to parse it.
Something like this:
int sum = 0;
boolean exit = true;
Scanner input = new Scanner(System.in);
while (input.hasNextInt()) {
int n = input.nextInt();
if (n == 0) {
break;
} else {
sum += n;
}
}
// Print outside of the loop
System.out.println(sum);
Result of the program
Input:
1
2
3
0
Output:
6
Try;
int n;
int sum = 0;
boolean exit = true;
Scanner input = new Scanner(System.in);
while (exit) {
n = input.nextInt();
if (n == 0) {
exit = false;
}
else {
sum += n;
System.out.println(sum);
}
}
You have a while(true) which is a continuous loop.
Working code:
import java.util.*;
public class Aufgabe2 {
public static void main(String[] args) {
/* TODO: add code here */
int n;
int sum = 0;
boolean exit = false;
Scanner input = new Scanner(System.in);
while (!exit) {
System.out.println("Enter a number:");
n = input.nextInt();
if (n == 0) {
exit = true;
} else {
sum += n;
System.out.println(sum);
}
}
}
}
Output:
Enter a number:
1
1
Enter a number:
3
4
Enter a number:
6
10
Enter a number:
0
Edit:
You have to change while (true) loop to use boolean variable exit. I have modified the code accordingly and corrected the while loop condition.

How do you stop a loop from running in Java

How do you stop a conditional loop from running. For example if I write an if statement that accepts values from 0 to 100. How do stop the program if a user enters a number less then 0 or above 100.
import java.util.Scanner;
public class TestScores {
public static void main(String[]args) {
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++) {
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100) {
try {
throw new InvalidTestScore();
}
catch (InvalidTestScore e) {
e.printStackTrace();
}
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
You use the
break;
keyword. This breaks out of a loop.
You may want to use break
for(int i=0; i<100; i++)
{
if(user entered invalid value)
break; // breaks out of the for loop
}
Here's a hint, since this looks like homework to me: you can either use the break keyword, or use this condition:
if (grade[index] < 0 || grade[index]> 100)
{
// invalid grade...
}
as part of the loop condition.

Categories

Resources