Breaking out of For Loop Java - java

I have this piece of code here:
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
if (input.nextInt() == 999){
break;
} else {
array[i] = input.nextInt();
}
}
I want to break out of the loop if the user enters 999 inside the array but so far no luck. I tried using break or return false but nothing works. Does anyone have a solution? Much thanks!

You are using input.nextInt(); twice.That is reading from console in if and else.
for (int i = 0 ; i < array.length; i++ ) {
int enteredNumber = input.nextInt();
if (enteredNumber == 999){
break;
} else {
array[i] = enteredNumber ;
}
}

You are reading twice inside your loop. So, if your if condition is falsy (user does not enter 999), then it will go into else block where you are reading a new input from user, which can possibly be 999.
Change your loop to:
for (int i = 0 ; i < array.length; i++ ) {
int read = input.nextInt();
if (read == 999) {
break;
}
array[i] = read;
}
Apart from that, you should also consider the case where user doesn't actually passes an integer, in which case, your code will blow. You can use Scanner#hasNextInt() method for that.
for (int i = 0 ; i < array.length; i++ ) {
while (!input.hasNextInt()) {
System.out.println("You must pass an integer");
input.next(); // Advance the scanner past the current line.
}
int read = input.nextInt();
if (read == 999) {
break;
}
array[i] = read;
}
Of course, that loop might run forever if user keeps on entering non-integer values. To overcome that, you can give user a maximum number of attemps. That I'll leave up to you to handle. (HINT: You will need a counter that goes from 0 to max. On each loop iteration, reset it).

The way you currently have it is that you're calling nextInt() multiple times within each iteration.
That means you'll lose data. Let's say you first enter 7. That's picked up in the if statement as "not 999" so it moves onto the else clause where you ask the user for yet another number (you've lost the 7).
In addition, you'll only break out of that loop if you enter 999 when it's executing the first call to nextInt(). If you enter 999 when it's executing the second call, it will just store it and keep going.
Try this instead:
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
if (next == 999)
break;
array[i] = next;
}

Try this thing in your for loop.
for (int i = 0 ; i < array.length; i++ ) {
int number = input.nextInt();
if (number == 999){
break;
}
System.out.println("aghsdgha" + number);
}
This is the simpler and cleaner way to check the input number.

Related

Working on a random challenge, but having a problem with

//Java nested loop, if the user input less than 1 and Great than 11 it must display error message. Implementing java nested for loops.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size: ");
int size = input.nextInt();
if (size < 1 && size > 11)
System.out.println("INVALID NUMBERS");
for (int rows = size; size > 0; rows++) {
for (int colums = size; colums < 11; colums++) {
System.out.print("#");
}
}
System.out.println();
}
}
Tags
if(size<1 && size>11)
size can not both be less than 1 AND greater than 11.
You'll need a logical OR here:
if(size<1 || size>11)
Not exactly sure what you mean, but to my understanding this is what you're looking for?
int size=input.nextInt();
if(size<1 || size>11) {
System.out.println("INVALID NUMBERS");
}
else{
for (int rows=size;size>0;rows++){
for(int colums=size;colums<11;colums++){
System.out.print("#");
}
}
}
First of all question is not very elaborative and does not mention what the end result should look like.
To my understanding, this code will result in infinite loop when size entered is greater than 0, because of the line:-
for (int rows = size; size > 0; rows++) , the loop will be infinite because the test condition is always greater than zero.

While-loop Restriction

I want to restrict the while Loop.
I don't want to use break;, instead I want to say that the loop must end after three times.
My while Loop:
while(!file.isFile()) { userInput = JOptionPane.showInputDialog("UserInput);
int i = 0;
while(!file.isFile() && i < 3) {
userInput = JOptionPane.showInputDialog("UserInput);
i++;
}
And I agree that for loop is better choice :)
Use a for loop instead :
for (int i = 0; i < 3 && !file.isFile(); i++) {
userInput = JOptionPane.showInputDialog("UserInput");
...
}
Consider refactoring to a for loop, introducing a counter variable in a tight scope:
for (int i = 0; i < 3 && !file.isFile(), ++i){
userInput = JOptionPane.showInputDialog("UserInput"/*ToDo - quotation inserted*/);
}
The for loop conditional check i < 3 && !file.isFile() is verified before the statement in the loop body is ran.
Then you need to make your while loop a for-loop like thing:
int counter = 0;
while (counter < 3 && !file.isFile()) { ...
counter++;
For the record: the code you are showing isn't really useful: you are "overriding" the input you get from the user; and: you are condition !file.isFile() ... will not change its value ... because there is no code that would do that. In other words: there is more to fix about your code than just the way you are looping. It simply seems weird to ask the user the same thing three times; to ignore what he says the first two times.
int i = 3;
while(!file.isFile() && i>0) {
userInput = JOptionPane.showInputDialog("UserInput");
i--;
}
int counter = 0;
while(!file.isFile() && counter < 3) {
userInput = JOptionPane.showInputDialog("UserInput);
counter++;
}
Replace 3 with the number of iterations you would like the loop to be limited to.
int count = 0;
while(!file.isFile() && count < 3 ) {
count++;
}

Checking for specific integers in an array

First post here so I'm hoping I don't screw up.
My task is to have a user enter an array of 10 integers and then input another integer separately and have the program either retrieve that number if it's in the array, or give an error if not.
I'm having trouble comparing the inputted integer with those in the array.
Here's part of my code, with the rest found below:
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt();
if(numbers.length==10){ //method doesnt work properly if you input over 10 integers, only if you input less
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
if(numbers[index] == compare){ //this is where the error is I believe
System.out.print(compare); //here too
}
http://pastebin.com/U5PdJgr6
Thank you in advance!
If you're using java-8, you can perform that easily using an IntStream
boolean contained = IntStream.of(inputtedNumbers)
.anyMatch(x -> x == numberToSearch);
Turn
if (numbers[index] == compare) {
System.out.print(compare);
}
Into
boolean found;
for (int number : numbers) {
found = number == compare;
if (found) break;
}
if (found) System.out.print(compare);
else throw new Exception("Number Not Found");
P.S. You don't need to check to make sure numbers.length is still 10. The length of an array is always final and can't change.
package integerarrayexceptions;
import java.util.Scanner;
import java.util.InputMismatchException;
public class IntegerArrayExceptions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numbers[] = new int[10];
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt(); //The loop only applies to this statement.
if(numbers.length==10){
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
for (int index2 = 0; index2 < numbers.length; index2++) {
if(numbers[index2] == compare){
System.out.print(compare);
}
}
}
}
catch (InputMismatchException MismatchException)
{
System.out.print("One or more values entered is not an integer.");
}
}
}
There's a loop missing after you entered the compare value:
for (index = 0; index < numbers.length; index++) {
if(numbers[index] == compare){
System.out.print(compare);
}
]
You try to use the variable "index" outside the "for" loop, where it does not exist...

Java Loops - Break? Continue?

I've read through a bunch of threads on using break and continue and I suspect the problem isn't necessarily my use of those, but the layout of my loops. In the following code, I am trying to iterate through the chars in a string that is input by the user to find any - symbols. If found, it will throw an error to the user that a negative number was found and exit. Otherwise, if it does not find a - symbol, it should print out all of the chars in the string.
I used break at the end of my first loop to find the - symbol, but it is not continuing on to the next loop. I tried continue as well but that didn't work. Loops are new to me so I may have this completely wrong, all I know is my first loop is working OK and will throw the error when it finds a - in the string.
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i = 0; i < strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-') {
System.out.println("Negative Digit Found - Exiting");
break;
}
}
for (int i = 0; i < strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c <= 9) {
System.out.println(c);
}
}
The break statement breaks you only from the first loop. In order to skip running the second loop in the event of finding a - character, you can use some boolean variable to indicate whether the second loop should run :
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
boolean isValid = true;
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
System.out.println("Negative Digit Found - Exiting");
isValid = false;
break;
}
}
if (isValid) {
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c <= '9'){
System.out.println(c);
}
}
}
If you replace the break with a return it will exit the whole method. It sounds like this is probably what you want.
'break;' will stop the loop that it is in from running, where 'continue;' will skip the current 'iteration' in the loop.
for(int x = 0; x < 10; x++)
{
if (x == 5)
break;
// other code
}
// more other code
This will exit the loop once x == 5, and not do the 6th through 10th iterations.
for(int x = 0; x < 10; x++)
{
if (x == 5)
break;
// other code
}
// more other code
This will do every iteration, besides the 6th iteration.
But if you want to skip the '// more other code', then you would need to use a 'return;', provided your code is in a function, and it will skip the rest of the function, which in this case is the '// more other code'.
Use the return statement instead of break if you dont want to execcute the second loop after the first one.
You don't say if the number should be an integer, so I'm assuming yes.
If so, instead of using loops, a better way of validating the input would be:
int num1;
try {
num1 = Integer.parseInt(strNum1);
catch (NumberFormatException e) {
//not a valid number, complain about it
}
if (num1<0) {
//negative number not allowed, complain about it
}
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
System.out.println("Negative Digit Found - Exiting");
break;
}
}
can be modified as
if(strNum1.charAt(0) != '-'){
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c <= 9){
System.out.println(c);
}
}
}
else {
//negative number found...
}
In This way, unnecessary for loop and break statements can be avoided
All answers are good, but if you want to repeat prompt until you get a valid value,
you will need another loop for that, using labels:
negative: while(true) {
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
System.out.println("Negative Digit Found - Exiting");
continue negative;
}
break negative;
}
}

Program Terminates Before Reaching Essential Code

A little background, I saw a question on here a while back about creating a program that asks how many people are in the room, and then you 'interview' each person on their age, assign them to an age group, and then print their age group and the amount of people in that age group. I decided to take a shot at it off of needing an idea for a practice program, unfortunately the code terminates before getting the first for statement and i'm not exactly sure why. I assume it would be a syntax error but I honestly have no idea, so any help is greatly appreciated.
import java.util.Scanner;
public class UnkownProjects {
public static void main(String[] args){
Scanner stringInput = new Scanner(System.in);
Scanner numInput = new Scanner(System.in);
System.out.println("How many people are in the room?");
int amountOfPeople = numInput.nextInt();
int[] totalPeople = new int[amountOfPeople];
System.out.println("Test");
for(int index = 0; index == totalPeople.length; index++){
System.out.println("Please enter an age for each person in the room:");
int ageOfPerson = numInput.nextInt();
ageOfPerson = totalPeople[index];
System.out.println("Test");
}
for(int index = 0; index == totalPeople.length; index++){
if(totalPeople[index] < 20 && totalPeople[index] > 0){
int[] underTwenty = null;
underTwenty[index] = totalPeople[index];
System.out.println("Test");
}
}
}
}
I also know the spacing is a bit off but I just copy/pasted and tried to make it look pretty for you all, so don't worry. Oh and the 'println' statements were just there to check and see where the program terminates.
Output:
How many people are in the room?
(A number you would've entered here)
Test
Ninja Edit:
Decided that I should come back to this post and place the finished code here for anyone who comes across this question and would like to take a look at the finished product.
import java.util.InputMismatchException;
import java.util.Scanner;
public class InterviewClass {
public static void main(String[] args){
try{
Scanner numInput = new Scanner(System.in);
System.out.println("How many people are in the room? (Ex: 5, 10, 24)");
int totalPeopleInRoom = numInput.nextInt();
int[] agesOfPeopleInRoom = new int[totalPeopleInRoom];
int youngPeople = 0, middleAged = 0, oldPeople = 0, deadPeople = 0;
System.out.println("Please enter an age for " + totalPeopleInRoom + " people (Ex: 17, 21, 45):");
for(int index = 0; index < agesOfPeopleInRoom.length; index++){
int tempAgePlaceHolder = numInput.nextInt();
agesOfPeopleInRoom[index] = tempAgePlaceHolder;
if((index + 1) == (totalPeopleInRoom/2)){
System.out.println("Half way there!");
}
}
System.out.println("Age Group\tAmount In Group");
for(int index = 0; index < agesOfPeopleInRoom.length; index++){
if(agesOfPeopleInRoom[index] < 30 && agesOfPeopleInRoom[index] > 0){
youngPeople = youngPeople + 1;
}
if(agesOfPeopleInRoom[index] < 60 && agesOfPeopleInRoom[index] > 30){
middleAged = middleAged + 1;
}
if(agesOfPeopleInRoom[index] < 115 && agesOfPeopleInRoom[index] > 60){
oldPeople = oldPeople + 1;
}
else if(agesOfPeopleInRoom[index] < 0 || agesOfPeopleInRoom[index] > 115){
deadPeople = deadPeople + 1;
}
}
System.out.println("Young People:\t" + youngPeople);
System.out.println("Middle Aged:\t" + middleAged);
System.out.println("Old People:\t" + oldPeople);
System.out.println("Dead People:\t" + deadPeople);
System.out.print("Total People:\t");
System.err.println(totalPeopleInRoom);
}catch(InputMismatchException inputException){
System.err.println("[ERROR] Wrong type of input used: " + inputException);
}
}
}
This is a bad for loop: for(int index = 0; index == totalPeople.length; index++)
Instead do: for(int index = 0; index < totalPeople.length; index++)
Let's break the for loop down:
The first part of the loop, int index = 0 is the initial condition. It tells the loop what the index should be set to when the loop starts.
The 2nd item in the for loop, in your loop you have index == totalPeople.length, is the condition statement that tells the for loop whether to keep looping if true or to stop looping if false. Your statement will be false when the loop tries to begin, and so the loop will never begin. So this is where your problem is. Instead you want to tell it to continue looping as long as the index is less than the length of the array, or in Java, index < totalPeople.length.
The 3rd item in the loop, here index++, tells the loop what to do with the index at the completion of each loop. Here you're telling it to increase by one, which is good.
The for loop condition must be true for it to iterate; it breaks out when it's false. In your case, it's false right away, so it never executes.
Instead of
for(int index = 0; index == totalPeople.length; index++){
try
for(int index = 0; index < totalPeople.length; index++){
And similarly for the other for loop.
In the Java tutorial on for loops, it states this:
When the termination expression evaluates to false, the loop terminates.
for(int index = 0; index == totalPeople.length; index++){
The second part in the parentheses is not a stopping condition, it is a check to continue. Use:
for(int index = 0; index < totalPeople.length; index++){
for(int index = 0; index == totalPeople.length; index++) should be
for(int index = 0; index < totalPeople.length; index++)
otherwise the boolean condition is evaluated to false and hence the loop doesn't execute
You should read this.
The general form of the for statement can be expressed as follows:
for (initialization; termination;
increment) {
statement(s) }
When using this version of the for statement, keep in mind that:
1. The initialization expression initializes the loop; it's executed once, as the loop begins.
2. When the termination expression evaluates to false, the loop terminates.
3. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment
or decrement a value.
Your for loops are saying
Continue doing this code while index is equal to the arrays length
What you mean to say is continue doing this code while index is less than the arrays length

Categories