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 8 years ago.
Improve this question
I'm making a class involving objects. I'm having trouble with the retrieveMessage method, because when I test it, it returns a NullPointerException.
public class PostOffice
{
public PostOffice(int size)
{
boxbox = new Letter[size];
}
public boolean placeLetter(Letter mail, int boxNum)
{
if(((boxNum>(boxbox.length-1))||(boxNum<0))||(boxbox[boxNum]!=null))
return false;
else{
boxbox[boxNum]=mail;
return true;
}
}
/**Returns the message contained within the Letter located in the specific box number.
* Returns "Empty!" if the post office box specified by the integer does not contain a Letter.
* Returns "Box does not exist!" if there is no box with the specified integer.
* #param boxNum The post office box number to be checked.
*/
public String retrieveMsg(int boxNum)
{
if(boxNum<=boxbox.length-1)
{
String swag = boxbox[boxNum].getMsg();
if(swag!=null && swag.isEmpty()==false)
{
return swag;
}
return "Empty!";
}
return "Box does not exist!";
}
public Letter findSender(String name)
{
String sender;
int index =0;
for(int i = 0; i<boxbox.length; i++)
{
if((boxbox[i].getSender()).equals(name)){
index= i;
}
else{
return null;
}
}
return boxbox[index];
}
}
I guess the NullPointerException is thrown on this line :
String swag = boxbox[boxNum].getMsg();
When created, boxbox have size values, all of them are null.
You should first check if boxbox[boxNum] is null or not. If it is, it means that the post box does not contain a letter.
Related
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.
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 5 years ago.
Improve this question
(At time of posting, I do not have access to code, will add later)
I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.
When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.
This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.
So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you
static void employeeSort(Employee[] emply, int size)
{
int i;
Employee temp;
boolean flag = true;
while(flag)
{
flag = false;
for(i = 0; i < size; i++)
{
if (emply[i].getName().compareTo(emply[i+1].getName())>0)
{
System.out.println(emply[i].getName());
temp = emply[i];
emply[i] = emply[i+1];
emply[i+1] = temp;
flag = true;
}
}
}
}
On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.
public class Employee implements Serializable
{
int prefHours;
String name;
String avail;
Employee( String nam, int hours, String aval )
{
name = nam;
prefHours = hours;
avail = aval;
}
void prnEmpl()
{
System.out.print("Name: " + name);
System.out.println();
System.out.print("Prefered hours: " + prefHours);
System.out.println();
System.out.print("Availability: " + avail);
System.out.println();
}
String getName()
{
return name;
}
String getAvail()
{
return avail;
}
}
Without your code it is hard to figure out what's the problem. As far as I understand I think you should use java.util.PriorityQueue instead of Array.
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 5 years ago.
Improve this question
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package plaindromenumbers;
import java.util.Scanner;
/**
*
* #author taha
*/
public class PlaindromeNumbers {
/**
* #param args the command line arguments
*/
int func1(int n)
{
if(n==1)
return 1;
return n*func1(n-1);
}
static boolean check=false;
int func(int no)
{
String a=""+no;
String reverse = new StringBuffer(a).reverse().toString();
if(a.equals(reverse))
{
if(!a.contains("0"))
{
System.out.println("hey");
check=true;
return Integer.parseInt(a);
}
}
// else
// {
func(no++);
if(check==true)
{
return 0;
}
return 0;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner in=new Scanner(System.in);
System.out.println("Enter testcase");
int testcase=in.nextInt();
while(testcase>0)
{
int a=in.nextInt();
PlaindromeNumbers obj=new PlaindromeNumbers();
System.out.println(obj.func(a));
testcase--;
}
}
}
Here is the problem:
func(no++);
Let's say no is 32. This will pass 32 to func and then increment it. Which means that you are once again calling the function with a value of 32. And when that function hits this line, it will, once again, pass that 32 to func. Hence, an infinite recursive loop.
You can fix this bug like this:
func(++no);
Now it will increase no before calling func. no will be 33, it will match its reverse, and all will be well.
You will need to return func(no + 1), this way your code will return the next palindrome number (which I assume is what you want your code to do?). check is not needed. Why include func1 when it's not even used by your code?
By the way, the stack overflow is caused by the infinite recursion of func.
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
When I type nothing in the TextField which uses getText() method. What will be the value fetched.?
String s = jTextField1.getText();
if(s==null)
{
JOptionPane.showMessageDialog(null,"No Input");
}
Is the value null?
A JTextField with nothing it will typically return an empty String...
String s = jTextField1.getText();
if (s.isEmpty()) {...}
However, a JTextField may not always be completely empty and may contain spaces, if you it matters to you you can use...
String s = jTextField1.getText();
if (s.trim().isEmpty()) {...}
instead, for example
If you follow the source code of getText(), you will get to this method:
/**
* Retrieves a portion of the content. where + len must be <= length().
*
* #param where the starting position >= 0
* #param len the length to retrieve >= 0
* #return a string representing the content; may be empty
* #exception BadLocationException if the specified position is invalid
* #see AbstractDocument.Content#getString
*/
public String getString(int where, int len) throws BadLocationException {
if (where + len > count) {
throw new BadLocationException("Invalid range", count);
}
return new String(data, where, len);
}
in the class javax.swing.text.StringContent.
So the answer is: No. It won't return null. It will return an empty String.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
so i am trying to create an arraySet from only an array and array methods. I have the following piece of code that should find the index of the item chosen (i've included comments so you can understand what each method is supposed to do). As you can see the add method calls on the findIndex method before it can add the item. The problem i am having is that the findIndex method brings up an error (missing return value). How would i return just the int index of the item that the code finds? (the question marks in the code are just to show where i am stuck)
/** Find the index of an element in the dataarray, or -1 if not present
* Assumes that the item is not null
*/
private int findIndex(Object item) {
for(int i=0; i<data.length;i++){
if(data[i] == item){
return i;
}
}
return ???
}
/** Add the specified element to this set (if it is not a duplicate of an element
* already in the set).
* Will not add the null value (throws an IllegalArgumentException in this case)
* Return true if the collection changes, and false if it did not change.
*/
public boolean add(E item) {
if(item == null){
throw new IllegalArgumentException();
}
else if(contains(item) == true){
throw new IndexOutOfBoundsException();
}
else{
int index = findIndex(item);
if(index<0||index>count){
throw new IndexOutOfBoundsException();
}
ensureCapacity();
for(int i=count; i>index; i--){
data[i]=data[i-1];
}
data[index] = item;
count++;
return true;
}
}
If I'm understanding your question right it should just be this, the 'return i' accomplishes what you are asking, the return -1 is for the not found case:
private int findIndex(Object item) {
for(int i=0; i<data.length;i++){
if(data[i] == item){
return i;
}
}
return -1;
}
You've answered your own question, for the most part, in your comments. Which integer should be returned when the item can't be found? It can't be a valid value for something in the collection (think 0 <= x < list.size()).
A method that is declared to return a value must either return a value or throw an exception, no matter what. In the code you've written so far, you return a value only when you actually find what you're looking for. What should the method do when you don't find what you're looking for? It needs to return something then, too.
What is often done is to return a special value that couldn't possibly be an index. Hint: what kind of integers are never used as array indexes in Java? Return one of those. Then document this choice, and code that calls your method will have to check for this special return value to see if the item was found or not.
You should have the return i in the middle of your loop, as you currently have.
But you also need a return statement in case that if statement is never reached. Since your comment says you should use -1, you need a return -1 where you have return ???