This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to print out the names of the employees and their department and location from a list of the names and id numbers and I keep getting the NullPointerException even though it prints all of the names and locations. It then stops the build and doesn't xecute the print department and print location methods.
I've tried re-doing the for loops and seeing if any one data point was the problem but it seems to happen if I do the loop for all of the Employee objects or if I just do one.
package homework5_parth_desai;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
*
* #author Party Parth
*/
public class Homework5_Parth_Desai {
public static int emplIndex = -1;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
File file = new File("acmeEgr.txt");
Scanner scan = new Scanner(file);
Employee[] emp = new Employee[50];
String s = "";
String t = "";
int r = 0;
while (scan.hasNextLine()) { //scans in file
emplIndex++;
emp[emplIndex] = new Employee();
if (scan.hasNextLine() == true) { //takes first line as first name, second as last naem and third as id number and tehn ccreates an object out of that
s = scan.nextLine();
}
if (scan.hasNextLine() == true) {
t = scan.nextLine();
}
if (scan.hasNextLine() == true) {
r = Integer.parseInt(scan.nextLine());
}
emp[emplIndex].Employee(s, t, r);
// TODO code application logic here
}
printAll(emp);
printDepartment("IT", emp);
printLocation("Auburn Hills", emp);
}
static void printAll(Employee[] ppl) {
for (int i = 0; i < ppl.length; i++) {
System.out.println(ppl[i].toString());
}
}
static void printDepartment(String title, Employee[] ppl) {
for (int i = 0; i < ppl.length; i++) {
if (title.equals(ppl[i].getDept())) {
System.out.println(ppl[i].getName() + " is in " + ppl[i].getLocation());
}
}
}
static void printLocation(String loc, Employee[] ppl) {
for (int i = 0; i < ppl.length; i++) {
if (loc.equals(ppl[i].getLocation())) {
System.out.println(ppl[i].getName() + " is in " + ppl[i].getDept());
}
}
}
}
Small exert of the .txt file:
Alexander
Seiber
10010
Zehua
Showalter
20010
Cassidy
Woodle
20030
Randall
Shaukat
10030
Pam
Korda
10020
Justin
Polito
20030
public static int emplIndex = -1;
Why is the index maintained as a static field? Don't do that.
Employee[] emp = new Employee[50];
The employee array has a fixed size of 50 elements, however
while (scan.hasNextLine()) {
this loop is based on the lines of the acmeEgr.txt file, which might be more than 50.
In that case, you'll get an ArrayOutOfBoundException first
emp[emplIndex] = new Employee();
or a NullPointerException after
emp[emplIndex].Employee(s, t, r);
Instead, if the lines are less then 50, this
for (int i = 0; i < ppl.length; i++) {
System.out.println(ppl[i].toString());
}
will still loop all the 50 elements, because
ppl.length = 50
Thus, this line
ppl[i].toString()
will throw a NullPointerException.
This is what happens if the elements are, for example, 40
System.out.println(ppl[0].toString());
System.out.println(ppl[1].toString());
System.out.println(ppl[2].toString());
System.out.println(ppl[3].toString());
...
System.out.println(ppl[40].toString()); // ppl[40] is null, NullPointerException!
ArrayList is a much easier array type to deal with. Try using it instead of a normal array, because then you don't have to deal with indexes.
Related
This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
2D array Null Pointer Exception error
(2 answers)
Closed 4 years ago.
Matrix.java
import java.io.*;
class Matrix {
private int q[][];
public Matrix() {
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
q[i][j] = Integer.parseInt(System.console().readLine());
}
public Matrix( int a , int b ) {
int mat[][] = new int [a][b];
for(int i=0; i<mat.length; i++) {
for(int j=0;j<mat[i].length;j++)
q[i][j] = Integer.parseInt(System.console().readLine());
}
}
public void show() {
for(int i=0; i<q.length; i++) {
for(int j=0;j<q[i].length;j++)
System.out.println(q[i][j]+" ");
}
}
}
UseMatrix.java
class UseMatrix {
public static void main(String args[]) {
Matrix m1 = new Matrix();
System.out.println("First Matrtix ");
m1.show();
Matrix m2 = new Matrix(5,4);
System.out.println("Second Matrtix ");
m2.show();
}
}
This programs shows NullPointerException error at runtime
Confused why this isn't working could use a little help, I want to the create a 2D Array of Size 3*3 through Default Constructors.
Then I want to create a Array of size 5*4 using parameterized constructors.
There are a number of problems:
First: private int q[][]; // this holds a null value, never assigned on the parameterless constructor. A possible solution to this would be to add in your constructor: q[][] = new int[a][b]; and q[i] = new int[b];// each time you enter the loop. See the code below for clarity.
Second in public Matrix() { you try to access the array contents without checking its length (for(int i=0;i<3;i++) goes from 0 to 3, regarles of the actual array size). The array is empty at the beggining so this causes another NullPointerException here q[i][j] = Integer.parseInt... (I will solve this reusing the other constructor because they want to achieve the same result)
Third there is problems reading from console(), so I changed that too. (And added a line where you ask the user for a number)
And the last change I made was a small tweak to the show method.
Result:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class App {
public static void main(String[] args) {
Matrix m1 = new Matrix();
System.out.println("First Matrtix ");
m1.show();
Matrix m2 = new Matrix(5,4);
System.out.println("Second Matrtix ");
m2.show();
}
}
class Matrix {
private int q[][];
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public Matrix() {
this(3, 3);
}
public Matrix(int a, int b ) {
int value;
System.out.println("Input a number to fill the new 3x3 matrix");
try {
value = Integer.parseInt(br.readLine());
} catch (IOException e) {
throw new RuntimeException("There was a problem reading the number from console", e);
}
q = new int[a][b];
for(int i=0;i<a;i++) {
q[i] = new int[b];
for(int j=0;j<b;j++) {
q[i][j] = value;
}
}
}
public void show() {
for(int i=0; i<q.length; i++) {
for(int j=0;j<q[i].length;j++)
System.out.print(q[i][j]+" ");
System.out.print("\n");
}
}
}
i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();
Basically, I'm trying to create two different sized 2D arrays from a text file that looks like this:
2
add
3 4
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
subtract
2 2
2 12
10 0
4 6
9 1
The 2 is the number of problems (add and subtract), the 3 and 4 are the number of rows and columns, and the numbers below it are the two separate matrices being filled into the 2D arrays. If I just stop there, this program works correctly:
class Matrices {
private Scanner fileReader;
private int rows;
private int columns;
int problems;
String method;
public Matrices(String file) throws FileNotFoundException {
this.fileReader = new Scanner(new FileInputStream(file));
problems = fileReader.nextInt();
method = fileReader.next();
if(method.equals("add")) {
rows = fileReader.nextInt();
columns = fileReader.nextInt();
}
}
public int[][] readMatrix() throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public int[][] add(int[][] a, int[][] b) {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
public void printMatrix(int[][] matrix) {
for ( int[] anArray : matrix ) {
for ( int anInt : anArray ) {
System.out.print(anInt+ " ");
}
System.out.println();
}
}
}
With this driver:
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
Matrices matrixReader = new Matrices(filename);
int[][] a = matrixReader.readMatrix();
int[][] b = matrixReader.readMatrix();
System.out.println("Matrix 1: ");
matrixReader.printMatrix(a);
System.out.println();
System.out.println("Matrix 2: ");
matrixReader.printMatrix(b);
System.out.println();
System.out.println("Addition: ");
int[][] addition = matrixReader.add(a,b);
matrixReader.printMatrix(addition);
}
}
It creates and prints the matrices just fine, with no problems. However, whenever I try to create and print the next two matrices (the 2x2 arrays below subtract in the text file), it returns the following error:
Enter name of file:
data/Matrices.txt
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at baker.Matrices.readMatrix(Matrices.java:27)
at baker.MatricesDriver.main(MatricesDriver.java:15
My question is, what adjustments should I make so that the program recognizes that two of the 2D arrays are to be 3x4, and the two following are to be 2x2?
I would recommend decomposing your implementation into the following parts:
class Matrix - holds the values of one matrix from problem definition
class Problem - holds the operation and the two matrices from problem definition
The Matrix class could look like:
class Matrix {
private int[][] values;
public Matrix(int[][] values) {
this.values = values;
}
public int[][] getValues() {
return values;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Matrix [values=\n");
for (int i = 0; i < values.length; i++) {
sb.append("\t" + Arrays.toString(values[i]) + "\n");
}
sb.append("]");
return sb.toString();
}
}
The Problem class could be:
class Problem {
private String operation;
private Matrix first;
private Matrix second;
public Problem(String operation, Matrix firstMatrix, Matrix secondMatrix) {
this.operation = operation;
first = firstMatrix;
second = secondMatrix;
}
public String getOperation() {
return operation;
}
public Matrix getFirst() {
return first;
}
public Matrix getSecond() {
return second;
}
#Override
public String toString() {
return "Problem [\noperation=" + operation + ", \nfirst=" + first + ", \nsecond=" + second + "\n]";
}
}
Based on this, your "driver" class does the following:
Get the filename from user input
Read from file the number of problems and construct a list with this initial size
For the number of problems (i.e. 2) get the operation, rows, and colums and construct a new Problem object containing these information and put the Problem into the list ...
Here is one simple solution - still room for improvement here :-)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
List<Problem> problems = readProblems(filename);
System.out.println(problems);
keyboard.close();
}
private static List<Problem> readProblems(final String filename) throws FileNotFoundException {
Scanner fileReader = new Scanner(new FileInputStream(filename));
int numberOfProblems = fileReader.nextInt();
List<Problem> problems = new ArrayList<>(numberOfProblems);
for (int i = 1; i <= numberOfProblems; i++) {
problems.add(readProblem(fileReader));
}
fileReader.close();
return problems;
}
private static Problem readProblem(Scanner fileReader) throws FileNotFoundException {
fileReader.nextLine(); // go to next line
String operation = fileReader.nextLine(); // read problem operation
int rows = fileReader.nextInt(); // read number of rows
int columns = fileReader.nextInt(); // read number of columns
Matrix firstMatrix = readMatrix(rows, columns, fileReader);
Matrix secondMatrix = readMatrix(rows, columns, fileReader);
return new Problem(operation, firstMatrix, secondMatrix);
}
private static Matrix readMatrix(final int rows, final int columns, final Scanner fileReader) throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return new Matrix(result);
}
}
Tested with your input file.
HTH
You tried to structure your data?
you can use that:
properties-file
For create array or vector without a fixed size use arrayList, you can make a arrayList from a arrayList
I am very new to Java. My current program loops through a block that asks for users input in the console until the value they type equals done. I want to store each value the user types in an array that is a class property. When I try to append this array, I get an error that says Error:(59, 18) java: not a statement. My code is below. I will point out the line that the error occurs on inside the code. Thanks for your time!
package com.example.java;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the musical key calculator!");
System.out.println("Enter your notes one at a time.");
System.out.println("Use uppercase letters A-G and # for sharp and b for flat.(Ex. Eb)");
System.out.println("Remember that E# and B# do not exist in music!");
System.out.println("When you have entered all of your notes, type 'done'");
System.out.println("------------------------------------------------------------------");
boolean finished = false;
Scale YourScale = new Scale();
while(finished == false) {
System.out.print("Enter a note: ");
String note = scanner.nextLine();
if (note == "done'") {
finished = true;
} else {
YourScale.addNote(note);
}
}
if(finished == true){
StringBuilder output = new StringBuilder("Your notes are ");
String[] completedNotes = YourScale.notes;
for (int i = 0; i < completedNotes.length; i++) {
output.append(completedNotes[i] + " ");
}
}
}
public static class Scale {
public String[] notes = {};
public void addNote(String note){
notes[] = note; //Error occurs here.
}
}
}
Java arrays are fixed length, and that isn't how you create (or populate an array). I would prefer to use a Collection like,
public List<String> notes = new ArrayList<>();
public void addNote(String note){
notes.add(note);
}
But, you could use Arrays.copyOf(T[], int) and something like
public String[] notes = new String[0];
public void addNote(String note){
int len = notes.length;
notes = Arrays.copyOf(notes, len + 1);
notes[len] = note;
}
Finally, you do not test String equality with ==
if (note == "done'") {
should be something like
if (note.equals("done")) {
notes is a String array, which means it has many String objects inside. Also you initialize it to an empty array. Arrays should have a fixed size.
//Declare a variable notes, and initialize it as an empty array?
public String[] notes = {};
public void addNote(String note)
{
//This doesn't make sense in java - it's syntax is wrong
notes[] = note;
}
If you want to use arrays this is an example:
//Declare a variable notes, and initialize it as an array of
//specific size (I used 5 as example)
public String[] notes = new String[5];
public void addNote(String note)
{
//Here you should have some short of counter that counts in which
// position of the array you will save 'note' or just run a 'for'
//loop and the first element that is not initialized can get the note
for (int i = 0; i < notes.length; i++)
if (notes[i] == null)
{
notes[i] = note;
break;
}
}
Although this method allows you to save a fixed size, which is not desirable in your case, but nevertheless it uses Array and can help you understand how to use them.
If you want to implement it properly you should use an ArrayList. An ArrayList is an array where you can add new elements and remove them. You can find plenty of documentation online of how to use them.
You are trying to assign a String to a String array. You probably intended to add it to the array.
I have been assigned a task that requires me to utilise a 2D Array. I have to read in a file and export it to a 2D array. I can only have a single method but I am unable to sort the array correctly. I am supposed to sort the data in 3 ways (alphabetically by name and with scores highest to lowest; highest to lowest scores for each student and highest to lowest by the average of 3 scores.) So far I have
import java.util.*;
import java.io.*;
public class ScoreSorter {
public static void main(String[] args) {
int student_num = 30;
String[][] DataInTableArr = new String[30][6];
try {
BufferedReader ReadIn = new BufferedReader(new FileReader("classZ.csv"));
for (int i = 0; i < 30; i++) {
String DataIn = ReadIn.readLine();
String[] DataInArr = DataIn.split(",");
DataInTableArr[i][0] = DataInArr[0];
DataInTableArr[i][1] = DataInArr[1];
DataInTableArr[i][2] = DataInArr[2];
DataInTableArr[i][3] = DataInArr[3];
int temptest1 = Integer.parseInt(DataInArr[1]);
int temptest2 = Integer.parseInt(DataInArr[2]);
int temptest3 = Integer.parseInt(DataInArr[3]);
}
} catch (Exception e) {
System.out.println("Whoops, you messed up, RESTART THE PROGRAM!!!!!");
}
}
}
I have no idea as to how to solve the rest of the task... I would appreciate if someone could tell me of the most efficient way and perhaps an example...
One plausible way is to create a Student class which implements Comparable interface, with the following members:
String name;
int scoreOne;
int scoreTwo;
int scoreThree;
compareTo(Student s) { //implement the comparison following 3 criteria you mentioned }
And, read the files row by row, for each row we create a Student object, and put all rows in a TreeSet. In this way, the TreeSet together with the compareTo method will help us sort the Students automatically.
Finally, iterate the sorted TreeSet to fill up the 2D array.
import java.util.*;
import java.io.*;
public class ScoreSorter {
public static void main(String[] args) {
int student_num = 30;
String[][] DataInTableArr = new String[30][6];
try {
BufferedReader ReadIn = new BufferedReader(new FileReader("classZ.csv"));
for (int i = 0; i < 30; i++) {
String DataIn = ReadIn.readLine();
String[] DataInArr = DataIn.split(",");
DataInTableArr[i][0] = DataInArr[0];
DataInTableArr[i][1] = DataInArr[1];
DataInTableArr[i][2] = DataInArr[2];
DataInTableArr[i][3] = DataInArr[3];
int temptest1 = Integer.parseInt(DataInArr[1]);
int temptest2 = Integer.parseInt(DataInArr[2]);
int temptest3 = Integer.parseInt(DataInArr[3]);
}
/*Code To be Inserted Here*/
} catch (Exception e) {
System.out.println("Whoops, you messed up, RESTART THE PROGRAM!!!!!");
}
}
}
If there are 6 columns such that First is name and the other 3 are scores then what does other 2 columns contain?? I ignore your array declaration :
String[][] DataInTableArr = new String[30][6];
and assume it to be 30x4 array
String[][] DataInTableArr = new String[30][4];
Logic for sorting Alphabetically
if(DataInTableArr[i][0].compareTo(DataInTableArr[i+1][0])){
/* Sorting Name of adjacent rows*/
String temp = DataInTableArr[i][0];
DataInTableArr[i][0] = DataInTableArr[i+1][0];
DataInTableArr[i+1][0] = temp;
/*Sorting the three marks similarly*/
temp = DataInTableArr[i][1];
DataInTableArr[i][1] = DataInTableArr[i+1][1];
DataInTableArr[i+1][1] = temp;
temp = DataInTableArr[i][2];
DataInTableArr[i][2] = DataInTableArr[i+1][2];
DataInTableArr[i+1][2] = temp;
temp = DataInTableArr[i][3];
DataInTableArr[i][3] = DataInTableArr[i+1][3];
DataInTableArr[i+1][3] = temp;
}
Put the above code in bubble sorting algorithm i.e. 2 loops.
Logic for sorting according to highest marks
In this case you have to find the highest marks in all three subjects of each DataInTableArr[i] and then compare the highest marks with that of next row.
Logic for sorting according to Average marks
Calculate the average of each i'th row as
(Integer.parseInt(DataInTableArr[i][1]) + Integer.parseInt(DataInTableArr[i][2]) + Integer.parseInt(DataInTableArr[i][3]))/3
and compare it with [i+1] th rows average.(same formula just replace [i] with [i+1])