Null Pointer Exception Error, not sure why - java

So I had to create a method that separated input string into first/middle/last names, counted the number of "students" created, etc, and then I had to create a class that tested those methods.
public void setName(String newName)
{
String[] nameInput = newName.split(" ");
if(nameInput.length == 0)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if(nameInput.length == 1)
{
firstName = nameInput[0];
middleName = "";
lastName = nameInput[1];
newName = firstName + lastName;
}
else if(nameInput.length == 2)
{
firstName = nameInput[0];
middleName = nameInput[1];
lastName = nameInput[2];
newName = firstName + middleName + lastName;
}
else
{
System.out.println("Error! You can only enter up to three names.");
}
}
public String getName()
{
if (middleName == null)
{
return firstName + " " + lastName;
}
else
return firstName + " " + middleName + " " + lastName;
}
public String getId()
{
return identifier = generateID();
}
#Override
public String toString()
{
return getName() + "\n" + "(" + generateID() + ")";
}
private String generateID()
{
return UUID.randomUUID().toString();
}
and this is the way I am testing the code:
public static void testStudent()
{
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
testStudent1 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
testStudent1 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
}
I keep running into a null pointer exceptions when it tests toString for a student with 2 names, and I have no clue why.

Edit: The issue is with the testStudent variable in the testStudent() method.
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
Student testStudent2 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
Student testStudent3 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
Since you are re-using the testStudent1 variable to create a new Object of Student class and not using them to invoke getter functions, it will throw an NPE for testStudent2 and testStudent3 variables.
Answer for old issue: The issue is with your while statement. It will never stop.
You can just find out the count by doing nameInput.length for the String array.
It should be like this:
String[] nameInput = newName.split(" ");
if (nameInput.length == 1)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if (nameInput.length == 2)
{
...
}
else if (nameInput.length == 3)
{
...
}
else
{
...
}

You could use StringTokenizer class to help you with this.
import java.util.StringTokenizer
StringTokenizer test = new StringTokenizer("An example string");
while (test.hasMoreTokens()) {
System.out.println(test.nextToken());
}
Output:
An
example
string.
The countTokens() method can provide how many tokens a string will provide prior processing. That way you will know if you have a middle name or not.

please check trim() method
public static void getName(String newName) {
newName = newName.trim();
String fullName = null;
String[] nameInput = newName.split(" ");
switch (nameInput.length) {
case 2:
fullName = mergeName(nameInput[0], "", nameInput[1]);
break;
case 3:
fullName = mergeName(nameInput[0], nameInput[1], nameInput[2]);
break;
default:
System.out.println("Error, please enter at least two names.");
break;
}
System.out.println(fullName);
}
public static String mergeName(String firstName, String middleName,
String lastName) {
String name = firstName+" " + middleName+" " + lastName;
return name;
}

Related

program printing extra null that I can't seem to get rid of

public class Student {
private String courses = null;
}
.....Some code here.......
//Enroll in courses
public void enroll() {
//Get inside a loop and user hits Q
do {
System.out.print("Enter Course to Enroll(Q to quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if (!course.equals("Q")) {
courses = courses + "\n " + course;
tuitionBalance = tuitionBalance + costOfCourse;
}
else{ break; }
}while ( 1!= 0);
}
......Some code here......
//Show Status
public String showInfo() {
return "Name: " + firstName + " " + lastName +
"\nGrade level: " + gradeYear +
"\nStudent ID: " + studentId +
"\nCourses Enrolled:" + courses +
"\nBalance: $" + tuitionBalance;
}
}
Everything seems to be running just fine. But there's an extra null printed after the Courses Enrolled that sticks out like a sore thumb. How could I get rid of it? I've tried setting the String variable courses to null and also without assigning but doesn't seem to affect the result
Name: Frank Kuo
Grade level: 1
Student ID: 11001
Courses Enrolled:null
Math101
Balance: $0
You can replace private String courses = null; with private String courses = ""; to get rid of the null.

Java: Accessibility problems with two methods in ArrayList (three classes)

I have three classes: Main,ReusaxCorp and Employee. Let's get straight to the point: In the ReusaxCorp class I want to implement two methods: retrieveEmployee, which iterates through the Array List and prints out all employees information. So I tried this:
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.grossSalary);
}
}
But that does not work, because I can't access - for instance - employee.ID or employee.name. In the second method. updateEmployee I would have liked to change the information, but that doesn't work either because of the accessibility. I appreciate any kind of help. Here are my three classes:
public class Employee {
protected String ID;
protected String name;
protected double grossSalary;
final String END_OF_LINE = System.lineSeparator();
public Employee (String ID, String name, double grossSalary){
this.ID = ID;
this.name = name;
this.grossSalary = grossSalary;
}
public double getGrossSalary() {
return grossSalary;
}
public void setGrossSalary(double grosssalary) {
this.grossSalary = grossSalary;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here's my Main class:
public class Main {
private static String END_LINE;
private Scanner sc;
public String name;
public String ID;
public double salary;
private int GPA;
private ReusaxCorp reusaxcorp;
public Main(){
sc = new Scanner(System.in);
END_LINE = System.lineSeparator();
}
public void presentoptions(){
while (true){
System.out.println("=== Welcome === ");
System.out.println("Choose an option below: ");
System.out.println(" ");
System.out.println("1. Register an employee. ");
System.out.println("2. Remove an employee. ");
System.out.println("3. Retrieve an employees information. ");
int option = sc.nextInt();
switch (option) {
case 1:
System.out.println("What type of employee? " + END_LINE
+ " - Intern. " + END_LINE
+ " - Employee. " + END_LINE
+ " - Manager. " + END_LINE
+ " - Director." + END_LINE);
String type = sc.nextLine();
createEmployee();
break;
case 2:
break;
case 3:
reusaxcorp.retrieveEmployee();
break;
default:
System.out.println("Error. Please try again.");
break;
}
}
}
public void createEmployee(){
String typeofemployee = sc.nextLine();
System.out.println("What's the ID of the new " + typeofemployee + "?");
ID = sc.nextLine();
System.out.println("What's the name of the new " + typeofemployee + "?");
name = sc.nextLine();
System.out.println("What's the salary of the new " + typeofemployee + "?");
salary = sc.nextDouble();
Employee employee = new Employee(ID, name, salary);
switch (typeofemployee) {
case "Intern":
System.out.println("What's the new Interns GPA? ");
GPA = sc.nextInt();
case "Employee":
break;
case "Manager":
break;
case "Director":
break;
default:
System.out.println("Error");
break;
}
}
public static void main(String[] args) {
Main runcode = new Main();
runcode.presentoptions();
}
}
And here at last the ReusaxCorp class.
public class ReusaxCorp extends Main {
ArrayList<Employee> employees = new ArrayList<Employee>();
final String END_OF_LINE = System.lineSeparator();
public void registerEmployee(){
employees.add(new Employee(ID, name, salary));
}
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.grossSalary);
}
}
public void updateEmployee(){
}
}
You are trying to access the variable employee which does not exist anywhere int the class.
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
//add this line
Employee employee = employees.get(i);
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.salary);
}
}
You can also use a for-each loop:
for(Employee employee: employees){
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.salary);
}
Also note that accessing the fields such as ID using employee.ID is only applicable if the classes are in the same package (being protected). Otherwise you need to create a getter and access them using getter such as employee.getID()
Use employee.getId() instead of employee.ID while iterating through the list of employees, you already have those public getter methods implemented while the class members are protected. Do so for the other class members (name and so on) as well…
You can do that in your solution by getting the employee from the list by index like
System.out.println(employees.get(i).getId());
or you just take a "for each" loop like
for (Employee employee : employees) {
System.out.println(employee.getId());
}

JAVA - Issues Printing ArrayList

I'm currently attempting to make a lottery program through the use of a GUI. I can not figure out why the method getTicketNumbers() is not returning anything. It is simply printing [].
And so too is:
String output = "Name: " + name + "\nNumbers: " + ticketNumbers + "\n\n";
tickNumbers is outputting [] but name successfully prints out the name.
I added a System.out.print to the Ticket class in the constructor to confirm the ArrayList is being passed successfully and it is:
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
The method toString is successfully printing the name but again, it is not printing the ArrayList called ticketNumbers.
private void enterLottoButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (nameInput.getText().equalsIgnoreCase("")) {
JOptionPane.showMessageDialog(null, "Please Enter Your Name", "Error", JOptionPane.ERROR_MESSAGE);
} else if (ticketNumbers.size() < 4) {
JOptionPane.showMessageDialog(null, "Please Enter Four Numbers", "Error", JOptionPane.ERROR_MESSAGE);
} else {
ticketList.add(new Ticket(ticketNumbers, nameInput.getText()));
JOptionPane.showMessageDialog(null, "You Successfully Entered! \n\nName: " + nameInput.getText() + "\nNumbers: " + ticketNumbers.toString());
ticketNumbers.clear();
numbersTextField.setText("");
nameInput.setText("");
numberOfPeopleLabel.setText(" People Entered: " + ticketList.size());
}
Ticket Class:
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
public class Ticket {
private String name;
private ArrayList<Integer> ticketNumbers = new ArrayList<>();
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
public String getName() {
return name;
}
public ArrayList<Integer> getTicketNumbers() {
return ticketNumbers;
}
public ArrayList<Integer> getSortedTicketNumbers() {
Collections.sort(ticketNumbers);
return ticketNumbers;
}
#Override
public String toString() {
String output = "Name: " + name + "\nNumbers: " + ticketNumbers + "\n\n";
return output;
}
}
If needed, code in its entirety:
http://pastebin.com/7i8VWQLk and http://pastebin.com/iRd49Nc7
ticketNumbers.clear()
This line cause the problem. As you said, during the construction of Ticket object, the data been passed in correctly in this line: ticketList.add(new Ticket(ticketNumbers, nameInput.getText()));. But you cleared them afterwards. You will need a clone of ticketList. Regardless of the best practice, you can do it inside Ticket class.
private List<Integer> clonedTicketNumbersList = new ArrayList<Integer>();
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
for(Integer ticketNum : ticketNumbers) {
clonedTicketNumbersList.add(ticketNum );
}
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
#Override
public String toString() {
String output = "Name: " + name + "\nNumbers: " + clonedTicketNumbersList + "\n\n";
return output;
}
It looks like you're copying the reference to the list, and so when you clear it in one place (or modify it) it changes/clears everywhere.
Try making a defensive copy. Like:
ArrayList<Integer> tickets = new ArrayList<>(ticketNumbers)

How to leave out a null value in a loop in Java

Here's my Java Code:
public class DVD {
public static void main(String[] args) {
DVD newdvd1 = new DVD();
newdvd1.setPlayit("The song is playing \n");
newdvd1.setArtist("Eva Cassidy");
newdvd1.setTitle("Songbird");
newdvd1.setGenre("Blues");
System.out.println(newdvd1.getPlayit());
System.out.println(newdvd1);
DVD newdvd2 = new DVD();
newdvd2.setPlayit("The next song is playing \n");
newdvd2.setArtist("an unknown artist");
newdvd2.setTitle("new song");
System.out.println(newdvd2.getPlayit());
System.out.println(newdvd2);
}
private String artist;
private String title;
private String genre;
private String playit;
public String getPlayit() {
return playit;
}
public void setPlayit(String playit) {
this.playit = playit;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String toString () {
return ("The artist is called " + artist +
" who is a "+ genre + " singer" +
" and this song is called " + title + ".\n");
}
}
what it outputs is:
The song is playing
The artist is called Eva Cassidy who is a Blues singer and this song is called Songbird.
The next song is playing
The artist is called an unknown artist who is a null singer and this song is called new song.
What i'm asking is, in the second song, how do i leave out 'null singer' as I don't want to display the second songs genre?
Use the ?: (ternary) operator. See JLS specs, for example.
return ("The artist" +
(artist == null ? "" : " is called " + artist) +
(genre == null ? "" : " who is a "+ genre + " singer") +
(title == null ? "" : " and this song is called " + title) +
".\n");
If the given property is not null, you print the relevant text, otherwise simply print nothing.
You can also define sensible default values like:
(artist == null ? " is unknown" : "is called " + artist) +
You can try this.
public String toString() {
StringBuilder builder = new StringBuilder();
if (artist != null && !artist.isEmpty()) {
builder.append("The artist is called : " + artist);
}
if (genre != null && !genre.isEmpty()) {
builder.append(" who is a " + genre + " singer");
}
if (title != null && !title.isEmpty()) {
builder.append(" and this song is called " + title + ".\n");
}
return (builder.toString());
}
If you want the solution to be generic for then modify your toString method as:
public String toString () {
String returnString = "The artist is called " + artist ;
if(genre !=null && !"".equals(genre.trim())) {
returnString += " who is a "+ genre + " singer" +;
}
returnString += " and this song is called " + title + ".\n";
return returnString;
}
You can add more null checks if required for artist and title as well.
You should override toString() using some condition
public String toString () {
if(genre!=null){
return ("The artist is called " + artist +
" who is a "+ genre + " singer" +
" and this song is called " + title + ".\n");
}else{
return ("The artist is called " + artist +
" and this song is called " + title + ".\n");
}
}
If its just about the singer, you could do the following:
public String toString() {
String temp = "The artist is called " + artist";
if(singer != null){ //checks if the object "singer" is not null
temp+=" who is a " + genre + " singer";
}
temp+="and this song is called "+ title + ".\n";
return temp;
}
You can insert a null check to skip this part. Anyway you should use a StringBuffer for that otherwise you are creating many String objects and make the GC angry. Every + creates a new String Object, so with a StringBuffer you only create one String at the end.
public String toString ()
{
StringBuffer buffer = new StringBuffer("The artist is called ");
buffer.append(artist);
if(genre != null)
{
buffer.append(" who is a ");
buffer.append(genre);
buffer.append(" singer");
}
buffer.append(" and this song is called ");
buffer.append(title);
buffer.append(".\n");
return buffer.toString();
}

Printing separate name variations in java?

I am making a programming to print the following
user inputs name like so --> first middle last
prints:
FML
Variation one: LAST, First M.
Variation two: Last, First Middle
Now, I need an if statement so that if just a first name is entered it says "error, incorrect input"
I coded this horribly and extremely unconventional, but hey, this is the first thing I've ever programmed before, so I guess we all start somewhere.
import java.util.Scanner;
public class name {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
//Declares length of entire name
int nameLength = fullName.length();
//Declares int where first space is
int a = fullName.indexOf(" ");
//Declares int where second space is
int b = fullName.lastIndexOf(" ");
//If they equal each other, then there is only one space
if ( a == b )
{
firstName = fullName.substring(0,a);
lastName = fullName.substring(a+1,nameLength);
String firstNameInitial = firstName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
firstName = fullName.substring(0,a);
lastName = fullName.substring(b+1,nameLength);
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a));
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a));
}
//If a < b then it will notice a middle name exists due to multiple spaces
else if ( a < b )
{
firstName = fullName.substring(0,a);
middleName = fullName.substring(a+1,b);
lastName = fullName.substring(b+1,nameLength);
String firstNameInitial = firstName.substring(0,1);
String middleNameInitial = middleName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + middleNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
//MNIC = Middle Name Initial Capitalized
String MNIC = middleNameInitial.toUpperCase();
//MNIMFC = Middle Name Initial Minus First Character
String MNIMFC = middleName.substring(1, middleName.length());
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + middleNameInitial.toUpperCase() + "." );
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + MNIC + MNIMFC);
}
}
}
You can use the String.split() function to split a String into its parts along a seperator.
In your case that would be the space (" ")
Try:
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
String[] parts = fullName.split(" ");
if(parts.length() == 3){
// 3 words were entered, so there is a middle name
}
// ...
You can just add this check
if(fullName.indexOf(" ")==-1 || (fullName.indexOf(" ") == fullName.lastIndexOf(" "))){
// The first check is to check if only firstname was given and the second check is to check if only first and middle names were given.
// If first + middle is a valid scenario, you can remove the second half of the if condition
System.out.println("error, incorrect input");
System.exit(0);
}
before the below statement in your code.
int nameLength = fullName.length();
You can simply check for a == -1. indexOf returns -1 if not found (as per the docs).
if (a == -1)
System.out.println("Error, invalid input!");
else if (a == b)
...
You can narrow down to the condition you stated by following these steps:
Trim the input String fullName before statement int a = fullName.indexOf(" ");
Next check if the index of whitespace (i.e. value of a and b variables) is -1, then you can assume that the input contains only a single word, presumably Firstname
Print the error message "error, incorrect input"
since it's your first attempt, I'll give you a modified version of your code:
public class name {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
//Declares length of entire name
int nameLength = fullName.length();
//Declares int where first space is
int a = fullName.indexOf(" ");
//Declares int where second space is
int b = fullName.lastIndexOf(" ");
/*** Use the split function to split the names with spaces as delimiter **/
String[] n = fullName.split(' ');
firstName = n[0];
if( n.length == 2 ) {
lastName = n[1];
}
if( n.length > 3 ) {
lastName = n[1];
middleName = n[2];
}
String firstNameInitial = firstName.substring(0,1);
String middleNameInitial = middleName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + middleNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
//MNIC = Middle Name Initial Capitalized
String MNIC = middleNameInitial.toUpperCase();
//MNIMFC = Middle Name Initial Minus First Character
String MNIMFC = middleName.substring(1, middleName.length());
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + middleNameInitial.toUpperCase() + "." );
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + MNIC + MNIMFC);
}
}

Categories

Resources