Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I'm reading Head First Java and an exercise is confusing me a little bit. The Original instructions of the exercise are irrelevant, however, the point is to be able to solve it with out just compiling the code and running it, which would just spit out the answer. I am quite confused and am trying to play the debugger and go step by step each line of code and see what is happening. I have added my comments to the code to make sure I am understanding it. Just need help understanding for example what the count is at a specific point and such. Here is the original code, with one line added myself, which i've noted. Some of the lines I will note which I don't understand the best.
**Update: So I gave the best understanding on my code. Questions I have about certain lines are in the comments. If anyone can maybe do a step by step approach of what happens would make it a lot more understandable. Thank you all for your help in advance. I am new to StackOverFlow so hopefully this was the correct way of asking a question.
public class Mix4
{
int counter = 0; //This is setting the variable counter to 0.
public static void main (String[] args)
{
int count = 0; //This is setting the variable count to 0.
Mix4[] m4a = new Mix4[20];//This is initializing an array of 20 m4a objects to null.
int x = 0; //This is setting the variable x to 0;
while ( x < 9 )
{
m4a[x] = new Mix4(); //This actually creates the m4a object at array index 0.
m4a[x].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
count = count + 1; //This increments the variable count. Why do this though?
count = count + m4a[x].maybeNew(x);
//The count variable again is being implemented but this time it calls the
// maybeNew method and it is passing a 0 as as the argument? Why do this?
x = x + 1; // x is being incremented.
System.out.println(count + " " + m4a[1].counter);
//What is this printing and when does this print?
}
public int maybeNew(int index)
{
if (index < 5)
{
Mix4 m4 = new Mix4(); //Creating a new object called m4.
m4.counter = m4.counter + 1;
//Same question about this from the code of line stated above using dot
//operators on variables.
return 1; //Where does 1 be returned to? I thought you can only have one
//return statement per method?
}
return 0; // I thought only 1 return statement? I have no idea what these return
// statements are doing
}
}
}
m4a[0].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
m4a is an array of Mix4 objects. You can call object methods or properties(variables) using the . operator
count = count + m4a[x].maybeNew(x);
//The count variable again is being implemented but this time it calls the
// maybeNew method and it is passing a 0 as as the argument? Why do this?
maybeNew() return an int. You are trying to increase the count by whatever number maybeNew(x) returns. x is the value of m4a[0], if x = 0.
System.out.println(count + " " + m4a[1].counter);
//What is this printing and when does this print?
This prints at end of your program. It prints the counter value for the Mix4 object at index 1 in the m4a array
return 1; //Where does 1 be returned to? I thought you can only have one
//return statement per method?
}
return 0; // I thought only 1 return statement? I have no idea what these return
// statements are doing
First of all, a method may or may not return a value. In you method, you want it to return an int. So when you call it here count = count + m4a[x].maybeNew(x);, it like saying, whatever number maybeNew(x) returns, add that to count.
Your first return 1 is inside of a conditional statement. If the condition is satisfied, return 1, else return 0
int x = 0; //This is setting the variable x to 0;
You got this part right
Now inside while loop in the 1st iteration x = 0;
Mix4[] m4a = new Mix4[20];
This again as you correctly guesses is just defining of an array. Simply putting it is a group of 20 reference of type Mix which woould point to the actuall Object of type Mix. Now you have to assign these objects to the references which is what we are doing in the while loop.
m4a[x] = new Mix4();
Here in 1st iretartion we are doing m4a[0] = new Mix4(); so the element at index 0 is initialized.
m4a[0].counter = m4a[x].counter
Here we are simply accessing the counter of the actual object and assigning value to it.
How can you use a dot operator on a variable?
First if all m4a[0] has been initialized. Next thing you need to know is acess modifieer. If you look at the statement
int counter = 0;
No access modifer is specified which means it has default access modifier. Now for default access modifier visibilty of a variable is in the same class and same package(No need of getter/setter methods).
Also note that counter is an instance variable(not local variable) and instance variables are assigned default values(for int it is 0, for String it is null and so on...)
Try to debug the code step by step with this basic understanding.
Where does 1 be returned to? I thought you can only have one
return statement per method?
You may have have one return statement for one branch in your function, its not restricting to have one one return statement per function, its should be only one return statement for one logic path. Like :
public int DoStuff(Foo foo) {
if (foo == null) return 0;
...
return 1; // any thing
}
m4a[0].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
m4a is an array ofMix4Class objects. You can call object methods or properties using the . operator.
From Using Objects
Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:
objectReference.fieldName
System.out.println(count + " " + m4a1.counter);
//What is this printing and when does this print?
From System.out.println()
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
It will print the count value, and counter value for the Mix4 object at index 1 in the m4a array.
Your code as you have shown above will not compile for two reasons:
You have the System.out.printlninside the while loop; this will result in a NullPointerException as when the compiler gets to m4a[1].counter the m4a[1] object has not been created. Only m4a[0] has been created. Alternatively you can leave this line where it is but change it to m4a[0].counter
You have the maybeNew(int index) method declaration inside main; this is mostly likely just a mistake with your curly brackets but just so you know you can't declare a method inside another method; main is a method and so you must declare maybeNewoutside it but call it from within main
public class Mix4 {
int counter = 0;
public static void main (String[] args) {
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x < 9) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + m4a[x].maybeNew(x);
x = x + 1;
// System.out.println(count + " " + m4a[0].counter);
}
System.out.println(count + " " + m4a[1].counter);
}
public int maybeNew(int index)
{
if (index < 5)
{
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}
Related
i am trying to print numbers from 1 to 10 without using loops in java. When n+1 is passed to recursivefun method call in line 6,it works fine. But when n++ is passed,the code throws an error :/
public class PrintWithoutUsingLoops {
public static void recursivefun(int n) {
if (n <= 10) {
System.out.println(n);
recursivefun(n++);//an exception is thrown at this line.
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
recursivefun(1);
}
}
recursivefun(n++);
passes the original value of n to the recursive call (since you are using the post-increment operator), making this recursion infinite (since each recursive call gets the same value of n, which never reaches 11) and leading to StackOverflowError.
Change it to
recursivefun(n+1);
or
recursivefun(++n);
recursivefun(n++);
is a call with post-increment. Post increment is a mechanism which enlarges the value after it is read. In this case, you always pass 1.
You can use pre-increment which is ++n which first: increments and then passes the value.
The exception you get is StackOverflowError which means, that the stack is full and JVM cannot store more calls on stack, so it won't be able to revert.
recursivefun(n++);
This line means : call recursivefun(n); and then increment n by 1 so you'll always call your fuction with n=1 and caused a stackOverflow sure
So you need to increment n BEFORE all the function, you have some options :
recursivefun(n+1);
//-----------------------------
n++;
recursivefun(n);
//-----------------------------
recursivefun(++n); //pre-cincrement
Indeed both post and pre increment operators increments the value of a variable. Their behavior changes based on the context of the usage. Assume the following code:
For loop 1:
for (i=0; i<10; i++)
...
For loop 2:
for (i=0; i<10; ++i)
...
In both of the above statements, the for loop iterates 10 times irrespective of the increment style used. However consider the following code:
int x = 10;
int y = 20;
int z = x++ + ++y; // z = 10 + 21
System.out.println("x = " + x); // prints 11
System.out.println("y = " + y); // prints 21
System.out.println("z = " + z); // prints 31
Hence from your code it is evident that
recursivefun(n++);
calls recursivefun with argument 1 infinitely. To avoid StackOverFlow error use either ++n or n+1.
I am passing some parameters in the URL and then I add them in a list. My list has a limit of 5 elements. So if someone adds 6th element in the URL the list would simply ignore it. So I am trying to use a counter but the logic is not working as desired. I am using While loop to achieve this. So if list size is smaller than 5 set the agencyCds otherwise just return the list.
private List<IUiIntegrationDto> generateViewIntegrationReportData(ESignatureIntegrationConfig eSignConfig) throws Exception {
int counter = 1;
if(eSignConfig.getAdditionalAgencyCds() != null ) {
List<String> combinedAgencyCds = new ArrayList<String>();
for(String agencyCd : eSignConfig.getAgencyCd()) {
combinedAgencyCds.add(agencyCd);
}
StringTokenizer token = new StringTokenizer(eSignConfig.getAdditionalAgencyCds().toString(), StringConstants.COMMA);
while(token.hasMoreTokens()) {
combinedAgencyCds.add(token.nextToken());
}
while(combinedAgencyCds.size() < 5) {
counter = counter + 1;
eSignConfig.setAgencyCd(combinedAgencyCds);
}
// eSignConfig.setAgencyCd(combinedAgencyCds);
}
List<IUiIntegrationDto> intgList = getUiIntegrationManager().retrieveUiIntegrationReportData(eSignConfig.getAgencyCd(), eSignConfig.getCreatedDays(),
eSignConfig.getLob(), eSignConfig.getTransactionStatus(), eSignConfig.getAccounts(), eSignConfig.getSortKey(), eSignConfig.getSortOrder());
return intgList;
}
I am not completely sure about this logic if it is correct or if there is nay better approach.
Thanks
Try this instead of the last while in your code:
if(combinedAgencyCds.size() <= 5) {
eSignConfig.setAgencyCd(combinedAgencyCds);
} else {
eSignConfig.setAgencyCd(combinedAgencyCds.subList(0, 5));
}
The full combined list will then be used if it is less than 5 in size. Otherwise, only the first 5 elements are used.
Edit: Or even better:
eSignConfig.setAgencyCd(combinedAgencyCds.subList(0, Math.min(5, combinedAgencyCds.size())));
Ok so let's break down what your code is currently doing.
int counter = 1;
while(combinedAgencyCds.size() < 5) {
counter = counter + 1;
eSignConfig.setAgencyCd(combinedAgencyCds);
}
This snippet of code has a couple things wrong best I can tell. First, this loop has the possibility of running forever or not at all. Because combinedAgencyCds is never being manipulated, the size won't ever change and the logic being checked in the while loop never does anything. Second, there's a more efficient loop for doing this, assuming you don't need the counter variable outside of its usage in the while loop and that is using for loops.
Example syntax is as follows:
for (int i = 0; i < combinedAgencyCds.size(); i++) {
if (i < 5) {
// Do your logic here.
}
else {
break; // Or handle extra values however you want.
}
}
Notice there is no need for the explicit declaration for a counter variable as "i" counts for you.
Now in your actual logic in the loop, I'm not sure what the setAgencyCd method does, but if it simply sets a list variable in the eSignConfig like it appears to, repeating it over and over isn't going to do anything. From what I can see in your code, you are setting a variable with the same value 5 times. If you need any more explanation just let me know and I will be happy to revise the answer.
Tried changing around the for loop condition several times, still get ArrayIndexOutOfBounds when I pass zero as a parameter. Every other number works fine, I am trying to account for zero by setting it equal to zero automatically, am I doing that part incorrectly? Everything compiles and runs fine except for zero.
private static int iterativeCalculation(int userEntry)
{
int iterativeArray[] = new int[userEntry + 1];
iterativeArray[0] = 0;
iterativeArray[1] = 1;
for (int i = 2; i <= userEntry; i++)
{
iterativeArray[i] = (3 * iterativeArray[i - 1]) - (2 * iterativeArray[i - 2]);
iterativeEfficiencyCounter++;
}
return iterativeArray[userEntry];
}
public static void main(String[] args) {
System.out.println(iterativeCalculation(0));
}
Tried debugging my way through the code, still not understanding what is going wrong. Would appreciate any help! Thanks!
When you pass zero as parameter, userEntry + 1 = 1.
But here:
iterativeArray[1] = 1;
You are trying to set the second element's value. Remember that length of array is one less than its actual size. So removing this line will fix it. Or use userEntry + 2 instead and alter your loop accordingly.
EDIT:
If you really want to fix first and second element, then use this instead:
int iterativeArray[] = new int[userEntry + 2];
iterativeArray[0] = 0;
iterativeArray[1] = 1;
This will create an array of adequate base size.
And remember, length you enter in [...] while creating array has to be one more than the actual length you want. Because actual array starts counting from 0.
In your case, you were setting length as 1 (minimum). That would create an array which can store only one element; that is iterativeArray[0] = //something. Anything above that is OutOfBounds.
You are setting iterativeArray[1] = 1; regardless of whether or not there are actually 2 or more items in the array. That will be out of bounds with one element.
I think you should step through the code in debugger to best understand what the problem is. You'll see exactly where it's got a problem if you single-step through the code. This is a fundamental technique and tool.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am preparing for an exam next week, and I decided to look for some exam questions online for better preparation.
I came across this question and the answer is c. But I really want to know how or the step by step process to answer to answer a question like this. The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method? Whenever I get to a question like this is their anything important I should breakdown first?
private int[] myStuff;
/** Precondition : myStuff contains int values in no particular order.
/*/
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
Which of the following best describes the contents of myStuff after the
following statement has been executed?
int m = mystery(n);
(a) All values in positions 0 through m are less than n.
(b) All values in positions m+1 through myStuff.length-1 are
less than n.
(c) All values in positions m+1 through myStuff.length-1 are
greater than or equal to n.
(d) The smallest value is at position m.
(e) The largest value that is smaller than n is at position m.
See this page to understand a method syntax
http://www.tutorialspoint.com/java/java_methods.htm
int m = mystery(n); means this method going to return int value and you are assigning that value to a int variable m. So your final result is m. the loop will run from the array's end position to 0. loop will break down when array's current position value is less than your parameter n. on that point it will return the loop's current position. s o now m=current loop position. If all the values of the loop is greater than n it will return -1 because if condition always fails.
Place the sample code into a Java IDE such as Eclipse, Netbeans or IntelliJ and then step through the code in the debugger in one of those environments.
Given that you are starting out I will give you the remainder of the code that you need to make this compile and run
public class MysteriousAlright {
private int[] myStuff;
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
MysteriousAlright ma = new MysteriousAlright();
ma.setMyStuff(new int[] {4,5,6,7});
int m = ma.mystery(5);
System.out.println("I called ma.mystery(5) and now m is set to " + m);
m = ma.mystery(3);
System.out.println("I called ma.mystery(3) and now m is set to " + m);
m = ma.mystery(12);
System.out.println("I called ma.mystery(12) and now m is set to " + m);
}
public void setMyStuff(int[] myStuff) {
this.myStuff = myStuff;
}
}
You then need to learn how to use the debugger and/or write simple Unit Tests.
Stepping through the code a line at a time and watching the values of the variables change will help you in this learning context.
Here are two strategies that you can use to breakdown nonsense code like that which you have sadly encountered in this "educational" context.
Black Box examination Strategy
Temporarily ignore the logic in the mystery function, we treat the function as a black box that we cannot see into.
Look at what data gets passed in, what data is returned.
So for the member function called mystery we have
What goes in? : int num
What gets returned : an int, so a whole number.
There are two places where data is returned.
Sometimes it returns k
Sometimes it returns -1
Now we move on.
White Box examination Strategy
As the code is poorly written, a black box examination is insufficient to interpret its purpose.
A white box reading takes examines the member function's internal logic (In this case, pretty much the for loop)
The for loop visits every element in the array called myStuff, starting at the end of the array
k is the number that tracks the position of the visited element of the array. (Note we count down from the end of the array to 0)
If the number stored at the visited element is less than num (which is passed in) then return the position of that element..
If none of elements of the array are less than num then return -1
So mystery reports on the first position of the element in the array (starting from the end of the array) where num is bigger than that element.
do you understand what a method is ?
this is pretty basic, the method mystery receives an int as a parameter and returns an int when you call it.
meaning, the variable m will be assigned the value that returns from the method mystery after you call it with n which is an int of some value.
"The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method?"
A method may or may not return a value. One that doesn't return a value has a return type of void. A method can return a primitive value (like in your case int) or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, the name of any class, or an interface.
If a method doesn't return a value, you can't assign the result of that method to a variable.
If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable.
I'm starting out programming with java and I'd like to make some games and various other things which require changing variables, especially integers. Let me give you an example.
int Score = 0;
if(coinCollected = 1){
int Score = 1
}
Now of course this is going to return 'int Score has already been defined', or whatever, but I don't want it to say that, since I want to REdefine the variable. I've tried #Override before the if statement and that didn't work, either. Does anyone know what to do?
I think you want to update the value, if so, you don't need to re-define.
int Score = 0;
if(coinCollected == 1){
// change the value
Score = 1;
}
You do not want to redefine the variable. You want to assign it a new value.
So simply remove the "int" from the second occurrence, so it looks like score = 1.
By the way, Java style conventions state variable names start with lowercase.
so you don't have to define Score again..
your code should look like this
int Score = 0;
if(coinCollected == 1){
Score = 1
}
if(coinCollected = 1)
In the above statement you are assigning the value of 1 to variable named coinCollected, but thats NOT what you want to do, u want to compare the value 1 with the value of the variable named coinCollected.
Eg:
if(coinCollected == 1)
Now in the below code you are re-declaring the variable Score.
{
int Score = 1
}
Corrected code:
int Score = 0;
if(coinCollected == 1){
Score = 1
}
Use a different scope, or reuse the existing score or preferably using a different name.
{
int score = 0;
} // scope of Score has ended.
if(coinCollected == 1) {
int score = 1;
}