Using negation of equals method [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 9 years ago.
Improve this question
I'm trying to set up a while loop as follows:
while(!data.equals("String");
Whenever I run this code, I get a NullPointerException.
Why is this?
If I change the code to:
while(data.equals("String");
I get no such exception, so there must be data in data, correct?
EDIT: Adding real code at the behest of commentors.
The following code is a method that attempts to convert infix notation into postfix notation.
public static Queue infixConvert (LinkedListTest infix){
Stack stack = new Stack();
Queue postfix = new Queue();
while(infix.head.data != "EOF"){
if(isNumber(infix.head.data)){
postfix.insert(infix.head.data);
System.out.println("Insert Queue");
System.out.println("Operator");
}
else if (infix.head.data.equals("(") || infix.head.data.equals(")")){
if(("(").equals(infix.head.data)){
stack.push(infix.head.data);
System.out.println("Open paren");
}
else {
infix.delete(")");
while(!"(".equals(stack.head.data)){
stack.delete(")");
postfix.insert(stack.pop());
System.out.println("Insert Queue");
}
stack.delete("(");
System.out.println("Close Paren");
}
}
else{
if(!(highPrec(stack.head.data, infix.head.data))){
stack.push(infix.head.data);
System.out.println("Push onto Lesser Operand");
}
else if(highPrec(stack.head.data, infix.head.data)){
while(stack.head.data != null){
if (stack.head.data != "("){
postfix.insert(stack.pop());
}
else break;
}
stack.push(infix.head.data);
System.out.println("Push onto Greater Operand");
}
if (infix.head.data == "EOL"){
while(stack.head.data != "EOL"){
postfix.insert(stack.pop());
System.out.println("End Line");
}
}
}
System.out.println(infix.head.data);
infix.head = infix.head.next;
System.out.println("loop\n");
}
return postfix;
}
}
EDIT: Added stack trace
at Calculator.infixConvert(Calculator.java:57)
at Test.main(Test.java:7)

You could do it "Yoda-style":
while(!"String".equals(data)) {
//writing code here you must!
}
because for the case data is null then it would not cause NPE because you call equals method of the "String"

I have resolved the issue.
There was some other unintentional behavior that caused the "(" String to be removed from the stack, so when the while loop ran it would run through the entire stack until it hit null, and provided me with a NPE.

Related

Does print statement in java effect any variables (without using increment)? [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 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.

Number Format Exception occuring, try catch throwing exception? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
I am having an issue with this part of the method. The program is supposed to pass arguments, which in my binaryToDecimal method it does just fine. But everytime this method, the decimalToBinary attempts to pass the value of 5 to binary, it tells me the Number Format Exception occurs and it doesn't do the calculation. Anything I could try to avoid this from happening?
public static String decimalToBinary(String decimalString) {
int decimal = 0;
try {
decimal = Integer.parseInt("decimalString");
}catch(NumberFormatException e){
System.out.println("Number format exception occured");
}
String answer = "";
while(decimal > 0) {
answer = decimal%2+answer;
}
return answer;
}
Your issue is in here decimal = Integer.parseInt("decimalString");
you should used your parameter decimalString
instead of this decimal = Integer.parseInt("decimalString");
try using this decimal = Integer.parseInt(decimalString);

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

Java LinkedList problems [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 9 years ago.
Improve this question
Error :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
at java.util.LinkedList.get(LinkedList.java:474)
at InterfacePackage.Main.main(Main.java:116)
Java Result: 1
Code (shortened) :
if(input.length() > 0)
{
if(command.size() == 1)
{
switch(command.get(0).toLowerCase())
{
case "exit":
case "qqq":
active = false;
break;
default:
System.out.println("invalid input, for complete list of commands enter 'help'...");
break;
}
}
else if(command.size() > 1)
{
if(command.get(0).equalsIgnoreCase("shutdown") && command.size()==3)
{
Shutdown shutdown = new Shutdown();
shutdown.Start(command);
}
else if(((command.get(0).equalsIgnoreCase("scan")
&& command.get(1).equalsIgnoreCase("ips"))
|| command.get(3).equalsIgnoreCase("/e"))
&& (command.size()>=2 || command.size()<4))
{
SystemsIPs sips = new SystemsIPs();
sips.Start(command);
}
else
{
System.out.println("invalid input, for complete list of commands enter 'help'...");
}
}
}
The error occurs when the users enters two string within a line that doesn't exist in the else if(command.size() > 1) loop.
For example, if the user would enter : hello world the program produces this error.
So this is a program that does various things based on user input to a console. I've been getting this error and and wanting to know what is causing it. I know I can just catch it, but I really want to know what causing this error.
Your error seems to be caused by
command.get(3).equalsIgnoreCase("/e"))
There is no index 3. Check if that index exists first, before you do that.
You're getting an IndexOutOfBoundsException as it says, and it occurs when you're trying to access a position in a collection/array and that position is empty, you're trying to access to an index that doesnt exist. If you don't want that to happen then force the program to use an Collection with a size more than 3 element.
The problem is in this line:
else if(((command.get(0).equalsIgnoreCase("scan") &&
command.get(1).equalsIgnoreCase("ips")) ||
command.get(3).equalsIgnoreCase("/e")) &&
(command.size()>=2 || command.size()<4))
You are using command.get(3) to retrieve the 3rd element of the LinkedList, but it's not guaranteed that there are at least 3 elements in the list.
So you'd better add a condition command.size() >= 3 before command.get(3).
Ok so here is how I solved the problem :
else if((command.get(0).equalsIgnoreCase("scan") && command.get(1).equalsIgnoreCase("ips")) && (command.size()>=2 || command.size()<4))
So I removed the
|| command.get(3).equalsIgnoreCase("/e"))
... from the code entirely, and improved the case in the separate class that this if statement directs to.
Here is what I did in the separate class...
if(command.size()==3 && command.get(2).equalsIgnoreCase("/e")) { }
else if(command.size()==2) { }
And it works (:

Can someone explain this syntax error with my if loop? Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
if(check !=0){
if (wee[i]>wee[i+1])
{
System.out.println("False");
check = 0;
else()
System.out.println("True!");
}
}
The Code snippet contains a nested if loop. The second set keeps returning "else without if" and i don't understand why. I've tried it with and without the parenthesis.
to be more clear: Why is the compiler returning an "else" without "if" error.
Change what you have to this:
if(check !=0){
if (wee[i]>wee[i+1])
{
System.out.println("False");
check = 0;
}
else
{
System.out.println("True!");
}
}
You were missing the closing paranthesis for the inner if statement.
Try:
if(check !=0)
{
if (wee[i]>wee[i+1])
{
System.out.println("False");
check = 0;
}
else
{
System.out.println("True!");
}
}
Or for fun:
System.out.println(wee[i] > wee[i+1] ? "False" : "True");

Categories

Resources