I'm trying to do a certain project and there is this part in which I want to loop in a two-dimensional (2D) array and if the certain value of i and j then do something.
To be more specific my 2D array is defined for files and users (the attached photo might explain well); I want, for example, when i = 0 and j = 0 equals 1 then print out that user 1 can write in file. I was able to iterate over the array and find the indexes where 1's occur in the array with the following code:
my 2d array defined
public class Test {
public int counteri = 0;
public int counterj = 0;
public void readpermission(int[][] array) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 6; j++) {
if (array[i][j] == 1) {
counterj = j;
counteri = i;
System.out.println("found 1's at index =" + counteri + " " + counterj);
}
}
}
}
}
found 1's at index =0 0,
found 1's at index =0 1
found 1's at index =0 4
found 1's at index =1 1
found 1's at index =1 2
found 1's at index =1 3
found 1's at index =1 4
found 1's at index =1 5
When the first value is 0 0, I want an output that user 1 can write in file 1 and when the output is 0 1 I want an output stating that user 1 can read in file 1...and so on.
Given your last comment:
if(array[i=0][j=0]==1)
could be
if (i==0 && j==0 && array[i][j] == 1)
But the point is: that is really basic java syntax; and you should not need to come here and ask about that. Instead: you study tutorials and education materials that tells you how to do work with java syntax, for example here.
But please note: the whole thing that you are describing doesn't make too much sense. You are using int values to model permissions. That is not a good idea. Instead: you could create your own Permission class; or at least: use an enum instead of int values. Assuming that an int with value 1 ... means "write access" is simply a very naive and actually not-at-all intuitive model.
Related
This is my first time using stack overflow, so I'm so sorry if this is formatted incorrectly in any way. For a comp sci project, I have to do some different things to a 40-item Array List of random numbers.
The task I'm struggling with is this:
Count the longest run of the same number. A run continues only when consecutive numbers
have the same value. The repeated number and the length of the run is then printed. (Ex: Longest run is of number: 3, length is: 5.)
If there is more than one run of maximum length, mark the last one. Print the array with the longest run marked in the following fashion:
1 1 1 6 5 4 6 3 2 3 2 (3 3 3 3 3) 1 5 6 3 4 4 4
I genuinely have no idea how to approach this problem. Even just some pseudocode could be helpful; I know that these should probably be 2 different 'for' loops, one that detects the run and the other that prints it. I have some code from a friend who completed this using Arrays instead of ArrayLists:
public String longestRun()
{
int maxRun=1;
int currentLen = 1;
int repeated = x[0];
for (int i =1; i< 40-1; i++)
{
if (x[i] == x[i+1])
currentLen++;
else
{
if (currentLen >= maxRun)
{
maxRun = currentLen;
repeated = x[i-1];
startRun = i-maxRun;
endRun = i-1;
}
currentLen = 1;
}
}
return "The longest run is " + maxRun + " and the repeated number is " + repeated ;
}
public String printParenth()
{
for(int i = 0; i<40; i++)
{
if(i != startRun+1 && i != endRun+1)
System.out.print(x[i]);
else if(i == startRun+1)
System.out.print("(" + x[i]);
else
System.out.print(x[i] + ")");
}
return "";
}
I know how to create the ArrayList, convert to string & print, etc, it's just this one task that I don't understand. I assume this should be easier with an ArrayList, considering the increased number and utility of ArrayList methods. Thanks so much in advance, I really appreciate it!
Put your numbers in a list or an array.
Set max to 1 (you will always have at least 1 number).
initialize count to 1.
initialize the variable most to the first number in the array
also set the variable last to the first number in the array.
Now iterate thru the list starting with the second number.
If the current number is the same as last, increment count.
then see if count > max.
if it is
set max = count.
set most = last
if it isn't
set count = 1
set last = current number
continue in this fashion until all numbers have been checked.
At the end most will contain the number that was repeated and max will contain the length of the repetition.
I have debugged this code and it appears to run a for loop even though the termination condition is met.
This program takes two types of input:
Line 1 - How many data points there are following (N)
Lines 2 to N - The data points
The program should then print the smallest difference between all of the data points.
So, for instance, a sample input would be (on separate lines): 3 5 8 9
There are 3 data points (5 8 9), and the smallest difference is between 8 and 9, so the program should return 1.
I am trying to build the program in a way in which the data points are populated into an array at the same time as the comparisons are made. Obviously I could separate those concerns, but I am experimenting. Here it is:
package com.m3c.vks.test;
import java.util.*;
import java.io.*;
import java.math.*;
class Solution {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt(); //How many data points there will be
int strengthArray[] = new int[N]; //Initialise the array to be of length = N, the first input line
int tempStrengthDifference=99999; //junk difference set arbitrarily high - bad practice I know
int lowestStrengthDifference=99999;
for (int i = 0; i < N; i++) //Go through all elements of array
{
strengthArray[i] = in.nextInt(); //read a value for the ith element
System.out.println("i: " + i); //test
if (i > 0) //do not execute the next for loop if i = 0 as cannot evaluate sA[-1]
{
for (int j = i - 1; j < 1; j--) // **this is line 20** from wherever the array has populated up to, work backwards to compare the numbers which have been fed in thus far
{
System.out.println("j: " + j); //test
tempStrengthDifference = Math.abs(strengthArray[i] - strengthArray[j]); //finding the difference between two values
if (tempStrengthDifference < lowestStrengthDifference) //store the lowest found thus far in lowestSD
{
lowestStrengthDifference = tempStrengthDifference;
}
}
}
}
System.out.println(lowestStrengthDifference);
}
}
Everything is fine up until when i = 1 on line 20. At this point, j is set to i - 1 = 0 and the difference is found. However, when the for loop comes back around again, the termination condition of j < 1 is not met, and instead the loop continues to set j = -1, at which point it throws an out of bounds error as it clearly cannot evaluate strengthArray[-1]
Any ideas? Thanks
Have a look at your loop: for (int j = i - 1; j < 1; j--)
You start with j = 0 when i == 1 and thus j < 1 is ok.
The next iteration has j = -1 (0-1) and hence you get the problem.
Do you mean to use j >= 0 as your loop condition instead? Note that the second parameter is not a termination condition but a continuation condition, i.e. as long as that condition is met the loop will execute.
The reason behind your failure is the inner loop variable change.
When i=1, j=0 and after executing the loop once, J is decremented, and thus j becomes - 1. The condition j<1 is satisfied since you have written j--, change it to j++ and you should be fine.
I don't know how to address the question properly to even google it so far.
In a nested loop such as this
for (int i=0;i>0;i++)
{
for(int k=0;k<0;k++)
{
}
}
What kind of applications would there be if we use k
I have this question because I wanted to make a loop which iterates like star printing with * char printing left triangle but it iterates on a 2 dimensional matrix as the cursor moves it iterates on the array items such as this
a[0][0]
a[1][0], a[1][1]
a[2][0], a[2][1], a[2][2]
a[3][0], a[3][1], a[3][2], a[3][3]
I want to figure out a for loop or something to be able to iterate the array such as this. What do you suggest?
You must change the first for condition, because when i = 0 the condition i > 0 is false, so it never enters the loop.
Note that when you go line be line, the k must iterate in this pattern: [0, 01, 012, 0123] while i in [0, 1, 2, 3]. In other words, k must iterate until it reaches the value of i, so the condition of the nested for must be k < i + 1.
for (int i = 0; i < 4; i++) {
for (int k = 0; k < i + 1; k++) {
// Here you should access to the array
// array[i][k]
System.out.print(i + " " + k + " - "); // [DEBUG]
}
System.out.println(); // [DEBUG]
}
Output: Just to see indexes
0 0 -
1 0 - 1 1 -
2 0 - 2 1 - 2 2 -
3 0 - 3 1 - 3 2 - 3 3 -
It looks like what you want is something like
for (int i = 0; i < SOME_LIMIT; ++i) {
for (int k = 0; k <= i; ++k) {
do_something_with (a[i][k]);
}
}
It looks like you've already done the hard part -- designing the basic premise of the application and writing down on paper what you'd like to do.
Now all you do is take what you've written down and translate it in to code.
I'll give you one hint. On the inside loop, for(int k=0;k<0;k++), thibnk about how you would change this in order to achieve the behavior you're looking for.
Keep at it, you'll get there. The hard part is already done.
I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.
package hw3;
public class Main {
public static void main(String[] args) {
final int NumberOfElements = 1000;
int[] num = new int[NumberOfElements];
int var = 0;
//create input
java.util.Scanner input = new java.util.Scanner(System.in);
for (int i = 0; i < NumberOfElements; i++) {
System.out.print("Enter any positive number or enter 0 to stop: ");
num[i] = input.nextInt();
var++;
if (num[i] == 0)
break;
}
Arrays.sort( num, 0, var);
int i;
for (i = 0; i < var; i++) {
System.out.print(" " + num[i]);
}
}
}
Write a Java program reading a sequence of positive integers entered one per line. The program stops reading when integer ‘0’ is entered. The program will sort and output them into an ascending numerical order.For example: 5
1
7
12
36
8
0
Output: 1 5 7 8 12 36
Try to understand the problem: there are three steps.
Step 1: Get the input from the user. Continue getting input till the user enters 0
Step 2: Sort
Step 3: Print out the results
Step 1: Your for loop is almost correct.
But the for loop should end immediately after you have got the input.
In the following code,
num[i] = input.nextInt();
var++;
if (num[i] == 0)
break;
you are adding the user input to the array and then checking whether it is 0. This means that the 0 will also be part of your array. If you don't want this, you should check the input and add it to the array only if it is not 0.
Also note the declaration of i before the for loop. Because we need it after the for loop. Why? see below.
int i = 0;
for (i = 0; i < NumberOfElements; i++) {
int n = input.nextInt();
if (n == 0)
break;
else
num[i] = n;
} //for loop ends here
Step 2: Sort it
Arrays.sort(num);
Step 3: Print the output:
for (i = 0; i < num.length; i++) {
System.out.print(" " + num[i]);
}
The problem is, in step 2, an array of 1000 elements is sorted, while you actually need to consider only the number of elements the user has entered. You don't know that initially thats why you created an array of 1000 elements.But, at this point (after step 2) you do know how many number of elements the user has entered. This is present in i
So new step between 1 and 2: Create a new arrays that contains only those elements that the user has entered.
Step 1.5:
int[] newArray = Arrays.copyOf(num, i);
Now sort this new array, and print it (same as your code, but uses the new array we just created)
Arrays.sort(newArray);
for (i = 0; i < newArray.length; i++) {
System.out.print(" " + newArray[i]);
}
Notes:
1. The ideal way to do this is to use Lists and not arrays, but probably since this is homework, you might have to use arrays.
Since this is homework, I don't know whether you are allowed to use Arrays.sort or Arrays.copy. Your professor might frown at this because perhaps his intention was that you learn the constructs of the language via for, if and while. In that case you have to do step 1.5 (make array the right size) and sort by yourself.
This is not difficult (but just remember this is not the best way to do it, except for in a homework)
Copy array (homemade) (in place of step 1.4 above)
int[] newArray = new int[i]
for(int j=0; j<i; j++){
newArray[j] = num[j];
}
Sort (homemade) (in place of step 2 above):
Loop through the elements
If one element is greater than the previous element, swap them (in asc order, the prev element is always lesser or equal to the next element)
There are two loops because you have to do the comparison on a continuous basis: the the first element, compare with the entire array, place it in the right position, take the second compare with the entire array etc...)
for(int j=0; j<newArray.length; j++) {
for(int k=0; k<newArray.length; k++) {
if(newArray[k] > newArray[j]) {
//the swap logic:
int t = newArray[k];
newArray[k] = newArray[j];
newArray[j] = t;
}
}
}
Try to understand what really is happening, instead of just copy pasting.
Once you understand the homemade sort logic, think about this:
The second for loop in the sort or(int k=0; k<newArray.length; k++) { can actually just be for(int k=0; k<newArray.length; k++) {. Why?
Your print loop will remain the way you wrote it, but you will print newArray rather than num. You might want to change the loop variable to int j or something, but i will also work. (i holds the no of inputs now, so I would not use it for any other purpose. But it is just a manner of coding. Technically no difference - the code will work the same way)
I am not combining the parts. I leave that o you, otherwise it will look like I did your homework :-)
num[i] holds the last number you are reading. So you have to compare it against 0 and if it is 0, you have to end the loop. Read about branching statements to find out how to do that.
It is probably also good for you to read about control flow statements in general.
Here your application is reading int, you can check that the last one is != from 0. And break the loop.
If you don't like using break, you can still add a condition to your for.
For sorting an array, there is the Arrays.sort() solution.
And to print them you'll need another loop, but beware as you can have less than 1000 items in your array you can't simply print the whole array.
You'll need to find a way to count the number of elements you added in the array.
After your edit:
Good your application seems to work here is what I got :
Mac-Makkhdyn:~ Makkhdyn$ java hw3.Main
Enter any positive number or enter 0 to stop: 1
Enter any positive number or enter 0 to stop: 2
Enter any positive number or enter 0 to stop: 3
Enter any positive number or enter 0 to stop: 4
Enter any positive number or enter 0 to stop: 5
Enter any positive number or enter 0 to stop: 0
Mac-Makkhdyn:~ Makkhdyn$
The 0 you have must be from somewhere else. Isn't your actual code slightly different from the one you posted here ?
Resources :
javadoc - Arrays.sort()
Java tutorial - The break Statement