Main Error Исключение нулевого указателя / Невозможно запустить в командной строке - PullRequest
0 голосов
/ 15 ноября 2018

Я создаю программу, которая должна спрашивать пользователя в командной строке, что он хотел бы отсортировать, используя метод сортировки SHell.

У меня создан метод сортировки оболочки, но при попытке получить ошибку на моей сторонечтобы запустить его.

Я убедился, что это работало нормально при работе с клиентом Windows для друзей, но все еще не может запустить

public class client{
	public static void main(String args[]){
		// Get the file name of the data set , and the number of runs
// for the data set from the command line
// Read in the file of N random Doubles from the command line and
// store in the array data []
// Build i n c r e m e n t s e q u e n c e arrays for this data set
// D e t e r m i n e the upper value of array based on h [ k ] <= 0.5* N
// h1 [] , h2 [] , h3 [] , h4 []
// h1 is the i n c r e m e n t s e q u e n c e : 1 ,2 ,4 ,8 ,16 ,32 ,...2^ i
// h2 is the i n c r e m e n t s e q u e n c e : 1 ,8 ,23 ,77 ,281 ,...4^ i +3*2^{ i -1} + 1
// h3 is the i n c r e m e n t s e q u e n c e : 1 ,2 ,3 ,4 ,6 ,8 ,9 ,12 ,...2^ p *3^ q
// h4 is the i n c r e m e n t s e q u ee n c e : 1 ,3 ,7 ,15 ,31 ,63 ,...2^ i - 1
// sort the array of N items with each s e q u e n c e j trials , timing each :
		int n=5;

		int h1 [] = new int [1000];
		int h2[] = new int[1000];

		int h3 [] = new int [1000];
		int h4[] = new int[1000];
		Comparable data[] = new Comparable[1000];
		while(n>0){
ShellSort study = new ShellSort ( data );
double start = System.nanoTime (); 
study.sortUsing (h1);
double duration1 = System.nanoTime () - start ;
start = System . nanoTime (); study.sortUsing ( h2 );
double duration2 = System . nanoTime () - start ;
start = System . nanoTime (); study . sortUsing ( h3 );
double duration3 = System . nanoTime () - start ;
start = System . nanoTime (); study . sortUsing ( h4 );
double duration4 = System . nanoTime () - start ;
// display results for an average g e n e r a t e d from at least
	}
	n--;
}
}

это клиент

import java.util.*;
public class ShellSort
{
private Comparable [] data ;
public ShellSort ( Comparable [] x )
{
data = new Comparable [x.length ];
for ( int i =0; i < x.length ; i++)
this.data [ i ] = x [ i ];
}
public void sortUsing ( int [] h )
{
// your code
		int n = data.length; 
  
        // Start with a big gap, then reduce the gap 
        for (int gap = n/2; gap > 0; gap /= 2) 
        { 
            // Do a gapped insertion sort for this gap size. 
            // The first gap elements a[0..gap-1] are already 
            // in gapped order keep adding one more element 
            // until the entire dataay is gap sorted 
            for (int i = gap; i < n; i += 1) 
            { 
                // add a[i] to the elements that have been gap 
                // sorted save a[i] in temp and make a hole at 
                // position i 
                Comparable temp = data[i]; 
  
                // shift earlier gap-sorted elements up until 
                // the correct location for a[i] is found 
                int j; 
                for (j = i; j >= gap && less(temp,data[j-gap]); j -= gap)
                    data[j] = data[j - gap]; 
  
                // put temp (the original a[i]) in its correct 
                // location 
                data[j] = temp; 
            } 
        } 
        


}
private boolean less(Comparable v, Comparable w)
{
return ( v.compareTo(w) < 0); }
private void exch(Comparable[] data, int i, int j )
{
Comparable t = data[i]; data[i] = data[j]; data[j]= t; }

}

1 Ответ

0 голосов
/ 15 ноября 2018

Поскольку вы не заполняли сопоставимые элементы в массиве. Они установлены в нули, поэтому вы получаете НЛП.

Потому что:

 Comparable data[] = new Comparable[1000];

содержит все элементы со значением null, поскольку оно является Object так на самом деле например:

  data[0] = null
  .
  .
  .
  data[999] = null;

И при вызове этого метода:

 private boolean less(Comparable v, Comparable w) {
        return (v.compareTo(w) < 0);
    }

Вы передаете параметры как null, а когда вы вызываете что-то для null, вы получаете NullPointerExceptions.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...