String cause NullPointerException [closed] - java

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 9 years ago.
This is my code. I just read file that have lines first is number then lines as string their number equal the number in first line.
import java.io.*;
import java.util.*;
class groupmember
{
int recieving;
int giving;
String name;
groupmember()
{
recieving=0;
giving=0;
//name=null;
}
public void setname (String Title)
{
this.name = new String(Title);
}
public void setrecieving(int val)
{
recieving=val;
}
public void setgiving(int val)
{
giving=val;
}
public String getname()
{
return name;
}
public int getrecieving()
{
return recieving;
}
public int getgiving()
{
return giving;
}
}
class gift1 {
/**
* #param args
*/
public static void main(String[] args) throws IOException{
BufferedReader f=new BufferedReader(new FileReader("gift1.in"));
PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter("gift1.out")));
StringTokenizer st=new StringTokenizer(f.readLine());
int NP=Integer.parseInt(st.nextToken());
int excpectedgived=0,div=0;
groupmember []groupmember=new groupmember[NP];
for(int i=0;i<NP;i++)
{
st=new StringTokenizer(f.readLine());
String name=st.nextToken();
groupmember[i].setname(name);
System.out.println(name);
}
out.close();
}
}
The problem arises on this line:
groupmember[i].setname(name);
It causes NullPointerException. I want to know why this happens.

An array of reference type variables is filled with null entries after initialization. You need
groupmember[i] = new groupmember();
before you can do:
groupmember[i].setname(name);
In future, please follow the Java Naming Conventions and have your classes start with an uppercase letter, like GroupMember (even CamelCase).

groupmember[i] is never defined, you need to add
groupmember[i] = new groupmember();
or something like that at the start of your cycle.

You have just initialised the array of type groupmember, now all the values in the array are null, in order to start using the array, you need to do .
groupmember[i] = new groupmember();

Do this: String name = ""; String have default value null if they are not initialized.

Related

How to parse Bank information into particular format, plus java questions

Doing a java assignment in CSE 205 at ASU, and I'm having a hard time understanding parsing. I've looked through our online textbook, and parsing rarely comes up and it's never given a full explanation. I've looked through the java api documentation a few times and I never understand what it's saying, so I hope someone isn't too frustrated as to explain how to do it.
The class is:
BankParser
The BankParser class is a utility class that will be used to create bank objects from a string. The BankParser class cannot be instantiated. It has the following method:
public static Bank bankParser(String lineToParse)
The bankParser method's argument will be a string in the following format:
bankName/bankID/city,state
A real example of this string would be:
Bank Arizona/10001/Phoenix,AZ
The bankParser method will parse this string, pull out the information, create a new bank object, set the attributes of the object, and return it.
So far this is my setup:
public class BankParser {
public static Bank bankParser(String lineToParse) {
}
}
Also, in my Bank class I have this toString method:
public String toString() {
String printInfo = ("\nBank name:\t" + bankName + "\nBank ID:\t" + bankID + "\nBank address:\t" + bankAddress + "\n");
return printInfo;
It gives me 2 markers in eclipse: that this overrides java.lang.Object.toString, and that the return type is missing. What does this all mean?? The return type is String, I don't see what the problem is with that, but the override I'm clueless
EDIT; This is what I've come up with for bankParser
public static Bank bankParser(String lineToParse) {
String[] returnValue = lineToParse.split("/");
Bank temp = new Bank();
temp.setbankName(returnValue[0]);
temp.setbankID(returnValue[1]);
temp.setbankAddress = (returnValue[2]); //this one won't work, see below
return temp;
}
}
And THESE are the methods in Bank and Address that apply to bankParser
public void setBankName(String bank1) {
bankName = bank1;
}
public void setBankID(String bankID1) {
bankID = bankID1;
}
public void setBankAddress(String city, String state) {
bankAddress.setCity(city);
bankAddress.setState(state);
}
In Address.java:
public void setCity(String city1) {
city = city1;
}
public void setState(String state1) {
state = state1;
}
I would use library like Apache Common CSV for reading and writing.
Reader in = new StringReader("bankName/bankID/city,state");
Iterable<CSVRecord> parser = CSVFormat.newBuilder()
.withDelimiter('/')
.parse(in);
for (CSVRecord csvRecord : parse) {
...
}
Your bankParser method is empty. It needs to return a Bank object, and Java will complain until you do this. You could always have it return null for now til, make it at least a compilable stub you figure this out:
public static Bank bankParser(String lineToParse) {
Bank returnValue = null;
// TODO: create a Bank object, assign to returnValue
return returnValue;
}
As for your override bit, are you getting an error message? Or a warning? The code you've posted seems kosher, so it should compile. Please show the actual full message.
As for your actual parsing, I'd use String#split("/") to split the lineToParse into an array of tokens and then work with each token, create arguments for a Bank constructor call and create a Bank object.
i.e., code to show the concept:
String text = "Bank Arizona/10001/Phoenix,AZ";
String[] tokens = text.split("/");
System.out.println(java.util.Arrays.toString(tokens));

Trouble Passing an Array to an Arraylist [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Ok, so I have an assignment where we must create a java program which asks the user a contacts' name and and a variable amount of the numbers and number types(work, voip..) associated with the contact. The toString() method is suppose to print the contacts name and associated numbers and number types.
Am I passing my Array correctly from my main method to the phoneBookEntry constructor correctly? ( I know there are compile errors, etc, but I want to make sure I am passing the Arrays correctly. Also, is my approach correct?
Suppose to follow UML table accordingly here:
Phone book entry
name : String
phoneNumbers : String[]
phoneTypes : String[]
PhoneBookEntry()
PhoneBookEntry(nam : String) :
PhoneBookEntry(nam : String, numbers : String[], types : String[]) :
getName() : String
setName(nam : String) : void
getPhoneNumber(type : String) : String
setNumbers(numbers : String[], types : String[]) : void
toString() : String
Thanks!
Here is what I have so far:
package phonebookentry;
import java.awt.List;
import java.util.*;
public class PhoneBookEntry
{
private String name;
private String[] phoneNumbers,phoneTypes;
/**
* #param args
*/
public PhoneBookEntry()
{
}
public PhoneBookEntry(String nam, String[]numbers, String[]types)
{
phoneNumbers = numbers;
name = nam;
phoneTypes = types;
toString();
}
public String getName()
{
return name;
}
public void setName(String nam)
{
}
public String[] getPhoneNumber(String type)
{
return phoneTypes;
}
public void setNumbers(String[] numbers, String[] types)
{
this.phoneNumbers = numbers;
this.phoneTypes = types;
}
public String toString()
{
for (int index = 0; index < phoneNumbers.length; index ++ )
return System.out.println(nam, this.phoneNumbers, this.phoneTypes) ;
}
public static void main(String[] args)
{
String phoneN = "0";
ArrayList<String> Ptypes = new ArrayList<String>();
ArrayList<String> Pnumbers = new ArrayList<String>();
while (!phoneN.equals("-1"))
{
String phoneT;
Scanner input = new Scanner(System.in);
// Create an ArrayList to hold some names.
System.out.println("Phone number of Contact: (Input -1, to end)");
phoneN = input.nextLine();
if (phoneN.equals("-1"))
break;
Pnumbers.add(phoneN);
System.out.print("Type of phone number(mobile,home,VOIP,work,etc..):");
phoneT = input.nextLine();
Ptypes.add(phoneT);
}
String nam = "fas";
String[] types = Ptypes.toArray(new String[Ptypes.size()]);
String[] numbers = Pnumbers.toArray(new String[Pnumbers.size()]);
PhoneBookEntry passPhone = new PhoneBookEntry(nam,numbers,types);
passPhone.setNumbers(numbers,
types);
}
}
for (int index = 0; index < phoneNumbers.length; index ++ )
return System.out.println(index) ;
That returns nothing . println() returns void . Again , you are returning at the first iteration of the loop . You should construct a String and return it after the loop. Your public String toString() should return a String to avoid the compilation error.
Something like this :
public String toString()
{
StringBuilder str = new StringBuilder();
for (int index = 0; index < phoneNumbers.length; index ++ )
str.append(...) ; // append whatever you want to display
return str.toString();
}
The toString() method should concatenate out all the phone numbers(I presume)
#Override
public String toString() {
StringBuilder phoneBook = new StringBuilder();
//Generate comma separated entries of phone book
for (int i = 0; i < phoneNumbers.length && i < phoneTypes.length; i++ ) {
if (i > 0) {
phoneBook.append(',');
}
phoneBook = phoneBook.append(phoneNumbers[i])
.append(':')
.append(phoneTypes[i])
}
return phoneBook.toString();
}
Other comments
There is no point calling the toString() method in the constructor.
You should also check whether the lentgh of phoneTypes and phoneNumbers are equal in the constructor.
An empty constructor should be an empty phoneBook. By default the private fields are null. So the toString() method might blow up.
Separate get/set methods for phone numbers/types along with constructors are a bad choice. Instead keep a List where phone numbers could be added/deleted/updated. I guess that is the next assignment. Good Luck !

java.lang.nullpointerexception [closed]

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.
I have this problem with my code. Its called java.lang.nullpointerexception. and I cant seem to fix it. please help me take a look at it. Thank you. I didnt include the class name and import. class name is called CHORD. I didnt make public static since my assginemnt say dont use global variable.
private ArrayList<Integer> nodeList;
public static void main(String[] args){
CHORD obj = new CHORD();
obj.nodeList = new ArrayList<Integer>();
String filename ="";
if(args.length ==1){
filename = args[0];
obj.read(filename);
}
}
public void read(String file){
CHORD obj = new CHORD();
obj = null;
Scanner loadFile = null;
try{
loadFile = new Scanner(new File(file));
String inputLine;
while(loadFile.hasNextLine()){
inputLine = loadFile.nextLine();
String[] inputArray = inputLine.split(" ",3);
if(inputArray[0].equalsIgnoreCase("init")){
int size = Integer.parseInt(inputArray[1]);
setSizeFT(init(size));
}
else if(inputArray[0].equalsIgnoreCase("addpeer")){
System.out.println("adding");
nodeList.add(Integer.parseInt(inputArray[1]));
}
}
}
catch(FileNotFoundException x){
}
finally{
System.out.println(getFT());
loadFile.close();
}
System.out.println(getFT());
}
public void print(){
CHORD obj = new CHORD();
for(int x =0; x< obj.nodeList.size(); x++){
System.out.println(obj.nodeList.get(x));
}
}
public int init(int num){
int n = 23;
double k = Math.ceil(Math.log(n)/Math.log(2));
int size = (int)k;
return size;
}
public void setSizeFT(int size){
sizeFT = size;
}
public int getFT(){
return sizeFT;
}
}
Here's an explanation of what NullPointerException's are: http://antwerkz.com/dealing-with-nullpointerexceptions/ From the article:
The most common (and obvious to the seasoned developer) is that you didn't initialize a variable.
Looking at that line, it looks like obj.nodeList may be null. Here's how I deduced that:
I can see that obj is not null, because the first line is CHORD obj = new CHORD();. That means you didn't set obj to null.
I can tell that Integer is not null. That's a class and you're calling a static method. That can't be null because there's nothing to be assigned there.
inputArray[1] may return null, but if that were happening, your stack trace would not end on this line, it would probably end on some line inside Integer.parseInt. I'd need to see a full stack trace to be sure though. But looking at the javadoc of Integer.parseInt, it doesn't say it'll throw a NPE so that's even more evidence to rule it out.
If inputArray was null, you'd probably get the error on the first if statement so I can rule that out.
Somewhere your code needs to do a obj.nodeList = new NodeList() or something like that. I can't say for sure without seeing what the CHORD class looks like.

java, having a hard getting my print class to print my other class information, please help these are my codes [closed]

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.
// my first class
public class FirstProject{
int first_number;
public FirstProject(){
first_number = 0;
}
public FirstProject(int Fn){
first_number = Fn;
}
public void Print(){
System.out.println("First number = " + first_number); System.out.println();
}
}
//second class in a separate file
// keep getting an error on this class saying that cannot find the . in p1.print();
public class TestProgram {
public static void main(String[] args){
FirstProject p1 = new FirstProject(10);
p1.print(); System.out.println();
}
Java is case-sensitive:
p1.Print();
But better change
public void Print(){ -> public void print(){
Since methods should not start with a capital letter, according to conventions.
That is simply because you created it as public void Print and are calling it as print. Java is case sensitive ;)

Having trouble with "cannot find symbol" - Java [closed]

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.
I am receiving the following three cannot find symbol errors, and I am not sure why!
GrammerQueue.java:9: cannot find symbol
symbol : constructor GrammerStructure()
location: class GrammerStructure
public class GrammerQueue extends GrammerStructure implements StringQueue{
^
GrammerQueue.java:45: cannot find symbol
symbol : variable stack
location: class GrammerQueue
this.stack += tmpAr[i];
^
GrammerQueue.java:47: cannot find symbol
symbol : variable count
location: class GrammerQueue
this.count--;
^
3 errors
I got this error on another script and solved it by calling a new object of that type instead of directly calling the object my class creates. However, I'm not even trying to create an object yet! What can I do?
Here's the code:
import java.lang.*;
public class GrammerQueue extends GrammerStructure implements StringQueue {
private String queue = "";
private String structName;
// #override
public boolean offer(String item) {
if (item.length() == 0) // We don't accept empty Strings!
return false;
else if (this.queue.length() == 0) // If new queue, just add - no null.
queue = item;
else
// Append null and item for seperation.
queue += "\0" + item;
return true; // done.
}
// #override
public String[] asArray() {
// Splits the string at each null character and returns it as an array.
String[] array = this.queue.split("\0");
return array;
}
// #override
public void GrammerStructure(String structureName) {
this.structName = structureName;
}
// #override
public String take() throws EmptyException {
// If empty, throw errors.
if (this.queue.length() == 0)
throw new EmptyException(structName);
String[] tmpAr = this.asArray();
// Empties the stac now that we have it in a temp array.
this.queue = "";
// FIFO, so exclude first element in reconstruction.
for (int i = 1; i < tmpAr.length; i++)
this.stack += tmpAr[i];
// We made it this far without error, so reduce count.
this.count--;
// Return the first item.
return tmpAr[0];
}
// #override
public String peek() {
// Empty string check.
if (this.queue.length() == 0)
return null;
String[] tmpAr = this.asArray();
// Return the first item.
return tmpAr[0];
}
// #override
public int size() {
if (this.queue.length() == 0)
return 0;
String[] tmpAr = this.asArray();
return tmpAr.length;
}
// #override
public void clear() throws EmptyException {
// If empty, throw errors.
if (this.queue.length() == 0)
throw new EmptyException(structName);
else
this.queue = ""; // Empty now.
}
public void main(String args[]) {}
}
It looks like you don't have a stack and count variable. You need to declare and define them, and create getters and setters probably.
You need to import a package for GrammerStructure, assuming GrammerStructure is in a different package.
GrammerQueue extends GrammerStructure, which is a class that doesn't exist (AFAIK).

Categories

Resources