So well I'm just here wondering if there's a way to pass a variable through a statement. Something like this:
if (a < b) {
double g = 1
} else if (a > b) {
double g = 0
}
if (g = 1) {
System.out.print("true");
} else {
System.out.print("false");
}
Mainly saying, I want to set a variable if a statement is true or not, go to the next section of code and print out "true" or "false" and I pretty much am just wondering if this is possible without creating a new method (and of course if there is code for it).
Thank you.
You are almost there. You have to declare g outside the if statements, so you can access to it whithin the whole function. Read more about scopes, if you declare a variable inside a block {}, it will be accessible just inside it, so when you declared it into the if-else if blocks, you couldn't access to the variable outside.
Also to compare a primitive type (in this case double) you have to use == operator, because = is used for assignment.
double g;
if (a<b) {
g = 1;
}
else if (a>b) {
g = 0;
}
// What happen if 'a = b'?
if (g == 1) {
System.out.print("true");
}
else {
System.out.print("false");
}
Note: What value will take g if a == b? You may want to take care about that case too.
double g;
if (a<b) {
g=1
}
else if (a>b) {
g=0
}
if (g==1) {
System.out.print("true");
}
else {
System.out.print("false");
}
also make sure that you always use == instead of = in your if-statement
The if condition if (g=1) does not work with java. This would work with C though.
You should code if (g==1) to test if g is in fact equal to the int value 1.
You've got three problems.
a and b aren't defined. Define them before entering the if statement.
Define g outside of the if statement (a simple double g; will suffice), then set the values as part of your conditional logic. You do have to give it a default value if you intend to keep the else if there, since Java would complain about that not being defined.
g=1 isn't going to work the way you think it should; you probably mean g == 1.
With else if
int a, b; // assumed instantiated with values
double g = -1; // required since Java can't guarantee that the else-if will be hit
if (a<b) {
g = 1;
} else if (a>b) {
g = 0;
}
With else
int a, b; // assumed instantiated with values
double g; // instantiation not required since Java can guarantee the else case
if (a<b) {
g = 1;
} else {
g = 0;
}
double g; double a = 4.0; double b = 3.0;
if(a < b){
g = 1.0;
System.out.print("true");
}
else if (a > b){
g = 0.0;
System.out.print("false");
}
// Why not write your code like the above example. It seems like the
//same operations are executed but with less lines of code.
Related
In JavaScript you can add extra conditions like:
var b = 0.0;
var q = (void 0);
var e = -1.0;
while(q = e, b > 32.0){
console.log(q);
b++;
}
Meaning that q equals to e.
I have tried to rephrase Java code to
Float b = 0.0;
Float q = Float.NaN;
Float e = -1.0;
do{
q = e;
b++;
}while(b < 32.0);
But it seems that it doesn't work as JS version.
Can I just add q = e to while conditions? Is there any valid Java syntax for it?
There is no comma operator in Java, and even if there was, it would be considered bad style.
There are ways you can achieve similar things. If you define a function that takes any parameter and always returns true:
<T> boolean trick(T any) {
return true;
}
you can use it to sneak in assignment expressions in any boolean context you want:
while (trick(q = e) && b > 32.0){
System.out.println(q);
b++;
}
But again, this would be considered terrible style. Don't use this in a real project.
Java doesn't have a hyperflexible comma operator like JavaScript so you'll have to split the statements apart. That's not a bad thing. while(q = e, b > 32.0) is poor style.
Stick with a regular while loop. A do-while loop won't do because it'll always execute b++ at least once.
I would use double rather than float.
double b = 0.0;
double q;
double e = -1.0;
q = e;
while (b < 32.0) {
b++;
q = e;
}
And we might as well initialize q when it's declared:
double b = 0.0;
double e = -1.0;
double q = e;
while (b < 32.0) {
b++;
q = e;
}
I am working through hackerrank and I felt pretty solid about my code, but it doesn't work. Evidently, it has something to do with the way that I named the variables. Ultimately, the goal was to output the area of a rectangle if the area is positive, and if not,
System.out.println("java.lang.Exception: Breadth and height must be positive")
This was my code:
int B = scan.nextInt();
int H = scan.nextInt();
scan.close();
Boolean correct = (B > 0) || (H > 0);
if(correct){
int area=B*H;
System.out.print(area);
}
else correct = false;
System.out.println("java.lang.Exception: Breadth and height must be positive");
scan.close();
This is the code that actually works:
private static int B;
private static int H;
private static boolean flag;
static {
Scanner scan = new Scanner(System.in);
B = scan.nextInt();
H = scan.nextInt();
scan.close();
if (B <= 0 || H <= 0) {
System.out.println("java.lang.Exception: Breadth and height must be positive");
flag = false;
} else {
flag = true;}
I expected the input of negative integers to output the Breadth and height error, but instead it outputs
20java.lang.Exception: Breadth and height must be positive
Rather than using someone else's code (the second example), I would really like to fix my own code idea and understand the use of the static class better.
First, your condition should contain and AND not an OR. The input is correct if both the height and the width are positive.
Second, you have missed out braces after the else, so the println happens in all cases.
Also:
You don't need to use Boolean, you can use boolean.
You don't need to set correct to false after the else. In fact, you don't need it at all.
Your indentation is wrong. It is much harder to get your code right if it is not indented correctly.
Java variables should be lower case (b and h, not B and H).
Practice spending a bit more time reviewing your own code and learning how to debug it because these are very basic errors. It will help you a lot.
Your condition sould use && insteed of ||. Ans since you dont put {} to the else it only affect the correct = false; and not the print.err
int B = scan.nextInt();
int H = scan.nextInt();
scan.close();
Boolean correct = (B > 0) && (H > 0);
if(correct){
int area=B*H;
System.out.println(area);
} else
System.err.println("java.lang.Exception: Breadth and height must be positive");
scan.close();
You have several problems in your code:
(B > 0) || (H > 0) This condition should use AND instead of OR: (B > 0) && (H > 0)
You forgot curly brackets at your "else" part of code.
Do not "throw exceptions" that way. It's hmm... weird.
This is what you want to do:
if (correct) {
int area=B*H;
System.out.print(area);
} else {
correct = false; //as long as your're throwing exception in this block, this assignment is redundant
scan.close();
throw new Exception("Breadth and height must be positive");
}
P.S. Also to mention. You probably do not want to use a static block to put your code into. Use methods instead. Something like: public int getSquare() { } and place your code inside.
Consider the following method:
void a ()
{
int x;
boolean b = false;
if (Math.random() < 0.5)
{
x = 0;
b = true;
}
if (b)
x++;
}
On x++ I get the "Local variable may not have been initialized" error. Clearly x will never be used uninitialized. Is there any way to suppress the warning except by initializing x? Thanks.
No, there is no way Java can examine all possible code paths for a program to determine if a variable has been initialized or not, so it takes the safe route and warns you.
So no, you will have to initialize your variable to get rid of this.
There is one :
void a () {
if (Math.random() < 0.5) {
int x = 1;
}
}
The compiler isn't responsible for devising and testing the algorithm. You are.
But maybe you should propose a more practical use case. Your example doesn't really show what's your goal.
Why don't you simply use
void a ()
{
int x;
boolean b = false;
if (Math.random() < 0.5)
{
x = 0;
b = true;
x++;
}
if (b) {
//do something else which does not use x
}
}
In the code why do you want to use x outside the first if block, all the logic involving x can be implemented in the first if block only, i don't see a case where you would need to use the other if block to use x.
EDIT: or You can also use:
void a ()
{
int x;
boolean b = (Math.random() < 0.5);
if (b) {
x=1
//do something
}
}
You can and should be defining the value of x unconditionally if it will be used later in your code.
There are a few ways to do this:
On initialization
int x = 0;
Because this is outside the conditional (if), Java won't complain.
Add else clause to conditional
if (Math.random() < 0.5)
{
x = 0;
b = true;
} else
{
x = 1;
}
Because there is an else to this if, and both code paths initialize x, Java will also be happy with this.
Move your usage of the variable into the conditional block
Clearly the question has a minimally-reproducible example, not a full one, but if you only ever want to use the variable conditionally, then it belongs in the conditional block.
if (Math.random() < 0.5)
{
x = 0;
x++;
}
If you don't aren't conditionally using the variable, then you need to provide an integer value to use in case Math.random() >= 0.5, using one of the solutions above.
Just a declaimer:i am a beginner in java.
Write a method named numUnique that takes three integers as parameters and that returns the number of unique integers among the three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, the call numUnique(6, 7, 6) would return 2 because there are only 2 unique numbers among the three parameters: 6 and 7.
public int numUnique(int x,int y,int z){
if(x==y||y==z){
}
return 1;
else if(x!=y||y!=z){
}
return 2;
}
I am very confused about the relationship of if and return.I always put return inside if statement.But i dont understand why does it generate me an error message.if something is fulfil,i return in the loop.Why is it wrong.But on the other hand,the println statement can be put inside for loops.
Another issue,because this question,i tried to attempt using if else too.But my first condition is if and i return it.So after that i placed else if after the first return,it gives me error again.
I will appreciate someone will explain to me and i will alter the codes on my own.Please dont give me the full codes.Thank you.
Edited*
By the way,i read through all the comments and i finally understand it.This is my codes that i work out on my own(:
public static int numUnique(int x, int y, int z) {
if(x==y && y==z){
return 1;
}else if(x==y && y!=z || y==z && z!=x || x==z && y!=z ){
return 2;
}
return 3;
}
The return statements should be placed within the curly bracets.
To give you a clear understanding of "return" statements, i will say there can be only one return statement in one block of code i.e {...}.
"return" statement is used to return to the caller, and it has to be last statement of the block.
As suggested by you i am not providing you complete code, rather making you aware of usage of "return" statement.
In your code you are writing two "return" statements in one block.
i think you need to write return statements inside if-else blocks otherwise it will always return 1
The syntax for a what you want looks like this:
public static int numUnique(int x,int y,int z){
if(x==y||y==z){
return 1;
}else if(x!=y||y!=z){
return 2;
}
return 3;
}
Maybee this code ist better understandable:
public static int numUnique(int x, int y, int z) {
if (x == y && x == z && y == z) {
return 3;
} else if (x != y && x != z && y != z) {
return 1;
}
return 2;
}
Pseudocode If
if( condition ){
// do something if condition is true
}
Pseudocode If then else
if( condition){
// do something
}else{
// do something if condition is false
}
Pseudocode elseif
if( condition ){
// do something
}else if(condition2){
// do something, only if condition2 is true, if condition 1 is true, you never will be here
}else{
// do something, your only here if the two conditions above were false
}
A return statement, immidiently brakes execution ( there are some exception, exmaple: the finally block)
First, your return are outside the if statements, they should be inside. Because if you write:
if(Something) {
}
return 1;
Then 1 will be always returned because your if is empty. If you want to return 1 only if(Something) then write it inside the if body:
if(Something) {
return 1;
}
Second, your logic is not good. You need to check:
if x == y == z then they're all equal.
if x == y and x != z then you should return 2.
if x != y != z then you should return 0.
....
You need to cover all situations.
since if is a conditional flow, i may or may not run (depending on the condition),
but if your method has return type it should return in every cases. But in the later case, (if condition is false), it wont find any return.
so if you write
public int value(boolean flag){
if(flag){
return 0; //only reachable if flag is true, else value can not return from here
}
}
it is wrong, since if flag is false method wont return anything. so you must provide a return in else or after if block ends
using the fact that Sets store values only once...
public int numUnique(int x,int y,int z){
Set<Integer> number = new HashSet<Integer>();
number.add(x);
number.add(y);
number.add(z);
return numbers.size();
}
You have to put the return statement in the block from if and else:
public int numUnique(int x,int y,int z){
if(x==y||y==z){
return 1;
}
else if(x!=y||y!=z){
return 2;
}
}
it fails because the compiler think, that you have not a return statement for the function in every path.
Your code is ill-formed:
And if-else statement is as following:
if { code }
else { code }
So, if and else blocks make a pair. But you have:
if (condition) { code }
code
else { code }
code
So, the code just above the word else breaks this pair, and else remains isolated, and thus your program is syntactically incorrect.
You "want" to do:
if (x==y || y == z) {
return 1;
}
else if (x != y || y != z) {
return 2;
}
Moreover, if a if (or else) block has only one line, you can erase the brackets:
if (x==y || y == z)
return 1;
else if (x != y || y != z)
return 2;
Even more, you algorithms isn't a solution to your problem, ¿how about 3 unique values?. You should check more situations (all diferents, all equals, or only one different).
In the following code I'd expect that it should not be necessary to initialise variables a and b in last else block, however the compiler does not like it.
import java.util.Random;
public class Foo {
private void foo () {
double a,b;
boolean c;
double r = (new Random()).nextDouble();
if(r < 0.25) {
a = 1;
b = 2;
c = true;
} else if(r >= 0.25 && r < 0.75) {
a = 3;
b = 3;
c = true;
} else {
// why is it necessary to init a and b here?
// given that c is set to false
c = false;
}
if(c) {
double k = a + b;
}
}
}
With the code above, the compiler does complain.
bash-3.2$ javac Foo.java
Foo.java:25: variable a might not have been initialized
double k = a + b;
^
Foo.java:25: variable b might not have been initialized
double k = a + b;
^
2 errors
I would have thought that the compiler could do the static analysis to figure out that k will not be evaluated if c is set to false. So my question is why does the compiler demand that I initialise a and b?
The compiler isn't smart enough to understand that going through the else block will set c to false, and that the next if block thus won't ever be executed. The static analysis is more limited than what you expect, which also makes the comilation faster/
And it's probably a good thing, because changing the code of the else block would suddenly make the next if block not compilable, which would be annoying.