Program Terminates Before Reaching Essential Code - java

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

Related

repeat number sequence on java

So recently a had an exam to make this simple program on java:
You enter a number, then the program needs to repeat a sequence based on the amount you entered, like this: if it was number 3 it should show 01-0011-000111, as you can see the numbers repeat in the same row, if it would be number 5 it should show: 01-0011-000111-00001111-0000011111 without the "-" symbol, I'm just putting it for you to understand better.The only thing I could do was this:
Scanner lea = new Scanner(System.in);
int number;
int counter = 1;
System.out.println("Enter a number");
number = lea.nextInt();
while(counter<=number){
System.out.print("0");System.out.print("1");
counter = counter + 1;
}
thanks in advance!
I have a feeling this is inefficient, but this is my idea:
You'd need to use 1 loop with 2 additional loops inside it. The outside loop will iterate N times (the amount the user specified), and the 2 loops inside will iterate the number of current iterations the outside loop has. One of them is for printing 0s and the other for printing 1s.
In code, it would look like so:
for(int i = 0; i < N; i++){
for(int j = 0; j <= i; j++){
System.out.print(0);
}
for(int j = 0; j <= i; j++){
System.out.print(1);
}
if(i + 1 != N) System.out.print(" ");
}
I'd rather use 1 for loop for this case with a formatted string using String.repeat
for (int i =0; i <= N; i++)
System.out.print(String.format("%s%s ","0".repeat(i),"1".repeat(i)));

Using return vs While(condition) methods To Break Loops

I'm doing a little google interview question. Find the pair of numbers in a loop that add up to the number given. I found the numbers 2 and 6 that make up 8 so I say match = true so that the while loop stops, however it still proceeds until it finds the second which is 6 and 2 however, those numbers I have already found just the other way around and I had expected my loop to break as my if statement states if there is any 2 numbers that give the sum, match = true therefore terminating the loop, I guess I am wrong though.
However, if I get rid of the while statement and just return; once a match is found it breaks without looking for the second match (which I want it to).
Why is this happening, the logic of both seems the exact same to me.
Using the while(condition) Method
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
boolean match = false;
int sumNeeded = 8;
while(!match){
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j >= 0; j --){
if(list[i] != list[j]){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
match = true;
}
}
}
}
}
}
}
Using return
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
int sumNeeded = 8;
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j >= 0; j --){
if(list[i] != list[j]){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
return;
}
}
}
}
}
}
In your while-loop implementation, if the array doesn't have the desired pair at all it would result in an infinite loop. There is no need for the while statement in your solution.
After you enter into the while loop, you look for all the possible pairs in the array and then check for their sum. If it equals the desired sum, you make the boolean variable match as true.
But, until the nested for loop is completely executed (i.e., all the possible pairs are checked) we do not check for the while condition. The entire nested for loop is executed in one iteration of the while loop. Then, the while loop condition is checked again.
As by the end of the first iteration of the while loop all the possible pairs are accounted for, there is no need for a while loop.
Moreover, there are other logical errors in your implementation. The correct brute-force implementation is as follows:
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
boolean match = false;
int sumNeeded = 8;
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j > i; j --){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
return;
}
}
}
}
}
The inner-for loop is modified to reduce the double-counting of the unordered pairs. Whenever a match is found and printed, we exit the function.
You may also add a break statement inside the while loop in your initial implementation.
if(match == true) {
break;
}
The while condition continues to execute the first and second for-loop until it's finished where as with return it stops execution entirely from the first and second loop.
To fix the while loop you could use a label and then break from that.
firstLoop:
for(int i = 0; i < list.length; i ++) {
match = true;
break firstLoop;

nested for loops integers missing from array

Beginner here. I'm having problems running this series of for loops to find which integers are missing from an array.
public class FunWithArrays{
public static void main(String[] args){
String nString = args[0];
int n = Integer.parseInt(nString);
int inputArray [] = {1,2,4};
System.out.println(" The missing numbers are " );
findMissingNum(n, inputArray);
}
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= inputArray.length; i++){
int count = 0;
for( int j = 0; j < n; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
}
I get the answer I want, namely 3, however it doesn't print but rather shows up in a runtime error:
java.lang.ArrayIndexOutOfBoundsException: 3
at FunWithArrays.findMissingNum(FunWithArrays.java:17)
at FunWithArrays.main(FunWithArrays.java:9)
the method should take an input n from the user (when the program is run) as the largest value of the array and print all the ones missing
The logic is the outer for loop should traverse the array for numbers 1-n, and the inner loop should add to the count variable each time it finds a certain number. At the end of iteration it should print any numbers with a final "count" of 0. THIS IS LITERALLY DRIVING ME CRAZY!!! thanks in advance :)
First of all, you should traverse from 0 to (inputArray.length-1) index of inputArray. This will get rid of the ArrayIndexOutOfBoundsException, because java array indexing starts from 0 not 1.
And for inner loop, run from 0 to n, since n is the max number.
And Thirdly, it should be inputArray[i] == j, not inputArray[j] == i, same for printing the value. In you case I believe you have n>=4, so it was trying to access inputArray[3] via inputArray[j] call. That's why you are getting this out of bound error.
I think your code means like this: nest loop always run through inner loop first before run the outer loop.
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= n; i++){
int count = 0;
for( int j = 0; j < inputArray.length; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
I will just use a while loop instead:
int num =1;
while(num<=n){
for(int i = 0;i<inputArray.length;i++){
if(inputArray[i]!=num){
System.out.println(num);
}
}
num++;
}
The i incrementing to <= ipnutArray.length is not causing the error because i is never used as the index. What is causing the error is when n > length.
Also, you should not be checking n elements starting from the beginning because n is the max value, not the number of elements.

Array Index out of bound for loop

import java.util.Scanner;
public class Taxi {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int groups = input.nextInt();
int counter=0;
int[] pass = new int[groups];
for(int i=0; i<groups; i++){
pass[i] = input.nextInt();
}
for(int i=0; i<groups; i++){
if(pass[i]==4)
counter++;
else if(pass[i]+pass[i+1]<=4){
counter++;
i++;
}
else
counter++;
}
System.out.println(counter);
}
}
keep on receiving error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Taxi.main(Taxi.java:21)
please help
This line appears to be causing the exception:
else if(pass[i]+pass[i+1]<=4){
You're limiting i to be less than groups, which is the size of the array, but then you deliberately run off the end by using i+1.
Check if i is less than one less than groups first.
else if ( (i < groups - 1) && (pass[i]+pass[i+1]<=4)){
else if(pass[i]+pass[i+1]<=4) line is your killer definitely.
the reason is you are using for loop with i < groups
for(int i=0; i<groups; i++)
so i+1 goes to equals to groups for the last iteration.
say for example , it the groups size is 5 then for loop becomes
for(int i=0;i<5;i++)
we can have group[0] ... groups[4] max
and groups[5] causes array index out of bound exception.
if we check for loop like above then when i goes to 4 then it satisfies for loop check as 4<5 and enters for loop but there you are doing pass[i] -> ok but pass[i+1] will become like pass[5] which definitely causes array index out of bound exception
so check for loop like below
for(int i=0; i<groups-1; i++)
it will work now even for the last element.

Breaking out of For Loop 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.

Categories