Why is my while loop not stopping after I want it to? - java

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 1;
int[] arrayNumber = new int[10];
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
}
}
} while (number != 0);
I am trying to have the user enter numbers (up to 10) and is stopped once the user enters 0. But, when 0 is entered it does not stop.

It is simply because you have an inner for loop, you're setting the number to 0 but the for loop still hasn't finished completing. Here would be the fix
This will finish executing after the user enters 10 numbers or enters 0, whichever comes first
Scanner scanner = new Scanner(System.in);
int[] arrayNumber = new int[10];
int maxNums = 0;
while (maxNums < 10) {
arrayNumber[maxNums] = scanner.nextInt();
if (arrayNumber[maxNums] == 0) break;
maxNums++;
}
This is much shorter and neater, more readable

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 1;
int[] arrayNumber = new int[10];
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
break;
}
} while (number != 0);

The point is that your code would work properly only if you enter 0 at the last iteration at for loop. You can explicitly break your loop to let the while loop process your zero value and stop the loop.
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
break;
}
}
} while (number != 0);

Related

not sure why while loop isn't looping

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]);
}

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 to count and separate consecutive heads or tails flips in java coin flip program?

I'm trying to add spaces and a counter between consecutive runs in a simple java coin toss program.
I want this output: HHHHTHTTTTTTTHTTTHHHTTTTHTTHHHTTTTHHTHHHHHTTTTTTHT
to look print like this: HHHH4 T1 H1 TTTTTTT7 H1 TTT3 HHH3 TTTT4 H1 TT2 HHH3 TTTT4 HH2 T1 HHHHH5 TTTTTT6 H1 T1
I am not sure how to position the conditions in the loop so that spaces and a counter are printed between the consecutive 'T's and 'H's. Do I need to use a different kind of loop? I have tried rearranging the loop and using break; and continue; but haven't gotten the result to print correctly.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
Random randomNum = new Random();
for (int i=0; i < timesFlipped; i++) {
int currentflip = randomNum.nextInt(2);
int previousFlip = 0;
int tailsCount = 0;
int headsCount = 0;
if (currentflip == 0) {
System.out.print("H");
previousFlip = 0;
headsCount++;
}
else if (currentflip == 1) {
System.out.print("T");
previousFlip = 1;
tailsCount++;
}
if (previousFlip == 0 && currentflip == 1) {
System.out.print(headsCount + " ");
headsCount = 0;
}
else if (previousFlip == 1 && currentflip == 0) {
System.out.print(tailsCount + " ");
tailsCount = 0;
}
}
}
You can just store the last flip and a counter like
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
Random randomNum = new Random();
int counter = 1;
int previousFlip = randomNum.nextInt(2);
printFlip(previousFlip);
for (int i=1; i < timesFlipped; i++) {
int currentflip = randomNum.nextInt(2);
if (currentflip == previousFlip) {
counter++;
} else {
System.out.print(counter + " ");
counter = 1;
previousFlip = currentflip;
}
printFlip(currentflip);
}
System.out.print(counter);
}
private static void printFlip(int currentflip) {
if (currentflip == 0) {
System.out.print("H");
}
else if (currentflip == 1) {
System.out.print("T");
}
}
Via a single method:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
if (timesFlipped <= 0)
return;
Random randomNum = new Random();
boolean isHeads = false;
int sequence = 0;
for (int i = 0; i < timesFlipped; i++) {
boolean prevFlip = isHeads;
isHeads = randomNum.nextBoolean();
if (i > 0 && isHeads != prevFlip) {
System.out.print(sequence + " ");
sequence = 0;
}
sequence++;
System.out.print(isHeads ? "H" : "T");
}
System.out.println(sequence);
}

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 can I check if the user entered in an array is palindrome or not?

I need help guys I have been checking on google for similar question but I cant find the most suitable answer for this. Here is my output.
Enter 3 Elements
23
Is a palindrome
22
Is not a palindrome
11
Is not a palindrome
The program:
public static void main(String [] args)
{
int number = 0;
int reverse =0;
int numCopy = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter how many numbers you want to enter");
int num = scan.nextInt();
System.out.println("Enter "+num +" Elements");
numCopy = num;
int[] array = new int[num];
for(int i = 0; i < num; i++)
{
array[i] = scan.nextInt();
int digit = numCopy % 10;
numCopy = numCopy / 10;
reverse = (reverse * 10) +digit;
if(num == reverse)
{
System.out.println("Is a palindrome");
}
else
{
System.out.println("Is not a palindrome");
}
}
}
A Palindrome by definition is the same forwards and back so 11 would be and 22 would be. 23 would not etc.
Quick easy psudo code for checking if Palindrome as a STRING:
function isPalin(string str)
if(str.length() == 0) {
return true;
}
int end = str.length() - 1;
int start = 0;
while(start < end) {
if(str[start++] != str[end--]) {
return false;
}
}
return true;
If you have numbers just covert it to a string then use the function.
A palindrome, for example, we need to consider two difference case:
AA and ABA.
These two are all palindrome. So for integers, you need to confirm its length is even or odd. Then check from both sides: start, end.
This should get the correct result.
you should have your program like below:
public static void main(String[] args)
{
int number = 0;
int reverse =0;
int numCopy = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter how many numbers you want to enter");
int num = scan.nextInt();
System.out.println("Enter "+num +" Elements");
numCopy = num;
String[] array = new String[num];
for(int i = 0; i < num; i++)
{
array[i] = new Integer(scan.nextInt()).toString();
String rev="";
for(int k=array[i].length()-1;k>=0;k--){
rev +=array[i].charAt(k);
}
if(array[i].equals(rev))
{
System.out.println("Is a palindrome");
}
else
System.out.println("Is not a palindrome");
}
}

Categories

Resources