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.
Related
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.
Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}
I have recently got into java and I need help with a basic program:
public static void main(String[] args) {
Random gen = new Random();
int roll = gen.nextInt(6) + 1;
int[] array = new int[20];
// Replacing all the numbers of the array to random ones
for (int i=0; i<20; i++){
roll = gen.nextInt(6) + 1;
array[i] = roll;
}
// Bracketing all repeating numbers
for (int i=0; i<19; i++){
if (array[i] == array[i++]){
System.out.print("(");
}
System.out.print(array[i]);
if (array[i] == array[i--]){
System.out.print(")");
}
}
}
}
All this code does is take the random die roll and bracket all the numbers that are the same:
13(66)5(2222)(66)71
However, all it does with this code is bracket all the numbers instead of the ones that are the same:
(1)(3)(6)(6)(5)(2)(2)(2)(2)(6)(6)(7)(1)
What am I doing wrong?
Your code is only checking numbers immediately prior to and immediately after the indexed number in array[i].
You could create a second loop inside the first to iterate over all of the numbers in the array to check for a match.
If you do so, you'll need to keep track of the matching numbers with some other mechanism. Immediately printing out a parenthesis as you're currently doing will be problematic with an inner loop.
A simple method to consider is another array that keeps track of whether there was a match or not.
If you are recently got into Java try to avoid i++ and ++i within square brackets. You can solve this problem with a boolean variable that indicates if there is already a bracket open.
After generate random numbers, try this:
boolean openBracket=false;
for (int i=0; i<array.length-1; i++){
if (array[i] == array[i+1] && !openBracket){
System.out.print("(");
openBracket=true;
}
System.out.print(array[i]);
if(array[i] != array[i+1] && openBracket){
System.out.print(")");
openBracket=false;
}
}
I am trying to create a bubble sort program for a small presentation that I am doing. The code runs fine but the largest integer in my array is never displayed. Output for the program as it stands is:
1
3
4
6
7
11
The 12 is missing!
Here is my code, excuse the comments - some of them might even be wrong.
public class BubbleSort {
public static void main(String[] args) {
int number []={6,3,1,7,4,12,11};
// 0,1,2,3,4
//For temporarily storing a value that has to be swapped
int temp;
//Keeps the loop running until there is nothing left to sort.
boolean fixed=false;
while (fixed==false) {
fixed=true;
//If this IF statement is accessed it means something still has to be
//swapped, so at the end of the statement fixed is reverted to false
//again, so it can continue the loop.
for(int i=0; i<number.length-1 ; i++){
//This makes i start at 0 the first time it is run,
//this is due to the array starting at 0, too.
if(number[i] > number[i+1]) {
//If 8 > 5
temp = number[i+1];
//Store 5 in temporary variable
number[i+1]=number[i];
//Swap array 1 with array 0/
number[i]=temp;
fixed=false;
}
}
}
for(int i=0; i<number.length-1 ; i++){
System.out.println(number[i]);
}
}
}
for(int i=0; i<number.length-1; i++){
System.out.println(number[i]);
}
Should be
// no '-1'
// V
for(int i = 0; i < number.length; i++) {
System.out.println(number[i]);
}
Why?
Let's see what happens if there are 5 elements in the array, then they are indexed as follows:
0, 1, 2, 3, 4
If we use i < 5-1 (or i < 4), once i becomes 4, before the next iteration of the loop runs, it will stop, skipping the last index.
In case the above doesn't explain it, note the order in which things happen in a for-loop:
First the initialization occurs
Then the following is repeated until the condition is false:
The condition is checked
A loop iteration is run
The increment happens
The most applicable part here is that a loop iteration will never run if the condition is false.
The error is in your last loop showing numbers.
Your loop does not reach the last element because it stops in number.length-2. You have to add one more execution to your loop.
Try:
for(int i=0; i<number.length ; i++){
System.out.println(number[i]);
}
or
for(int i=0; i<=number.length-1 ; i++){
System.out.println(number[i]);
}
for(int i=0; i<number.length-1 ; i++){
System.out.println(number[i]);
When you are printing your array, remove -1 only write number.length.
you are using wrong ending loop condition it should be
for(int i=0;i<number.length;i++)
as array index starts from 0.
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