for (int i = 0; i < ary1.length; i++) {
int j = 1;
System.out.println("Enter integer #"+ j++ +":" );
ary1[i] = elementValue.nextInt();
}
This is part of code that allows me to input values into an array. I want the system out to display enter integer #1 for element 0 and integer #2 for element 1 and so on. Variable j isn't increasing although I set it to raise by one each time. Any guidance would be greatly appreciated. Thank you
You do not really need the second counter. You can do the following.
for (int i = 0; i < ary1.length; i++) {
System.out.println("Enter integer #"+ (i+1) +":" );
ary1[i] = elementValue.nextInt();
}
Simply move the declaration of j outside of the loop:
int j = 1;
for (int i = 0; i < ary1.length; i++) {
System.out.println("Enter integer #"+ j++ +":" );
ary1[i] = elementValue.nextInt();
}
You need to declear the j var outside the loop. In you code the j var is assigning every time. So increment is interrupting. It should be
int j = 1;
for (int i = 0; i < ary1.length; i++) {
System.out.println("Enter integer #"+ j++ +":" );
ary1[i] = elementValue.nextInt();
}
While a second variable is not needed here (and it is a bit silly because of the relationship), it is perfectly valid to "loop multiple variables", including declaring and incrementing them together:
for (int i = 0, j = 1; i < ary1.length; i++, j++) {
// ..
}
Note that j is also scope to the loop (albeit with an initial value of 1), and is also incremented in the loop independently of (but at the same time as) i.
Related
I'm trying to compare elements in an array. When I use a variable within a loop, I get an out of bounds error. Yet when I use explicit values in place of the variables, with the same value, it works fine.
What am I missing?
The problem line is:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
But if I use this, it works (values should be identical):
int result = (myList[0]).compareToIgnoreCase(myList[1]);
Have searched high and dry for this. Other posters had different issues. Would appreciate any input! Here's the example with dummy content:
public class methodSortTest
{
public static void main(String[] args)
{
// Create and load data into array
String[] myList = new String[2];
myList[0] = "Charlie";
myList[1] = "Bravo";
// Compare, positive/negative
for (int j = 0; j < myList.length; j++)
{
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
System.out.println("Result is: " + result);
}
}
}
Try this:
change this:
for (int j = 0; j < myList.length; j++)
to this:
for (int j = 0; j < myList.length-1; j++)
problem is inside this statement:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
because you are accessing the j+1
Simple Helping material:
https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/
When j equals 1, myList[j + 1] evaluates to myList[2] which throws an ArrayIndexOutOfBoundsException. There is no item at index 2 because you have only inserted items at index 0 and 1.
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
Change your for loop from
for (int j = 0; j < myList.length; j++)
To
for (int j = 0; j < myList.length-1; j++) // note the "-1"
I would like to know, which is fast way to write/read in an int array.
Here my Java code: I have three int arrays, two in read access and one int array in write access.
for(int j = h20 ; j < h21 ; j++){
for(int i = w20 ; i < w21 ; i++){
if( int_color == arr3[j*h31 + i] ) continue; //condition
arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
}
}
My code is a classic 2D array loop, there are just one special condition to check.
Is it other way to write this code to decrease processing time?
Thx.
You can reduce the amount of calculations, if you separate them by variables. In your case, any calculation that relies on j alone doesn't have to be inside the inner loop because the result won't change for the rest of the loop. Instead, calculate the values outside and only use the result in the inner loop.
for(int j = h20 ; j < h21 ; j++){
int tmp1 = j*h31;
int tmp2 = (j+decY)*w11 + decX;
int tmp3 = j*w21;
// j won't change inside here, so you can simply use the precalculated values
for(int i = w20 ; i < w21 ; i++){
if( int_color == arr3[tmp1 + i] ) continue; //condition
arr1[tmp2 + i] = arr2[tmp3 + i];
}
}
Edit: If you want to reduce this even more, you could rewrite the calculation for tmp2:
(j+decY)*w11 + decX ==> j*w11 + decY*w11 + decX
Then, you could extract the decY*w11 + decX into its own variable outside the first loop.
int tmp0 = decY*w11 + decX;
for(int j = h20 ; j < h21 ; j++){
int tmp1 = j*h31;
int tmp2 = j*w11 + tmp0;
int tmp3 = j*w21;
// j won't change inside here, so you can simply use the precalculated values
for(int i = w20 ; i < w21 ; i++){
if( int_color == arr3[tmp1 + i] ) continue; //condition
arr1[tmp2 + i] = arr2[tmp3 + i];
}
}
But this will save you only one addition per iteration, so I don't think it's worth the extra effort.
Removing calculations, especially multiplications might help.
For arr3 this would be:
final int icolor = int_color;
final int ix3 = h20 + w20;
final int dx3 = h31 + h21 - h20;
for (int j = h20; j < h21; ++j) {
for (int i = w20 ; i < w21 ; ++i) {
assert ix3 == j*h31 + i;
if (icolor != arr3[ix3]) {
arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
}
++ix3;
}
ix3 += dx3;
}
Whether this is really worthwile one needs to test.
Depending on the frequency of the condition, one might think of using System.arraycopy for consecutive ranges of i.
I need the second for loop to pick up where it left off. Every time the if statement is true I need a slot to fill in the array used in the first for loop. But I don't want the same key value to keep getting added. I need the second for loop to move to the next key value. (In the code below, arrl is an ArrayList of objects that have a value)
int temp = 0;
int count = 0;
for(int i = 0; i < eeVal.length; i++)
{
count= 0;
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1 && count == 0)
{
eeVal[i] = arrl.get(j);
count++;
temp=j;
}
}
}
}
return eeVal;
You need another variable to track where the inside loop has gotten to. Something like the following:
int temp = 0;
for(int i = 0; i < eeVal.length; i++)
{
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1)
{
eeVal[i] = arrl.get(j);
}
temp=j;
}
}
}
return eeVal;
This way, once the outside loop runs the second time around, the inside loop will start from 'temp' until the end of the loop.
From your explanation, it sounds like you do not want the inner for loop. The traversal of arrl needs to be manually controlled using a variable, e.g.`cnt', which only gets incremented when your condition for incrementing it is satisfied.
What you probably are looking for is a List.
In your answer, you don't need the first loop. This one has issues though - index i can go out of bounds.
int i = 0;
for(int j = 0; j < arrl.size(); j++) {
if(arrl.get(j).getValue() == 1) {
eeVal[i++] = arrl.get(j);
}
}
return eeVal;
What you need is a dynamic collections such as List.
Using list (I am calling the type as MyType).
List<MyType> vals = new ArrayList<>();
for(MyType item : arrl) {
if(item.getValue() == 1) {
vals.add(arrl.get(j));
}
}
return vals.toArray(new MyType[vals.size()]);
The code was picking up where the last correct value was. I needed to add 1 to j when I wanted progress to know where I left off.
int count2 = 0;
int progress = 0;
for(int i = 0; i < retVal[h].length; i++)
{
count2 = 0;
for(int j = progress; j < arr.size(); j++)
{
if(arr.get(j).getLevel() == h && count2==0)
{
retVal[h][i] = arr.get(j);
count2++;
progress = j+1;
}
}
}
return retVal;
I am trying to write a program that:
1) asks for user input to create an array of 10 elements
2) checks to make sure the elements are distinct
3) identifies the highest value among the elements.
I think Im close but I keep receiving this error message:
error: variable i is already defined in method main(String[])
for (int i = 0; i < myList.length; i++) {
Here is my full code:
import java.util.Scanner;
public class max101 {
public static void main(String[] args) {
double[] myList = new double[10];
double max = myList[0];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " distinct numbers: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble ();
for(int i = 0; i <myList.length; i++) {
for(int j = i+1; j<myList.length; j++) {
if(myList[i] == (myList[j])); {
System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers");
}
if(myList[i] != (myList[j])); {
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
System.out.println("The maximum value is " + max);
}
}
}
}
}
}
Try using different variable names in your loops
If you dont want to do the above dont reinitialize the variable with int just put i = 0
It might also be useful to look into how scope works.
My suspicion is you’re not ending your blocks properly — a block meaning from { to }. When I have my IDE indent your code, it is:
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
for (int i = 0; i < myList.length; i++) {
for (int j = i + 1; j < myList.length; j++) {
if (myList[i] == (myList[j]))
;
{
System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers");
}
if (myList[i] != (myList[j]))
;
{
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max)
max = myList[i];
System.out.println("The maximum value is " + max);
}
}
}
}
I think you see now that i is declared inside a for loop that already declares i. Also once you’ve detected a duplicate I think you should break out of the two loops rather than checking for more duplicates, and not find a max until the user has entered 10 new numbers.
One more tip, don’t put a semicolon after your if ( … ), it breaks your logic.
Thanks for taking the time to check out my question. I have to write some code in Dr. Java that takes in a word and then prints it out in a specific pattern. Basically here are some examples:
Input: fishy
Output: f
fifi
fisfisfis
fishfishfishfish
fishyfishyfishyfishyfishy
Basically, I'm just adding another character to the previous one and printing it out that many number of times.
Here is my attempt at my solution:
String wordcopy = word;
int size = wordcopy.length();
for (int i=1; i<=size; i+=1)
{
for (int j=0; j<i; j++)
{
System.out.print(word.substring(0,j+1));
}
System.out.println("");
}}
I have already set up my parameters so that's fine. The only thing I seem to be missing is the method itself that prints out what it's supposed to. Can anyone please help me with this problem and how I can go from here?
Thanks!
Replace word.substring(0,j+1) with word.substring(0,i):
String wordcopy = word;
int size = wordcopy.length();
for (int i = 1; i <= size; i += 1) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}
There are some cleanup things you can do. For instance, this code yields the same result:
for (int i = 1; i <= word.length(); i++) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}