This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 6 years ago.
I was trying to reverse String using recursion as follows.
But when I am calling reverse(arr,start++,end--) it is giving stackoverflow error.
I tried using reverse(arr,start+1,end-1) then it is working fine.
public class Reverse {
public static void main(String[] args) {
char inp[] = "TestString".toCharArray();
int n = inp.length;
reverse(inp, 0,n-1);
System.out.println(String.valueOf(inp));
}
public static void reverse(char[] arr, int start, int end){
if(start>=end)
return ;
char tmp;
tmp = arr[start];
arr[start] = arr[end];
arr[end] = tmp;
reverse(arr,start+1,end-1);//error line
}
What is the problem with reverse(arr,start++,end--)?
I want to know why value of start++ and end-- will not get passed to function.
Have a look at this SO question
SO post-increment-and-pre-increment-concept
Post
reverse(arr,start++,end--) when you do this the incremented/decremented value will not be passed to recursive method, means you are calling the method with original value of start and end result in SO error
Pre
When you do reverse(arr,start+1,end-1) or reverse(arr,++start,--end) incremented and decremented value of start and end will be passed to recursive method.
While debugging in Eclipse IDE check the values of start and end in variables panel if not using IDE write start and end values to console in reverse method
Related
This question already has answers here:
What does the "Assigned value is never used" warning mean?
(5 answers)
Closed 3 months ago.
I'm following Princeton's introductory computer science course (I'm not a student, just teaching myself). I working on this assignment.
Main is calling two methods: amplify and reverse, both of which return an array. Amplify multiplies all values in the array by a constant alpha. Reverse returns an array that lists the original array values in reverse order, ex. {1,2,3} -> {3,2,1}.
Amplify works fine, but nothing happens when I call reverse and I get a bug that states: The Value Assigned Is Never Used
public class audiocollage {
// Returns a new array that rescales a[] by a factor of alpha.
public static double[] amplify(double[] a, double alpha) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * alpha;
}
return a;
}
// Returns a new array that is the reverse of a[].
public static double[] reverse(double[] a) {
double[] b = new double[a.length];
for (int i = a.length - 1, j = 0; i >= 0; i--, j++) {
b[j] = a[i];
}
return b;
}
// Creates an audio collage and plays it on standard audio.
public static void main(String[] args) {
double[] samples = StdAudio.read("cow.wav");
double alpha = 2.0;
samples = amplify(samples, alpha);
samples = reverse(samples);
}
}
It sounds like you have two questions:
Why doesn't anything happen when I call reverse(samples)?
The code you're showing does nothing with the result of reverse(samples) other than store it in the variable samples (overwriting its previous value). You will need to do something with samples after that to observe the new array (like printing samples, which should now appear to be reversed).
Which leads into the next question:
Why do I get a warning about "the value assigned to samples is never used"?
This is a warning saying that the code you wrote doesn't do anything.
Dead store to local variable is the first line of the warning, which describes what's happening: the value stored to samples is "dead" -- it is never used again, and so we may as well have skipped that line altogether. That causes your compiler (or extension) to give us a warning because it's almost certain that the code you wrote is not doing what you intended, so in many cases that warning can be helpful for spotting mistakes.
This warning can be resolved by using samples somehow, such as by printing it, calling another function with it, etc.
The previous line
samples = amplify(samples, alpha);
doesn't generate that warning because it's output is used in the following call to reverse():
samples = reverse(samples);
// ^ usage of `samples` variable!
This is made even clearer by using different variables for all your arrays:
public static void main(String[] args) {
// No warning; samplesRaw used later
double[] samplesRaw = StdAudio.read("cow.wav");
double alpha = 2.0;
// No warning; samplesAmplified used later
samplesAmplified = amplify(samplesRaw, alpha);
// WARNING! samplesReversed is never used!
samplesReversed = reverse(samplesAmplified);
}
If the hint is related to the last line, it means you have a local variables samples which has not used ( you assigned a value but never read it)
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have to to a calculator that adds, subtract, multiply and divide the numbers one by one to a stack, and at the end it will show the result of all operations. Example.
Input:10
Input:+
Input:10
Input:=
Output: 10+10=20
I tried to do it by manually pushing the numbers and operators, and it worked fine, for adding and subtracting only. (here is the code).
public static void main(String[] args) {
Stack<String> stack = new Stack();
stack.push("10");
stack.push("+");
stack.push("10");
stack.push("-");
stack.push("20");
stack.push("+");
stack.push("1");
stack.push("=");
int result=0;
int i;
int result=0;
for(i=0;i<stack.size();i++){
if (stack.elementAt(i)== "+"){
//does get in
I checked in the second code that the stack is similar to the one on the first code, and it is similar. For some reason, it doesn't want to go through the if statement, even though it is equal to "+" or "-".
Stack<String> stack = new Stack();
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String s1 = sc.next();
stack.push(s1);
if(s1.equals("=")) {
break;
}
}
int i;
int result=0;
for(i=0;i<stack.size();i++){
System.out.print(stack.elementAt(i));
}
for(i=0;i<stack.size();i++){
if (stack.elementAt(i)=="+"){
//doesn't get in
The problem with your code is in this line
if (stack.elementAt(i)== "+")
The stack takes String types of arguements. For comparision you should use
if(stack.elementAt(i).equals("+"))
Similarly , do the same for "-".
This question already has answers here:
Find duplicate element in array in time O(n)
(24 answers)
Closed 7 years ago.
I recently had an interview which consisted of following problem. Please help with possible solutions.
Write a method in Java to find duplicate elements in an integer array without using nested loops ( for/ while / do while, etc ) and without using library functions or standard API's.
Hey the below solution has complexity O(n) and works fine. Check if it helps.
public class Main {
public static void main(String[] args) {
int a[] = new int[]{10,3,5,10,5,4,6};
String distinctElement="";
String repetitiveTerms="";
for(int i=0;i<a.length;i++){
if(i==0){
distinctElement+=a[i]+" ";
}
else if(distinctElement.contains(""+a[i])){
repetitiveTerms+=a[i]+" ";
}
else{
distinctElement+=a[i]+" ";
}
}
}
}
This question already has answers here:
Why does Java think that the product of all numbers from 10 to 99 is 0?
(9 answers)
Closed 8 years ago.
I have created a recursive method to calculate the facortial of a number, however, it is always returning 0, and I can not see why. I have provided my code below:
public class projectTwenty {
public static void main(String [] args) {
int factorialAns = factorial(100);
System.out.println(factorialAns);
}
private static int factorial(int n) {
if (n == 0) {
return 1;
}else {
return (n * factorial(n-1));
}
}
}
I have tried changing the way in which the function is called and how values are returned, no luck so far.
I have also searched Google/StackOverflow for similar methods/questions and am yet to find a solution.
Because 100 factorial has so much digits that it causes an overflow on the integer type. You can try it on a smaller values and it will work much better.
In case you want to actually calculate big factorials you can use the BigInteger class in java.
factorial(100) is probably too large to fit in an int and you get an overflow. For smaller values of n it works fine.
12 is the highest int for which factorial(12) won't overflow.
This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 8 years ago.
I'd like to know why a postfix increment on a value being returned in a return statement is not evaluated if the increment occurs on the righthand side of the return statement.
I know that the value returned should be the pre-increment value, but assuming a class-level variable, the increment should still show up in the variable itself.
Here is my example.
public class ReturnDemo {
static int val=1;
public static void main(String[] args)
{
System.out.println(getVal());
System.out.println(val);
}
public static int getVal()
{
return(val=(val++));
}
}
I would have expected this to print out
1
2
but it actually printed out
1
1
If you do the same thing without the assign, it increments correctly.
This, for example:
public class ReturnDemo {
static int val=1;
public static void main(String[] args)
{
System.out.println(getVal());
System.out.println(val);
}
public static int getVal()
{
return(val++);
}
}
Returns
1
2
(It gets val at 1 then increments the variable val to 2.)
Why is it that there is a line drawn in the sand at evaluating the postfix increment within a return statement if it's on the righthand side of an assignment, but that same line is not applied to postfix increments that are not part of an assignment statement?
The return is a red herring. The problem is val=(val++), which is Just Plain Ugly and Bad Practice.
val++ is post-increment. In other words, this subexpression returns the previous value of val, then increments the variable.
So you are telling the compiler you want to obtain the previous value of val (1), then increment it (2), then assign that previous value to val -- setting it back to 1 again. The program is doing exactly what you told it to do.
You're trying too hard. If you want to return the value of val after it has been incremented, you can use return ++val;. If you want to increment val but return the previous value, use return val++;.