Questions about array - java

Here is my code and it works perfectly fine.
import java.util.Random;
class apples
{
public static void main(String args[])
{
Random rand = new Random();
int frequency[] = new int[7];
for(int roll = 1;roll < 1000;roll++){
++frequency[1+rand.nextInt(6)];
}
System.out.println("Face\tFrequency");
for(int face = 1;face < frequency.length;face++){
System.out.println(face + "\t" + frequency[face]);
}
}
}
I do not understand this line of code
++frequency[1+rand.nextInt(6)];
When I removed the "++" operator, it couldn't be compiled. I know that it will add 1 to the randon numbers generated from 0 to 5 but why there is a "++" in front of frequency ? Why is it neccessary to put the "++" operator there ?

The ++ operator is incrementing the frequency at the specified index. In this case, it's the same as saying:
for(int roll = 1;roll < 1000;roll++){
int index = 1+rand.nextInt(6);
frequency[index] = frequency[index] + 1;
}
Removing the ++ operator, you're left with:
for(int roll = 1;roll < 1000;roll++){
frequency[1+rand.nextInt(6)];
}
The line frequency[1+rand.nextInt(6)] makes no sense; it is not an operation, it does not do anything.
EDIT:
Perhaps a better illustration: let x be the value looked up in the frequency array. Then the original is equivalent to:
for(int roll = 1;roll < 1000;roll++){
int x = frequency[1+rand.nextInt(6)];
++x; // Equivalent to "x = x + 1"
}
Whereas if you remove the increment operator, your resulting loop would be:
for(int roll = 1;roll < 1000;roll++){
int x = frequency[1+rand.nextInt(6)];
x; // ...what?
}

The statement without the ++ looks at the contents of the array, but does not do anything with the value. Adding the ++ operator tells it to increment the value found there.
You probably are thinking that frequency[1+rand.nextInt(6)] is adding a value to the array. It is not. It is looking up a location in memory from a random location.

++ is a shorthand for
int i = 1+rand.nextInt(6);
frequency[i] = frequency[i] + 1;
Removing it causes no increment expression is executed.

that line is equivalent to this line of code
int index = 1+rand.nextInt(6);
frequency[index] = frequency[index]+1 ;
so if you removed '++' you make the statement incomplete like the following:
int x= 5;
x;
so it gives you error

Related

Program entering in a infinite loop only with a specific value

I just started with java and while was doing an exercise about permutations (the exercise asked to create a permutation of N elements using an array a[] meeting the requirement that no a[i] is equal to i.) I've created the following code. While testing it, I realized that it entered in a infinite loop sometimes when N = 6 specifically.
Any thoughts on where is the problem?
public class GoodPerm {
public static void main(String arg[]) {
int n = Integer.parseInt(arg[0]);
int[] guests = new int[n];
for (int i = 0; i < n; i++) {
guests[i] = i;
}
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int q = guests[r];
guests[r] = guests[i];
guests[i] = q;
if(guests[i] == i){
i --;
}
}
for(int q : guests){
System.out.println(q);
}
}
}
Maybe the code enters in a inf-loop in another values, but I didn't found any others.
This code can always enter an inf-loop. As I understand the code, you try to do some random switches to achieve your needed result. But if the last element of your array has never been switched, it won't be possible to switch it to any "later/higher" position (because there are no more). In the "last" iteration of your second for-loop (so i + 1 == n holds at the beginning) r will always evaluate to i thus no real switch happens. If the last element is still in place, you gonna repeat this forever.

how do i get rid of the zero that shows up after all my elements in my array are listed?

i have to make a program that prints out the elements of an array filled with random numbers backwards but it also prints out a zero after my variables? i think it has something to do with my for-loops but i get a java.lang.ArrayIndexOutOfBoundsExceptionerror any time i try to change them.
edit: i also noticed that the first printed element is always zero. i don't really see it as a problem but what could be causing that?
import java.util.*;
public class EZD_printBackwards
{
static int vars[] = new int[10];
static int backwards()
{
Random rand = new Random();
int bkwds = vars[0];
for (int a = 0; a < 10; a++)
{
vars[a] = rand.nextInt(100)+1;
}
for (int x = 10; x > 0; x--)
{
System.out.println("Element " + x + " is " + vars[x] );
}
return bkwds;
}
public static void main(String Args[])
{
int option;
Scanner kbReader = new Scanner(System.in);
do
{
System.out.println(backwards());
System.out.print("Type 1 to run again. Type 0 to end the program.");
option = kbReader.nextInt();
while(option !=1 && option !=0)
{
if (option != 1 && option != 0)
{
System.out.print("Please enter 1 to run again or 0 to end the program.");
option = kbReader.nextInt();
}
}
}while(option==1);
System.out.println("");
}
}
In your example, vars is size 10. The second for loop starts at index x = 10 which is greater than the last index of vars because array index starts at zero. To fix the issue, you should use this condition in your for loop:
for (int x = vars.length -1; x >= 0; x--)
{
System.out.println("Element " + x + " is " + vars[x] );
}
You have two problems:
FIRST => For loop out of bounds
you want to go through 10 elements, therefore your
for (int x = 10; x > 0; x--)
should be
for (int x = 9; x >= 0; x--)
0..9 is 10 elements and the same things goes for
for (int a = 0; a < 10; a++)
to
for (int a = 0; a < 9; a++)
SECOND ==> 0 at the end
That's because you do
System.out.println(backwards());
instead of
backwards();
you are returning the value of "bkwds", and you are initializing "bkwds" with vars[0] , and i guess in java the compiler initialize all the values of an array with 0 ,
in other words your probleme is in System.out.println(backwards());
remove it with
backwards();
and it should work !
EDIT
your look is out of bound either replace it with this
for (int a = 0; a < 10; a++)
or
do this
for (int a = 9; a > 0; a--)
The range of your Array is from 0 up to and including 9. Your for loop, however, is starting from 10 and coming down to index 1. It should start from 9 and comes down to index zero. This, however, does not explain printing random 0! The reason for these zeros is you have an int bkwds which youb set to vars[0] at the beginning of your function. But, since it is not initialized, it will be set to 0 (the default for int) In your main, you call the function in a print statement, which I suppose keeps printing that falsely, useless initialized variable that you return :)
As arrays are indexed from zero, change to
System.out.println("Element " + x + " is " + vars[x-1] );
output
Element 10 is 31
Element 9 is 63
Element 8 is 82
Element 7 is 46
Element 6 is 67
Element 5 is 24
Element 4 is 3
Element 3 is 27
Element 2 is 37
Element 1 is 13
edit
And change this
System.out.println(backwards());
to
backwards();
As the return value of this method is useless and not used, change this method to return void

array index out of bounds exception for no reason

I am getting array index out of bounds exception at the last line of the prog,
output[1][1] generates such an exception there. But the same thing remained normal in the previous loop.
{
int ict=66,total_slots=12,h1=15,index_count=65;
String output[][] = new String[ict][total_slots+1];
for (int x = 0; x < (ict); x++)
output[x][0] = Integer.toString(x);
for (int y = 0; y < (total_slots + 1); y++)
output[0][y] = Integer.toString(y);
for (int x = 1; x <= (index_count); x++ )
for (int y = 1; y <= (total_slots); y++)
output[x][y] = "n";
for (int x=1; x <= h1; x++) {
output[x][1]="y";//exception occurs here
limit[x]++;
}
}
{
int ict=66,total_slots=12,h1=15,index_count=65;
..................................................
..................................................
for (int x=1; x <= h1; x++) {
output[x][1]="y";//exception occurs here
limit[x]++;
}
}
At the last for loop, you recieve ArryIndexOutOfBoundsException , while trying to access the element output[13][1] cause your array width is only 13 i.e max index will be 12 but not more than that
Use total_slots instead of h1
Remember when you declare an array like String output[][]=new String[5][5]; then output[4][4] is the last element you can access since array indexes start at 0
you have declared your array as:
String output[][] = new String[ict][total_slots+1];
in your for loop you have
for( int x=1; x<=(ict); x++ )
for( int y=1; y<=(total_slots); y++)
output[x][y]="n";
On the very last iteration of the outer loop and the very first iteration of the inner loop, you are trying to access output[ict][0] which is what throws the exception. Remember that since 0 is the first index, ict - 1 will be the last valid index for the first dimension.
Try this:
String output[][] = new String[ict][total_slots]; //this is cleaner
for( int x=0; x<ict; x++ )
for( int y=0; y<total_slots; y++)
output[x][y]="n";
This way the last iteration of the outer loop would only go up to ict - 1
edit:
It seems you have edited the question significantly. Please do not edit your question in the future in response to answers, because this will only confuse new readers.
As your code stands right now, the only error (compile time no less, irrelevant to exceptions) is the fact that limit[x]++; is invalid because limit has not been declared in this scope. otherwise the code is legal and runs fine.
I am getting array index out of bounds exception at the last line of the prog, output[1][1] generates such an exception there.
Recheck the console output. You must have mistaken the erroring line, since there is no way to generate such an exception. The problem most probably lies in the limit[], which we don't know how it's declared.
Btw, the last line is limit[x]++ ;)

Java: Longest Ascending substring

I am trying to create a Java program that reads a numerical string typed from the keyboard,
and gives out the longest ascending substring.
The following is my code:
import java.util.Scanner;
public class Ascending{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number = ");
String n = in.nextLine();
int length = n.length();
for(int i = 0; i < length; i++) {
char first = n.charAt(i);
char next = n.charAt(i+1);
char last = n.charAt(length-1);
int f = (int)(first - 48);
int nx = (int)(next - 48);
int l = (int)(last - 48);
if (f<nx) {
String asc = n.substring(i, i++);
i++;
System.out.println("output = " + asc);
}
else {
String asc = n.substring(i, i++);
System.out.println("output = " + asc);
break;}
}
}
}
When I compile the above, I get
<Enter a number = 12 output = >
without any results.
I am assuming something went wrong inside the for-loop but I am unable to figure out where exactly I went wrong.
I'm afraid I might have defined too many unnecessary variables?
You are using the post-increment operator, but I don't think you have experimented to see how it works. Try this:
int i = 0;
System.out.println(i);
System.out.println(i++);
System.out.println(i);
You'll get
0
0
1
That's because post-increment (++) says "increment this value, then return what the value was before you incremented it".
So when you ask for
n.substring(i, i++);
You are explicitly asking for a 0-length string (because i == i++).
You could use the pre-increment operator, ++i, but it's rarely used outside of code-golf so you'll just end up confusing people. Best practice IMO is to just use ++ on its own line and avoid looking at the return value.
Really, what you want here is
n.substring(i, i+1);

Post increment operator not incrementing in for loop [duplicate]

This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 8 months ago.
I'm doing some research about Java and find this very confusing:
for (int i = 0; i < 10; i = i++) {
System.err.print("hoo... ");
}
This is never ending loop!
Anybody has good explanation why such thing happens?
for (int i = 0; i < 10; i = i++) {
The above loop is essentially the same as: -
for (int i = 0; i < 10; i = i) {
the 3rd part of your for statement - i = i++, is evaluated as: -
int oldValue = i;
i = i + 1;
i = oldValue; // 3rd Step
You need to remove the assignment from there, to make it work: -
for (int i = 0; i < 10; i++) {
(On OP request from Comments)
Behaviour of x = 1; x = x++ + x++; : -
As far as your issue as specified in the comment is concerned, the result of the following expression: -
x = 1;
x = x++ + x++;
is obtained as follows: -
Let's mark different parts of the second statement: -
x = x++ + x++;
R A B
Now, first the RHS part (A + B) will be evaluated, and then the final result will be assignmed to x. So, let's move ahead.
First A is evaluated: -
old1 = x; // `old1 becomes 1`
x = x + 1; // Increment `x`. `x becomes 2`
//x = old1; // This will not be done. As the value has not been assigned back yet.
Now, since the assignment of A to R is not done here, the 3rd step is not performed.
Now, move to B evaluation: -
old2 = x; // old2 becomes 2. (Since `x` is 2, from the evaluation of `A`)
x = x + 1; // increment `x`. `x becomes 3`.
// x = old2; // This will again not be done here.
Now, to get the value of x++ + x++, we need to do the last assignment that we left in the evaluation of A and B, because now is the value being assigned in x. For that, we need to replace: -
A --> old1
B --> old2 // The last assignment of both the evaluation. (A and B)
/** See Break up `x = old1;` towards the end, to understand how it's equivalent to `A = old1; in case of `x = x++`, considering `x++ <==> A` in this case. **/
So, x = x++ + x++, becomes: -
x = old1 + old2;
= 1 + 2;
= 3; // Hence the answer
Break up of 3rd part of x = x++, to see how it works in x = x++ + x++ case: -
Wonder why the replacement is done as A --> old1 and not x --> old1, as in case of x = x++.
Take a deep look at x = x++ part, specially the last assignment: -
x = oldValue;
if you consider x++ to be A here, then the above assignment can be broken into these steps: -
A = oldValue;
x = A;
Now, for the current problem, it is same as: -
A = old1;
B = old2;
x = A + B;
I hope that makes it clear.
You're using post-increment: i = i++;, it means something like this:
temp = i;
i = i + 1;
i = temp;
because 15.14.2 Postfix Increment Operator ++:
The value of the postfix increment expression is the value of the variable before the new value is stored.
That is why you have the old value.
For-loop done right:
for (int i = 0; i < 10; i++) {
System.err.print("hoo... ");
}
because of i=i++
for (int i = 0; i < 10; i++) {
System.err.print("hoo... ");
}
i++ will report the value of i, and THEN increment. This also means that you don't need to set i equal to i++, just change to
for (int i = 0; i < 10; i++) {
The problem is in the statement i=i++, this statement does three operations in sequence to complete. these are two operations in i++ and one assignment( = ) operation. These are;
i++ does two operation before any operation
Returns i
Increments i
finally assignment operation
Assigns returned value
So i is incremented before assignment making it to have old value.
Lets see i=i++ in the first loop( where i = 0 ) with the three operations
returns 0 , it will not be assigned to i until the next operation is done
increments i ( i= 0 + 1 = 1 )
assigns returned value 0 to i, ( i = 0), finally i having its old value.
In i++ first i is returned, but immediately before any operation is done it is incremented(i becomes i+1 ), However we are yet left with assignment operation to complete so that the returned value will be assigned to i making it to have old value, thereby entering infinite loop.
so replace i=i++ with i++or i=i+1

Categories

Resources