Does print statement in java effect any variables (without using increment)? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I was trying out the leetcode problem here
the code i wrote is
public int toLeaf(TreeNode j){
int ans=1;
try{
ans= Math.max(toLeaf(j.left),toLeaf(j.right))+1;
}catch(Exception e){
}
return ans;
}
public int diameterOfBinaryTree(TreeNode root) {
return toLeaf(root);
}
which gave me wrong answer but as soon as added a print statment i got correct answers on the sample testcases
public int toLeaf(TreeNode j){
int ans=1;
try{
ans= Math.max(toLeaf(j.left),toLeaf(j.right))+1;
}catch(Exception e){
}
System.out.println(j.val+" "+ans); //here
return ans;
}
public int diameterOfBinaryTree(TreeNode root) {
return toLeaf(root);
}
what is the reason behind this?
here is the screenshot
rejected

The printing is not the cause of the different behaviour but the access of j.val is.
If you had proper null-checks in your code, e.g. if (j == null) { return 0; } in the beginning of the method this would not happen.
In the first snippet if you call the method with j = null you get an NPE in the try, catch it, ignore it and then return 1. The caller will get the 1, add 1 and then return 2.
In the second snippet if you call the method with j = null you once again get an NPE in the try, ignore it, then continue to the print which raises another NPE which is then thrown from the method and the recursive caller will catch it and not perform the ans = ... + 1 successfully but simply return 1.
Therefore you have a different behaviour between the two snippets. But this is entirely unrelated to printing itself.

Related

Java how to stop if statement continuation after a condition is met? [closed]

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 1 year ago.
Improve this question
This is my first question on this site. If it's not appropriate here, I'd like a link to a better place to ask it (please).
I have a big chain of if statements that all execute even when I print an error message beforehand when a certain condition is met. How do I stop the rest from executing when if (myVar >= 0) is true?
Ok, here's a small example (I basically want the code to stop if "error" happens, sorry if there's too little that it doesn't make sense):
public static void main(String[] args){
int num = Integer.valueOf(args[0]);
int bigN;
String answer;
if (num>=0)
System.out.println("error");
bigN = num*20;
if (bigN>=80){
answer = ("something");
}
else
System.out.println("args[0] is " + answer)
It sounds like you just need to put a return statement.
If all of these are in your main loop, I would say pull them out into another module, like a method or function that is performing checks, and import it back in.
But you can set multiple returns. The method you are running will stop on the first return it hits.
I think you can stop or avoid the rest of process with one of them examples
1 Adding else statement in if
with else when
if(...){
// if pass here wont pass in next ones
}else if( ... ){
// if pass here wont pass in next ones
}else{
// it has passed because didn't pass in none of previous
}
2 Return value on method and exit from function
public String methodReturnString(...){
if(...){
return ""; // will return value to method and wont run next if
}
if(...){
return ""; // will return value to method and wont continue the rest of method
}
}
3 Return void on method and exit from function
the same last one but only exit method
public void methodWithNoReturn(...){
if(...){
return; // will return and wont run next if
}
if(...){
return; // will return and wont continue the rest of method
}
}
4 exit on throwing error
public void someMethod(...) throws RuntimeException{
if(...){
// if pass here will exit from method but will throw error to be handled in other method
throw new RuntimeException("some error);
}
}

Projekt Hangman game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a beginner in Java and I am working right now with a small projekt, a hangman game. One of the functions I am working on right now is a method where it takes a char input, check if the input is already added to the list or not, if it is, a message will show up saying "You have already used that character!" and the user will have to guess again, otherwise the input will be added to the list. My issue right now is that nothing is happening, inputs are not added to the list at all.
This is what I have done so far:
Any advice/help would be appreciated!
public static ArrayList<Character> getGuesses(ArrayList<Character> allGuesses, char input){
for (int i = 0; i < allGuesses.size(); i++) {
if (allGuesses.get(i) == input) {
System.out.println("You have already used that character!");
}else {
allGuesses.add(input);
}
}
return allGuesses;
}
You are adding the input character on each iteration as you search the collection. You should only add it after you have searched the collection and not found it.
for (int index = 0 ; index < allGuesses.size() ; ++index) {
if (allGuesses.get(index) == input) {
System.out.println("You already used that character!");
return allGuesses;
}
}
allGuesses.add(input);
return allGuesses;
However, this can be simplified by using the Collection contains method such that you do not employ a loop.
if (allGuesses.contains(input)) {
System.out.println("You already used that character!");
return allGuesses;
}
allGuesses.add(input);
return allGuesses;
If possible, consider switching the type of allGuesses to a Set implementation (e.g. HashSet). A Set seems to better match how you are using your collection and allows you to reduce this method to...
if (! allGuesses.add(input)) {
System.out.println("You already used that character!");
}
return allGuesses;

How can i get my PrimeNumber generator to work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I tried to write an primenumber generator. The method calcall() should return prime numbers (2,3,5,7...). Unfortunately I get the error, that the method doesn't returns an integer, wich I don't understand. Here is my code:
package primenumber;
public class primecalc {
public static int calcall(int a) { //actual generator
int konstante = a; //is this number a prime num?
int divisor = a-1; //divisor
int var1 = 0; //variable = 0
while(divisor>1) {
int quotient = konstante%divisor; //calc modulo
if(quotient == 0) { //if modulo==0 switch var1 to
var1++; //1 -> no primenumber
break; //stop calculating
} else { //else keep calculculating
divisor--; //until divisor <= 1
}
}
if(var1==0) { //if var1 still 0;
return konstante; //is a primnumber ->
} //return konstante
}
public static void main(String[] args) { //main function
int number = 3; //start with 3
while(True) { //(i'll add 2 manually)
System.out.println(calcall(number)); //print the prime number
number++; //increase number by one
}
}
}
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type int
at primenumber/primenumber.primecalc.calcall(primecalc.java:5)
at primenumber/primenumber.primecalc.main(primecalc.java:28)
What is wrong?
The gray lines on the code you posted are being ignored by the compiler.
The use of /* and */ makes everything between these seen by the compiler as comments. And that is why those lines are grayed out. If you want to comment on the same line as the code, I'd advise you to use //.
Also, it is common practise to use multi-line comments only to describe functions and place them just above the header of the function. Any other comments should be short, concise and describe functionality. Good variable names and well written code should do most of the explaining, and single line comments should be used when it's a bit harder toperceive what's going on.
Cheers

error: the left-hand side must be a variable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Eclipse is giving me the error "The left-hand side must be a variable" at this part of my code:
else
{ for(int i=0; i>=cellphoneArr.length; i++)
{if (cell_1.equals2(cellphoneArr[i]))
System.out.println(cellphoneArr[i]);
else
(cell_1.equals3(cellphoneArr[i])); ---> this is the error
System.out.println(cellphoneArr[i]);
}
The method equals3 is the following:
public boolean equals3(Cellphone phone)
{ if (brand.equals(phone));
}
I've been trying to figure this one out, but the way I invoked my two other methods equals 1 and 2 both worked with the object cell_1.
Try it as:
else
{ for(int i=0; i>=cellphoneArr.length; i++)
{if (cell_1.equals2(cellphoneArr[i]))
System.out.println(cellphoneArr[i]);
else if(cell_1.equals3(cellphoneArr[i]))
System.out.println(cellphoneArr[i]);
}
and the method equals3 must return a boolean values as:
public boolean equals3(Cellphone phone)
{ if (brand.equals(phone))
return true;
else
return false;
}
Remove ; at the end of else, Just like you did for if.
else(cell_1.equals3(cellphoneArr[i]));
^
Return a Boolean value from you function, instead of if
public boolean equals3(Cellphone phone)
{
return (brand.equals(phone));
}
You need to add an if:
else if (cell_1.equals3(cellphoneArr[i]))
You need an if following the else
EDIT
The code should be
if (cell_1.equals2(cellphoneArr[i])) {
System.out.println(cellphoneArr[i]);
} else if (cell_1.equals3(cellphoneArr[i])) {
System.out.println(cellphoneArr[i]);
}
Formatting allows you to pin point these kind of errors easily. If you are using Eclipse, do ctrl + shift + f

Recursive grep with good efficiency

This question is very specific to me, so I cannot find related questions on Stack Overflow. So, I'm coding a grep shown below. I am confused on the stringindextoutofboundexception. The reason for that is because I am checking whether it is equals to \0. That means I am handling the out of bound exception, no?
Example:
grep("hello","llo");
This will return 3. That is because its start matching at original[2] which is position 3. However, I am encountering an out of index error. I've spent hours and I can't figure it out.
public static int grep(String ori, String ma){
int toReturn = 0;
int oCounter = 0;
int i = 0;
while (i < ma.length()){
if (ori.charAt(toReturn) == ma.charAt(i)){
i++;
if (ma.charAt(i) == '\0'){ // error on this line
return toReturn;
}
toReturn++;
if (ori.charAt(toReturn) == '\0'){ // and this line if i delete the section above.
return -1;
}
} else {
i = 0;
toReturn++;
}
}
return -1;
}
You're getting an StringIndexOutOfBoundsException because you increment i inside the loop at a too early and wrong stage.
Checking for \0 is a C++ thing. Strings in java are not \0 terminated.
What you're writing is already done in the String class. There are several methods available.
System.out.println("hello".indexOf("llo"));
will print 2 because it's been found and starts at index 2. Feel free to add 1 if you dislike the starting at 0 for some reason.
You also ask "that means I'm handling the exception, no?". No, it doesn't. Exceptions are handled with a special syntax called try-catch statements. And example:
try {
// possibly more lines of code here
do_something_that_might_cause_exception();
// possibly more lines of code here
} catch (Exception e) {
// something did indeed cause an exception, and the variable e holds information about. We can do "exceptional" handling here, but for now we print some information.
e.printStackTrace();
}

Categories

Resources