This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Currently having difficulty with Selection Sort and Bubble Sort codes.
The selection sort is used to sort out student ID in ascending order and the bubble sort is used to sort out last names in ascending order. The program compiles but crashes upon choosing choice 10 or 11.
My array is declared as follows:
student[] list = new student[100]; //my array
This is the code that I have for selection sort and bubble sort. I am using an array with methods:
if (choice == 10) { // Dissplay the sorted array by student id
SortArrayBySelection(list);
System.out.println("Sorted studentid are:");
for (int i =0; i< studentNumber; i++)
{
System.out.println(list[i]);
}
}
if (choice == 11){ // Display the sorted array by family name
BubbleSort(list);
System.out.println("The sorted names are:");
for(int i = 0; i < studentNumber; i++)
{
System.out.println(list[i].Getfamilyname());
}
}
} while (choice != 1);
}
public static void SortArrayBySelection(student[] arrayToSort){ // Function to sort out the array on sutdentid
for(int i = 0; i < arrayToSort.length-1; ++i)
{
int minIndex = i;
int studentid3 = arrayToSort[i].Getstudentid();
int studentid2 = arrayToSort[minIndex].Getstudentid();
for(int j = i + 1; j <arrayToSort.length; ++j)
{
int studentid1 = arrayToSort[j].Getstudentid();
if(studentid1 < studentid2)
{
minIndex = j;
}
}
int temp = studentid3;
studentid3 = studentid2;
studentid2 = temp;
}
}
public static void BubbleSort(student[] arraySort){
String t;
for(int i = 0; i<arraySort.length; i++){
for(int j=0; j<arraySort.length-1;j++){
String str1 = arraySort[j].Getfamilyname();
String str2 = arraySort[j+1].Getfamilyname();
if(str1.compareTo(str2)<0){
t = str1;
str1 = str2;
str2 = t;
}
}
}
}
Any suggestions would be appreciated! thank you
Errors:
Exception in thread "main" java.lang.NullPointerException
at client.Client.SortArrayBySelection(Client.java:270)
at client.Client.main(Client.java:232)
Exception in thread "main" java.lang.NullPointerException
at client.Client.BubbleSort(Client.java:288)
at client.Client.main(Client.java:246)
As you have not mentioned line numbers in your code, also the Student class and the code where you are preparing the student[] list = new student[100]. So, as far as i can see the code from following lines you can get the java.lang.NullPointerException
Your list length will be always 100 as you are creating it with that value. So if it something dynamic values which you are preparing at runtime then it will be better if you use ArrayList<student> list=new ArrayList<student>(); and add the values using list.add(yourObject);.
Exception in thread "main" java.lang.NullPointerException
at client.Client.SortArrayBySelection(Client.java:270)
at client.Client.main(Client.java:232)
For this error you are calling SortArrayBySelection method and the lines which may end up in the above errors are
int studentid3 = arrayToSort[i].Getstudentid();
int studentid2 = arrayToSort[minIndex].Getstudentid();
int studentid1 = arrayToSort[j].Getstudentid();
Reason for the error :
You don't have the values present at the given index and as you are creating an array of length 100 where you put only let say 10-15 values then it will always have no values in other location. But your for-loop will go to 100 index position in which after 10-15 index you will always get null by calling the getters.
Same reason is for your other method as well.
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 1 year ago.
Improve this question
Why does this exception occur when I call my sort method?
Exception in thread "JavaFX Application Thread"
java.lang.IllegalArgumentException: 1 > 0
jdk: 1.8.0 u281
This is an assignment for school. I absolutely must solve this problem recursively as it calls for the use of an alphabetical recursive sort method to be used.
public void sort1() {
ArrayList<String> sortlist = new ArrayList();
for(int i = 0; i < size(); i ++) {
sortlist.add(getInd(i));
}
String[] testData = sortlist.toArray(new String[sortlist.size()]);
sort(testData);
for(String s: testData) {
System.out.println(s);
}
}
/**
* recursive alphabetical sort method
* #param a the array of string values
*/
public void sort(String[] a) {
if (a.length==1) {
System.out.println("list is not long enough");
}
// Copy array from 1..length-1 into new array rest
String rest [] = Arrays.copyOfRange(a, 1, a.length);
// sort rest
sort(rest);
// insert a[0] into rest and store the result in a
insert(a,rest);
}
// insert a[0] into sort and store result in a
private static void insert(String [] a, String [] sorted) {
int i;
String saveFirst = a[0];
// Find index 'i' where such that sorted[i] > a[0]
for (i=0; i < sorted.length; i++) {
if (saveFirst.compareTo(sorted[i])<0) {
break;
}
}
// Copy elements less than a[0] from sorted to a
for (int j=0; j < i; j++) {
a[j] = sorted[j];
}
// insert a[0]
a[i] = saveFirst;
// copy elements greater than a[0] from sorted to a
for (int j=i+1; j < a.length; j++) {
a[j] = sorted[j-1];
}
}
The same exception occurs here in a separate class's event handler & switch as well:
#Override
public void handle(ActionEvent event)
{
// Get the command from the command textfield.
TextField cmdTextField = (TextField)event.getTarget();
String cmdText = cmdTextField.getText();
// Use a scanner to read the name of the linked list
// method and do a switch on it.
Scanner sc = new Scanner(cmdText);
String cmd = sc.next();
switch(cmd)
{
case "sort":
ll.sort1();
break;
}
}
That error arises from Arrays.copyOfRange when the from variable is larger than the to variable.
Try changing:
if (a.length==1) {
System.out.println("list is not long enough");
}
to the following:
if (a.length<=1) {
System.out.println("list is not long enough");
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to read in a file and alphabetize the names. The file has a list of first and last names, for example:
Bob Flower
Tina Sea
Krusty Crab
Mark Klutz
I want to use bubble sort to alphabetize the strings. I keep getting an error saying:
java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at BubbleSort.Alphabetize(BubbleSort.java:48)
at BubbleSort.main(BubbleSort.java:31)
My Code so far is:
import java.util.*;
import java.io.*;
public class BubbleSort
{
public static void main(String[] args)
throws IOException
{
File inData = new File("names.txt");
if (!inData.exists()) {
System.out.println("File does not exist");
System.exit(0);
}
Scanner input = new Scanner(inData);
int x = 0;
String[] name = new String[30];
//String[] extra = new String[30];
while (input.hasNext()) {
name[x] = input.next();
input.nextLine();
// extra[x] = input.next();
// System.out.println(name[x]);
x++;
}
BubbleSort sorter = new BubbleSort();
sorter.Alphabetize(name, x);
for (int i = 0; i < x; i++) {
System.out.println(name[i]);
}
input.close();
}
private static void Alphabetize(String[] array, int a)
throws IOException
{
String temp;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j].compareTo(array[j + 1]) > 0) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
I don't understand how to fix this error, or what is truly wrong.
You're sorting an unused (and therefore null) array element. Instead of array.length you should be using a, throughout the sort method. That's what a is for.
I guess String[] name = new String[30]; contains null elements. In your example there are only 8 strings
Bob Flower
Tina Sea
Krusty Crab
Mark Klutz
However you create an array with 30 elements. As result there will be 8 String objects in the array and 22 null.
And later on in array[j].compareTo(array[j + 1]) there is comparison between a valid String object and null. Try to use ArrayList instead of String[].
You have problem with allocating memory(array) and using calculated indeces to access element. As a result you have a problem accessing not initialized elements or another time you could get IndexOutOfBoundExceptions. As a beginner it might helpful to learn and do it in low level, but I would like to share a little for your interest, and also it may help not to hate Java.
File class is old, try to use NIO.2 which came with Java 7.
For higher level abstraction here is a one line sorting solution:
Files.readAllLines(Paths.get("names.txt"))
.stream().filter(p -> p.length() > 0)
.forEachOrdered(System.out::println);
It could be even tried out in JShell(Java 9).
Files.readAllLines(Paths.get("names.txt"))
.stream().filter(p -> p.length() > 0)
.sorted()
.toArray(String[]::new);
Output:
{ "Bob Flower", "Krusty Crab", "Mark Klutz", "Tina Sea" }
Nope - You're accessing a null array element past the size of your array length. When you're at the end and access array[j + 1], it's null.
if (array[j].compareTo(array[j + 1]) > 0) { <- culprit here
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am writing a program that will take a disk file with an array of strings with a max size of 100 and do a few things to them. However, I am getting a console error due to my bubblesort method searching for and trying to sort 100 (the length of the array) items while the disk file may have, lets say, 15 items. The bubblesort method is returning a console error due to it searching for the remaining 85 items and trying to sort 85 blank items. I am totally lost on how to fix this problem. Is it possible to get the items in the disk file, pass them onto another array and then bubblesort that one so the 85 blank spots are eliminated? Or is adding a counter an option that will solve my problem? I am fairly new at java coding so any help would be greatly appreciated.
Here is the error i am getting:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at Assignment7.bubbleSort(Assignment7.java:52)
at Assignment7.main(Assignment7.java:12)
here is my code:
import java.io.*;
import java.util.*;
public class Code3 {
public static void main(String[] args) throws IOException {
String[] list2, targets, list1;
list1 = getInput("C:\\Users\\Steave\\Desktop\\file14.txt");
list2 = bubbleSort(list1);
targets = getInput("C:\\Users\\Steave\\Desktop\\upload6.txt");
double seqAvg = seqSearch(list1, targets);
double binAvg = binSearch(list2, targets);
System.out.println("Average number of searches for the seqeuntial search is " + seqAvg);
System.out.println("Average number of searches for the binary search is " + binAvg);
}//end of main method
public static String[] getInput(String filename) throws IOException {
String[] inputArr = new String[100];
Scanner in = new Scanner(new File(filename));
int count = 0;
while(in.hasNext()) {
if (count < 100){
inputArr[count++] = in.next();
} else {
break;
}
}
in.close();
return inputArr;
}// end getInput method
//This method will sort the array and pass it onto a list.
public static String[]bubbleSort(String[] inputArr) {
String[] Array2 = inputArr.clone();
for (int i = 0; i<Array2.length; i++)
{
for (int j = 0; j<Array2.length-1; j++)
{
if (Array2[j].compareTo(Array2[j+1]) > 0) //CONSOLE ERROR HERE
{
String temp = Array2[j];
Array2[j] = Array2[j+1];
Array2[j+1] = temp;
}
}
}
return Array2;
}// End of sort method.
//This method will do a sequential search on the list1
public static double seqSearch(String[] list1, String[] targets){
{
for (int j = 0; j < list1.length; j++)
{
for(String str:targets){
if(list1[j].equalsIgnoreCase(str)){
return j;
}
}
{
return j;
}
}
return -1;
}
}//end of sequentialSearch method
//This method will do a binary search on the list
public static int binSearch(String[] list1, String[] targets) {
int lo = 0;
int hi = list1.length - 1;
int mid = -1;
while( lo <= hi ) {
mid = (lo+hi)/2;
for(String str:targets){
if(list1[mid].equalsIgnoreCase(str)){
return mid;
}
hi = mid-1;
} for(String str:targets){
if(list1[mid].equalsIgnoreCase(str)){
return mid;
}
}
lo = mid+1;
{
return mid;
}
}
return mid;
}
}
Some elements of your string array were not initialized. Only the values you read from the input file are assigned a value, the rest are null. An easy fix is to return a new array created from the beginning part that has the assigned values.
Change this line:
return inputArr;
To this:
return Arrays.copyOf(inputArr, count);
I'm trying to create a program that takes user input and sorts it alphabetically as it comes in using compareTo String operations (not array.sort) and prints the final sorted array at the end. I've got most of the body of this problem down but am lost once I get to the sort function. Does anyone have any ideas on how I might be able to finish out the SortInsert method?
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array_size = GetArraySize();
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String nextString = GetNextString();
String[] sortedArray = SortInsert(nextString, myArray);
}
PrintArray(sortedArray);
}
input.close();
}
}
public static String[] SortInsert(String nextString, String[] myArray){
for(int i = 0; i < myArray.length;)
if (nextString.compareToIgnoreCase(myArray[i]) > 0) {
i++;
//if current text is less(alphabetically) than position in Array
}else if (nextString.compareToIgnoreCase(myArray[i]) < 0){
}
}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
return next_string;
}
}
There are a number of problems with this code. First I'll answer your immediate question, then enumerate some of the other problems.
The SortInsert method takes a String[] that will have been initialized with null values, so you will need to take that into account. The for loop would look something like this. (I'm using comments instead of writing the actual code since I'm not doing the project)
for (int i=0; i<myArray.length; ++i) {
if (myArray[i] == null) {
// we found a blank spot. use it to hold nextString.
break;
} else if (nexString.compareToIgnoreCase(myArray[i]) < 0) {
// nextString should be in spot i, so make room for it
// by shuffling along whatever is in the array at "i" and later
// by one place, then put nextString into position "i"
break;
}
// otherwise we'll just move to the next position to check
}
Now for the other issues.
You have a Scanner object in main that is never used. There's no point in having it and closing it at the end if your other methods make their own.
myArray will always be the sorted array so there's no point in making a local variable called sortedArray and return it from SortInsert. Note that your attempt to print sortedArray would fail anyway because that local variable is only in scope within the for loop.
When printing it should be myArray being passed to PrintArray.
If you're going to sort as you go, the TreeMap data structure is what you should be using, not an array. However, if you want to sort as you go with an array, you need to add some lines into your else if clause in SortInsert (should be sortInsert, BTW). (Another question: why is it else if rather than just else?)
The lines should create a new array of size one greater than the existing array, copy the first i-1 elements of the old array to the new array, put the new element in position i, then copy the remaining elements of the old array into positions one greater in the new array.
Once you find the position you wish to insert at, you have to shift all of the following elements down by one. Something like the following:
String temp = array[position];
for (int j = position+1; j < array_size-1; j++) {
String temp2 = array[j];
array[j] = temp;
temp = temp2;
}
array[array_size-1] = temp;
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am new to programming and while running some new code in eclipse, I came across this error and am completely lost.
import java.util.Scanner;
public class Lab6
{
public static void main(String[] args)
{
// Fill in the body according to the following comments
Scanner in= new Scanner(System.in);
// Input file name
String FileName=getFileName(in);
// Input number of students
int numOfStudents = FileIOHelper.getNumberOfStudents(FileName);
Student students[] = getStudents(numOfStudents);
// Input all student records and create Student array and
// integer array for total scores
int[]totalScores = new int[students.length];
for(int i=0; i< students.length; i++)
{
for(int j=1; j<4; j++)
{
totalScores[i]= totalScores[i]+students[i].getScore(j);
}
}
// Compute total scores and find students with lowest and
// highest total score
int i;
int maxIndex =0;
int minIndex =0;
for(i=0; i<students.length; i++);
{
if(totalScores[i]>=totalScores[maxIndex])
{
maxIndex=i;
}
else if(totalScores[i]<=totalScores[minIndex])
{
minIndex=i;
}
}
problem seems to be in the line if(totalScores[i]>=totalScores[maxIndex])
You have a ; after your last for, so after the for executes with no additional commands in each step, the variable i will have the value students.length which is outside the bounds of the array. Then the { ... } block following the for is executed once with that final value of i, causing the exception.
Remove that ; and it should work.
problem in this lines
int[]totalScores = new int[students.length];
for(int i=0; i< students.length; i++)
{
for(int j=1; j<4; j++)
{
totalScores[i]= totalScores[i]+students[i].getScore(j);
}
}
you allocated students.length size for the totalscore.. but u are using 4*students.length.. so arrayindex out of bounds occured. use this
int[]totalScores = new int[4*students.length];
thanks
arefin