Jagged Array & Nested For Loop in Java - java

I have what I thought was a very basic code example, but I can't figure out why the code never completes. It seems to stay stuck in a loop. This very simple code is supposed to declare and initialize a jagged array with the first row having 4 columns and the second row having 3 columns. The code asks the user for 7 integers and prints out the result to the screen. All of that works, but it doesn't break out of the loop unless I manually break out of it. If the manual break is used, the correct output is not achieved.
public class TestCode {
public static void main(String[] args) {
//Create new scanner object
Scanner userInput = new Scanner(System.in);
//Declare two dimentional array
int[][] num2d = new int[4][3];
//Declare variables
int i;
int j;
//Print to screen asking for user input
System.out.print("Enter seven numbers: ");
//Loop through array and print the result
for (i = 0; i < num2d.length; i++) {
for (j = 0; j < num2d[i].length; j++) {
num2d[i][j] = userInput.nextInt();
System.out.println(num2d[i][j]);
//break;
}
}
}
}
When I run this code with the break commented out, I get this result, but I have to manually stop it from running.
run:
Enter seven numbers: 1 2 3 4 1 2 3
1
2
3
4
1
2
3
When I put the break in, this is what I get.
run:
Enter seven numbers: 1 2 3 4 1 2 3
1
2
3
4
BUILD SUCCESSFUL (total time: 4 seconds)
What's going on? Why can I get the correct result with the "build successful" message without using the break?

Your code doesn't loop forever: it loops 12 times, because you have declared a 4x3 array - i.e. an array sized 4 where each of the elements is an array of 3 ints.
Instead, I think you want something like this:
int[][] num2d = {new int[4], new int[3]};

your loop runs on the "columns" of the 2d array which is 4 times and for each "column" it runs on its length which is 3. 4 times 3 is 12, and you only enter 7 numbers. the console is always waiting your input.

Related

Java: Sudoku Array not Filling

I've been trying to build a sudoku, starting with a 9x9 array that ensures no numbers in a given column nor row are the same (ie sudoku without the 3x3 boxes). I've set my code as seen below, but I keep running into a runtime error that I think stems from the do-while statement where the array won't finish filling. However, if I add 10 to the new randomized number (within the do-while statement) the array will finish filling. I've also created a lengthy "check" method that checks whether the current cell is the same as any of the others in that column or row and returns true only if the number is original. I have not included that method for simplicity. Is there something I'm missing?
import java.util.Random;
public class S9x9 {
public static void main (String[] args){
int [][] nines = new int [9][9];
Random rand = new Random();
for (int i = 0; i < nines.length; i++) {
for (int j = 0; j < nines.length; j++) {
nines[i][j] = rand.nextInt(9) + 1;
if (!(check(nines,i,j))) {
do
nines[i][j] = rand.nextInt(9) + 1;
while (!(check(nines, i, j)));
}
System.out.print(nines[i][j] + " ");
}
System.out.print("\n");
}
}
}
Your algorithm will end up in a deadlock quite soon. Suppose you have this:
5 2 3 1 8 6 9 7 4
4 3 1 6 9 2 5 8 7
2 1 6 7 3 5 8 9
There is no valid number to put in the last place. I suggest you change your algorithm to weed out all invalid numbers before using random generation. If there are zero candidates, you have to backtrack.
The problem is that you can deadlock yourself when you don't use any backtrack algorithm in finding a sudoku solution. Assume your two for() loops have already found the following grid:
xxx xxx x1x
xxx xxx x2x
xxx xxx x3x
xxx xxx x4x
567 891 2?.
... ... ...
... ... ...
... ... ...
... ... ...
The place with the ? marker, where your current i and j values are, cannot have any valid number since all the digits are already "used". Check other questions like How to solve Sudoku by backtracking and recursion? on how backtrack works for sudokus.

ArrayDeque<>(int capacity) - what's the difference between Scanner.nextInt() == 4 and (int) 4?

The task is to write a program that reads numbers and stores them to a deque.
Sample Input is: 4 1 2 3 4
Sample Output: 4 2 1 3
An even number should be added as the first element, an odd number - as the last. After, the program must output all elements from the first to the last.
Here is my piece of code:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Deque<Integer> deque = new ArrayDeque<>(sc.nextInt());
while (sc.hasNext()) {
int nextInt = sc.nextInt();
if (nextInt % 2 == 0) {
deque.addFirst(nextInt);
} else deque.addLast(nextInt);
}
for (int elt : deque) {
System.out.println(elt);
}
}
}
Sample Output: 4 2 1 3
It works fine, it's correct. BUT!
Let's rewrite
Deque<Integer> deque = new ArrayDeque<>(sc.nextInt())
as
Deque<Integer> deque = new ArrayDeque<>(4)
For this one, sample output is: 4 2 4 1 3 .
i.e. it's incorrect.
Why inputing the same capacity different way gives such different results?
This does not have much to do with how you pass the capacity. It has more to do with how many times Scanner.nextInt is called inside the loop.
Because there are always 5 inputs and the first input is always the size, if you do
Deque<Integer> deque = new ArrayDeque<>(sc.nextInt())
sc.nextInt will be called 5 times in total (because you have 5 inputs), 4 times inside the loop and 1 time in the line above, and so 4 numbers will be added to the Deque. This is correct.
If you did this however:
Deque<Integer> deque = new ArrayDeque<>(4)
sc.nextInt will be called 5 times inside the loop, and so 5 numbers will be added to the Deque. But the first number actually shouldn't be added to the Deque, because it is the size, hence producing the wrong output.
ArrayDeque is resizable so you don't actually need to specify the size and your code will still work.
You can ignore the first input by calling sc.nextInt before the loop:
sc.nextInt();
while (sc.hasNextInt()) {
...

What is wrong with my code/ what can I do to solve this assignment?

In this lab, you will be creating a program that merges two arrays of positive (greater than 0) integers. Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
After the two arrays have been input, your program must check to make sure the elements of each array have been entered in order. If an out of order element is found, print the message “ERROR: Array not in correct order”.
Your task is to merge the two input arrays into a new array, with all elements in order, lowest to highest. Print out each of the original arrays entered, followed by the merged array.
Please note that your program must output the arrays with exactly one space between each of the numbers.
Sample Run 1:
Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit
3
3
5
6
8
9
-1
Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit
3
4
5
6
-5
First Array:
3 3 5 6 8 9
Second Array:
3 4 5 6
Merged Array:
3 3 3 4 5 5 6 6 8 9
My code was:
import java.util.Scanner;
class Main{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int one1=0;
int two1=0;
int a = 0;
int b = 0;
int flag = 0;
int[]one=new int[10000];
int[]two=new int[10000];
System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
while (a==0){
int first = scan.nextInt();
if (first<=0) a++;
else{
one[one1]=first;
one1++;
}
}
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
while (b==0){
int second = scan.nextInt();
if (second<=0) b++;
else{
two[two1]=second;
two1++;
}
}
System.out.println("First Array:");
for (int i = 0 ; i < one1 ; i++){
System.out.print(one[i]+" ");
}
for (int i = 0 ; i < one.length-1 ; i++){
if (one[i]>one[i+1]) flag++;
}
System.out.println("Second Array:");
for (int i = 0 ; i < two1 ; i++){
System.out.print(two[i]+" ");
}
for (int i = 0 ; i < two.length-1 ; i++){
if (two[i]>two[i+1]) flag++;
}
int[]combo = new int[one.length+two.length];
for (int i = 0 ; i < combo.length-1 ; i+=2){
combo[i]=one[i];
combo[i+1]=two[i];
}
if (flag>0) System.out.println("ERROR: Array not in correct order");
else{
for (int i = 0 ; i < combo.length; i++){
System.out.print(combo[i]+" ");
}
}
}
}
This code keeps giving me runtime error- what am I doing wrong?
I am sorry, your merge algortithm is all wrong. You create an array combo of length one.length + two.length, that is, 20000 (I think one1 + two1 should suffice). Then you try to fill the new array by looping through it two elements at a time:
for (int i = 0; i < combo.length - 1; i += 2) {
So i is 0, 2, 4 etc. through 19998 (the last even number before 20000). Except when it gets 10000, you try to pick out one[i], that is one[10000], which is outside the one array. This gives the ArrayIndexOutOfBoundsException.
How I found out? The stack trace gives a line number. The line it mentions is
combo[i] = one[i];
It also mentioned the number 10000, so I knew this was the value of i at this point.
I think that what you were trying to do, was fill elements 0 from one and two into elements 0 and 1 of combo, I think it works so far. Then you wanted to fill element 1 from each array into elements 2 and 3; but since you have added 2 to i, you fill in element 2 from each source array and never use element 1 from them. Or any element from odd indices.
Before you mend that problem, allow me to mention one more thing. I think with your logic, input arrays 2 5 and 11 30 will come out as 2 11 5 30. This doesn’t fulfil “with all elements in order, lowest to highest”. So I think you should think your algorithm over.
the code exist many logic error,
as for Runtime Error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10000 at..
the problem is here:
for (int i = 0 ; i < combo.length-1 ; i+=2){
combo[i]=one[i];
combo[i+1]=two[i];
}
the i from 0 to 19999 and the index of a,b is from 0 to 9999, and the code exist other simple logic problem. Please check it again.
Homework questions are very frowned upon, but still, Java is a relatively easy language. If your program is throwing a RuntimeException, you just have to read what the problem is.
In this case, it seems a loop iterates more times than it should, and you are accessing other memory space. Give it a few reads with the info provided by the error trace in mind.

for loop decrementing by 2 to 0 and summing up the values that were generated before getting to 0

I am trying to find a way to count down from the int that is input by a user and then add each second value as i count down to 0
for example.
{user inputs 10
program counts down 8,6,4,2,0
then add 10 + 8 + 6 + 4 +2 +0= 30
}
how can I do this using a nested for loop
so far I have only been able to take user input, and count down by 2 each time. I get to 0 but have no way of adding every second value.
My code:
so far, it just counts to 0
public class Week5b {
static Scanner userVal = new Scanner (System.in);
public static void main(String[] args) {
//printTable();
reverseAddSkip();
public static void reverseAddSkip(){
System.out.println("Please enter an integer");
for (int i = userVal.nextInt(); i >=0; i-=2){
System.out.println(i) ;
}/* this creates a loop where the variable i is equal to user input;
the condition for the loop to continue is whether the input is larger or equal to 0; the update part of the loop takes 2 away each time, as if it were -- (which takes away one each time) */
}
}
How would I write that out mathematically?
Adding the sum of i-=2 to the original value of i.
You type 11 , it counts 9 7 5 3 1 , then adds 11 9 7 5 3 1. and give you the sum.
don't know how to sum every 2 numbers decrementing by 2, from a user value.
You input put 50, it counts down by 2 to 0
you put 51 it counts down by 2 to 0
but I haven't found away to sum all then numbers that were generated before getting to 0
:/
NoGlitching,
You need to look at the control flow of your program - which is to say, the path it takes upon execution.
You should also look at using more variables.
I'll give you the pseudocode I would use, because I think it's important for you to be able to write the code yourself:
Make a new integer called OriginalInput.
Make a new integer called RunningTotal.
Set RunningTotal to 0.
Store the user's input in OriginalInput.
Loop through OriginalInput.
Print the current OriginalInput.
Add the current OriginalInput to RunningTotal.
When the loop is finished:
Print RunningTotal.
I hope this helps.
EDIT:
// First you equalize j with i
input = userVal.nextInt();
j = i; // Put the user input in j first. for instance 11.
for (int i = input; i >=0; i-=2)
{
if (i >= 0) // If i is not below 0
{
j += i; // Add to j what i has now (everytime -2)
// put a system out print here to show what was added
// J starts as 11 and adds 9,7,5,3,1 then nothing. So it ends as 36.
}
}
// outside the For loop after it ends but INSIDE your method, you get the sum from the variable j!

For loop stopping prematurely

I'm trying to solve problem #299 - Train Swapping in website UVa Online judge. The code I have works fine for independent test cases. However, when I use the sample input they provide, my program omits one of the test cases, the last one to be more specific:
Here is my code:
import java.util.Scanner;
public class Tester {
void problem(){
Scanner imput = new Scanner(System.in);
int numT =imput.nextInt();
int numL, aux, swaps=0;
int [] train = new int [50];
for (int i =0; i<numT; i++) {
numL = imput.nextInt();
for (int m =0; m< numL; m++) {
train[m]=imput.nextInt();
}
for (int j=0; j<numL; j++) {
if (train[j]>train[j+1]) {
for (int k =j; k<numL-1;k++) {
aux = train[k];
train[k]=train[k+1];
train[k+1]=aux;
swaps++;
}
}
}
System.out.println("Optimal train swapping takes "+swaps+" swaps.");
swaps = 0;
}
}
}
Example Input:
3
3
1 3 2
4
4 3 2 1
2
2 1
Example Output:
Optimal train swapping takes 1 swaps.
Optimal train swapping takes 6 swaps.
Optimal train swapping takes 1 swaps.
My code prints until the second solution, then for some reason stops. I've tried to debug it and check what's going on step by step but it has driven me to a migraine point. Any insight is highly appreciated.
...
To be more precise it stops at the second for loop the third time around without taking anything into the array...and I don't know why!
Another thing I found out is that to solve this problem the number of swaps for the case of the middle is 6, therefore the bubble sort wont be useful here, since it makes over 10 swaps thus yielding a wrong output, this is a separate issue to the original one I presented however. I still haven't figure out why it stops the third time around the loop where I assign values to the array for the third time.
The input consists of:
first line is number of cases.
this line enters the length of a train ex: 4
this line enters the number of the wagons ex: 2 4 3 1
the next following lines correspond to the following test cases whose structure is the same as the example.
They ask you to arrange the train and tell the number of swaps made to make the train in order.

Categories