(In the process of writing my original question, I answered it, but the information might be useful to others, and I thought of a new question)
For instance:
int x;
if (x = 5) { ... }
Creates an error:
Type mismatch: cannot convert from int to boolean. (Because assignment doesn't return a
boolean value)
However,
int x;
if ((x = 5) == 5) {
System.out.println("hi!");
}
will print out "hi!"
And similarly,
String myString = "";
if ((myString = "cheese").equals("cheese")) {
System.out.println(myString);
}
prints out "cheese"
Sadly,
if ((int x = 5) > 2) { ... }
does not work with an in-line declaration. How come? Can I get around this?
Sadly,
I suspect that most Java developers would heartily disagree with that sentiment ...
if ((int x = 5) > 2) { ... }
does not work with an in-line
declaration. How come?
It does not work because a declaration is not a Java expression, and cannot be used in an Java expression.
Why did the Java designers not allow this? I suspect that it is a combination of the following:
Java's syntactic origins are c and C++, and you cannot do this in C or C++ either,
this would make the Java grammar more complicated and the syntax harder to understand,
this would make it easier to write obscure / cryptic programs in Java, which goes against the design goals, and
it is unnecessary, since you can trivially do the same thing in simpler ways. For instance, your example can be rewriten this to make the declaration of x to a separate statement.
Can I get around this?
Not without declaring x in a preceding statement; see above.
(For what it is worth, most Java developers avoid using assignments as expressions. You rarely see code like this:
int x = ...;
...
if ((x = computation()) > 2) {
...
}
Java culture is to favour clear / simple code over clever hacks aimed at expressing something in the smallest number of lines of code.)
Your x only exists within the scope of the assignment, so it's already gone by the time you get to > 2. What is the point of this anyway? Are you trying to write deliberately unreadable code?
Your best way to get around this is to declare x in a scope that will remain valid throughout the if statement. Seriously though, I fail to understand what you're doing here. Why are you creating a variable that is supposed to disappear again immediately?
if ((int x = 5) > 2) { ... }
Yes this will not compile because you can't declare variables inside the condition section of if clause
The > test will work fine, as long as you declare the int outside of the if condition. Perhaps you are simplifying your condition for the sake of brevity, but there is no reason to put your declaration in the condition.
Can I get around this?
Yes, declare your var outside the condition.
Because you didn't declare the int separately as you did in the == test.
jcomeau#intrepid:/tmp$ cat /tmp/test.java
class test {
public static void main(String[] args) {
int x;
if ((x = 5) > 2) System.out.println("OK");
}
}
In Java, for() allows initialization code, but if() doesn't.
You can't declare the variable in condition section. For example
for(int i = 0; j < 9; i++){...}
is completely valid statement. Notice we declare the variable in for but not in a condition clause, now look at this,
for(int i = 0; (int j = 0)<9; i++){...} // Don't try to make logical sense out of it
not allowed.
Related
I'm trying to add three kinds of monsters into an array by initializing my Monster-object based on the modulo. (I'm just a beginner so bear with me).
for (int i=0; i<nrofMonsters; i++) {
Monster m;
if (i%2==0) {
m = new Vampire("Vamp-"+i);
} else if(i%2==1) {
m = new Ghost("Ghost-"+i);
} else if(i%3==2){
m = new Demon("Demon-"+i);
}
monsters.add(m);
}
ERROR MESSAGE: variable m might not have been initialized.
The error message is pretty clear: there are possible execution paths throughout your code that won't lead to an assignment of a specific value into m before it is being accesses in the monsters.add(m); statement.
Specifically, there's no final else assigning some other value in the if-else if chain:
if (i%2==0) {
m = new Vampire("Vamp-"+i);
} else if(i%2==1) {
m = new Ghost("Ghost-"+i);
} else if(i%3==2){
m = new Demon("Demon-"+i);
}
else {
m = …whatever…; // or, handle this as an error
}
monsters.add(m);
Note that the compiler (apparently) isn't smart enough to understand the conditions in ifs and hence can't tell the else part isn't necessary.
I think you, in fact, wanted something like this:
if(i%3==2){
m = new Demon("Demon-"+i);
} else if (i%2==0) {
m = new Vampire("Vamp-"+i);
} else {
m = new Ghost("Ghost-"+i);
}
The if else ladder goes from top to bottom. When you delete based on modulo 2 you can have only 2 outcomes 0 or 1. Therefore you will never reach i%3. You can delete everything based on 3 and you will have 3 outcomes.
As mentioned below I don't believe it is an init issue - can you share the language you are writing on.(And do check the inheritance tree - there can be some nasty mistakes there, when you are a beginner)
The variable 'm' is a local variable .
It is a must that local variables must be initialized.
Else it must it lead to compilation error.
A simple assignment like the below one will resolve the issue:
Monster m = null;
Though the above assignment will lead to a NullPointerException, since the code might not reach any of the 'if' or 'else if' constructs.
Thus it is best to add the 'else' construct to ensure that the code runs successfully.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Idea is to make the most elegant code as you can. Theme of section: loops.
Task: return sum of squares of numbers from 1 to (n-1)
example: 6 -> 55 (which is 1^2 + 2^2 + 3^2 + 4^2 + 5^2)
I chose Java as language and wrote this code:
public class Program {
public static int Puzzle(int n) {
int r=0;
for(--n;n>=0;r+=n*n--);
return r;
}
}
but compiler says that my code is not elegant enough. Can you help?
Link:CodeHunt
You don't need loop that series. See http://en.wikipedia.org/wiki/Square_pyramidal_number
public class Program {
public static int Puzzle(int n) {
int x = n -1;
//sum of first n-1 squares
return x*(x+1)*(2*x+1)/6;
}
}
Elegance may be a combination of simplicity and accuracy. The biggest issue with your method is that it isn't simple; it may produce the correct result, but it's needlessly complicated with unusual iteration and the fact that you're running a for-loop for its side effects.
Why not go with the more direct approach instead?
public static Puzzle(int n) {
int sum = 0;
for(int i = 1; i <= n; i++) {
sum += Math.pow(i, 2);
}
return sum;
}
Several very inelegant aspects:
Inline increments/decrements: they make the code very confusing, because most people are no experts in when the variable will actually decrement, what will for instance happen with m = (n--)*(--n); (the answer is m = n*(n-2); n -= 2;). For some small simple expressions inline decrements make code more readible. But in nearly all cases, there is no performance gain, as the compiler is smart enough to convert a readible code to one with inline increment/decrement itself.
loops with no body: most people simply get confused, think the next instruction is part of the body, etc. Most IDEs even advice to always use braces and write something in the body.
manipulation of a parameters: this is confusing and makes code less extensible. Say you want to extend your code with some part below and you perform copy-past, since the parameters don't have their original value, the pasted code will work differently. IDEs mostly advice to make at least a copy. Nearly every compiler can optimize this if it turns out the parameters is not used any further.
decrement in for loop: although this sometimes yields a small improvement in code performance, most programmers are used to for loops that increment.
semantical variable names (something a compiler cannot detect): it is recommended that you name your variables appropriately, use sum instead of r. The java compiler sees names simply as identifiers. So at runtime there is no difference, it is however more readable for other people and yourself when you revisit your code months later.
These are all very bad ways to write an algorithm. Most books strongly suggest that unless you really need to write a code that takes the absolute maximum out of your CPU, you better write nice, well structured and readable code. And furthermore if that is the case, there are more efficient languages than Java.
As a better version, I recommend the following code:
public class Program {
public static int Puzzle(int n) {
int sum = 0;
for(int i = 1; i < n; i++) {
sum += i*i;
}
return sum;
}
}
Furthermore you don't need a for-loop to calculate this (as pointed out here):
public class Program {
public static int Puzzle(int n) {
return n*(n-1)*(2*n-1)/6;
}
}
If have the following code I correctly get an warning in eclipse at the else if code :
final int x = 8;
if (x < 10) {
System.out.println(x);
} else if (x < 5) {
System.out.println(x);
}
But I don't get any warning if I replace the line
final int x = 8;
with
final int x = getX();
getX() is defined somewhere.
What is the reason for this?
JVM knows that x always would be less than 10 in compile-time, but if you replace x declaration
final int x = getX();
JVM will know x value to compare only in runtime
Related questions:
Unreachable code error vs. dead code warning in Java under Eclipse?
final int x = 8;
if (x < 10) {
System.out.println(x);
} else if (x < 5) {
System.out.println();
}
Here you declared value as 8.
so if will execute.There is no possibility to execute else.
But in second case first we dont know the value.In runtime only it know.
if you write final int x = 8; the compiler knows for sure that x < 10 and the if branch is always executed, while in the second case it cannot know the value returned by the called function.
At compile time, the compile know that x will always be 8. But if you use a function, it doesn't drill down into that.
A final primitive is a compile time constant, so it can do the unreachable code check when compiling. In this case, the compiler knows x = 8 and can determine the results of the if statement accordingly.
For the getX() approach, it won't do that check at compile time. This means you won't see that warning.
if (8 < 10) {
//Executing code
} else {
if (8 < 5) {
//Alternative code
}
}
I believe this is the essential equivalent of how your code is read by the compiler (someone with more knowledge than I may be able to correct me. Scratch that, I'm certain they can correct me).
With that said if you look at the logical sequence of your steps, you'll see that the compiler has already determined the steps of execution and can determine that the second if is never satisfied. If you use getX() alternatively though the compiler cannot make those assumptions.
If this holds
x<5
Then this also holds
x<10.
Therefore, the second part will never execute even the value in x is unknown.
So, I have to make a random number generator to get numbers ranging from 0 to 400. I'm putting these into an array and then sorting them later on. I just am not sure how to go about doing this. I was given something along the lines of;
public int nextInt(400) //gives me errors
{
random.setSeed(12345L);
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
}
I've already called the random class, since the directions indicated that. I just don't know why this is not working. It's giving me errors especially with the first part; class, interface, or enum expected. Could somebody steer me in the right direction please?
Functions in Java (all programming languages) have "variables" in their definition.
You've got:
public int nextInt(400)
Over here, you want your 400 to be a value that is passed to the function.
Think of this as math. I'm sure you've dealt with something like f(x) = 2 * x. Here, x is the variable, and you "evaluate" f(x) with a value for x. Similarly, in programming, we'd have something like :
public int nextInt(int x)
As you see, our function defines x to be of type int. This is necessary in a language like Java because you're telling the compiler that this function will only accept integers for x.
Now that you've done that, you can use x as a variable in the body of your function.
Note that whenever you use a variable, it first has to be defined. A line such as:
int variable;
defines variable as an int.
Your program is missing these for random, val, arr, and a. Note here that arr and a are arrays (and somehow I get the feeling that they should not be two separate variables).
You should really brush up on variables definitions, arrays, and functions before attempting this question. Your best resource would be your textbook, because it'll explain everything in an organized, step-by-step manner. You can also try the many tutorials that are available online. If you have specific questions, you can always come back to StackOverflow and I'm sure you'll find help here.
Good luck!
You need to define this function within a class definition
even you have specified :
public int nextInt(400)
in this line function returns int and in your whole body u didn't have any return statement.
and yes as Kshitij Mehata suggested dont use 400 directly as value use variable over there.
this should be your function:
public int[] nextInt(int x) //gives me errors
{
random.setSeed(12345L);
int[] a=new int[arr.size];
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
return a;
}
even there is some issue with arr from where this arr come?
I wrote a 'setX' method in Java that says that if x value ( (x,y) ) is negative, the value of x wont be change, and the main() will continue as usual.
void setX (int num)
{
if (num < 0)
break;
else
{
_x = num;
}
}
Am I right ?
I am not sure because of the break issue, is the break statement just break from the current method ?
thnx
break is used only in loops (while, for).
If you want to exit the method, use return instead.
Perhaps you meant
public void setX(int x) {
if (x >= 0)
_x = x;
}
you should use return. break is to break loops.
Use return; here. break is used to break out of loops.
According to the Java tutorial, break is for use with switch, for, while, and do-while loops. It doesn't go in if statements. For a switch the break keeps the switch from falling through to the next case, which it would otherwise do. For loops it stops looping regardless of the loop guards.
A break statement can either be unlabeled, in which case it goes to where control would normally resume after the switch or loop, or labeled, in which case it goes to the label (almost as if it were a goto with strict constraints on where it can come from).
To get out of the current method, use return. A return with no value is the proper statement to leave a void method.
That looks like it should work, but the break really isn't doing anything anyway. why not just if(num>=0) _x = num;
I think your intention might be a bit clearer if your logic was reversed;
void setX (int num)
{
if (num >= 0)
_x = num;
}