for some reason I can't get Strings compareTo method to work. I get this error message:
exception in thread main java.lang.NullpointerException
at java.lang.String.compareTo(Unknown Source)
at Sort.main(Sort.java:27)
What can I do to fix this?
(this code demands that the to arrays are allready sorted individually.)
import java.util.*;
class Sort{
public static void main(String[] args){
String[] ord = new String[6];
ord[0] = "astra";
ord[1] = "bilum";
ord[2] = "deliber";
ord[3] = "kaliber";
ord[4] = "suppe";
ord[5] = "vorte";
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
String[] flettet = new String[ord.length + ordet.length];
for(int i = 0; i < ord.length; i++){
int teller = i;
for(int j = 0; j < ordet.length; j++){
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
teller += 1;
}
}
flettet[teller] = ord[i];
}
}
}
Do you mean - it looks like you are setting the wrong array:
String[] ordet = new String[6];
ordet[0] = "akilles";
ordet[1] = "kopper";
ordet[2] = "lipton";
ordet[3] = "mus";
ordet[4] = "orkester";
ordet[5] = "toving";
You never assign any values to ordet. so compareTo is comparing a string to NULL
String[] ord = new String[6];
ord[0] = "astra";
ord[1] = "bilum";
ord[2] = "deliber";
ord[3] = "kaliber";
ord[4] = "suppe";
ord[5] = "vorte";
String[] ordet = new String[6];
ord[0] = "akilles"; //overwriting ord[0]
ord[1] = "kopper"; //overwriting ord[1]
ord[2] = "lipton"; //overwriting ord[2]
ord[3] = "mus"; //overwriting ord[3]
ord[4] = "orkester"; //overwriting ord[4]
ord[5] = "toving"; //overwriting ord[5]
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
You never filled the ordet array, you just over-wrote the ord array.
At this point there is no elements in the ordet array, just nulls.
So...
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
is comparing to an element that doesnt exist, and #compareTo throws a NullPointerException because you passed in a null, not a String
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I have this error in my code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
70
at Main.main(Main.java:72)
I don't know why it is doing this? please help. I thank you in advance. I have gone through several threads on several websites and it doesn't have anything that worked. I have been working on this for a while. I know what the ArrayIndexOutOfBoundsException is i am trying to figure it out though and i have been unsuccessful
This is the code:
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static void main (String[] args)
{
Scanner myScanner = new Scanner (System.in);
Random myRandom = new Random();
int answer;
int definitionSelected = 0;
String[] code = new String[68];
String[] definition = new String[68];
int[] listedDefinition = new int[4];
int[] definitionUsed = new int[68];
int i;
int Size = 68;
int Other = 4;
double[] alpha = new double[68];
int count = 0;
code[0] = "10-0" ; definition[0] = "Disappeared";
code[1] = "10-1" ; definition[1] = "Frequency Change";
code[2] = "10-2" ; definition[2] = "Negative";
code[3] = "10-3" ; definition[3] = "Stop Transmitting";
code[4] = "10-4" ; definition[4] = "Affirmative";
code[5] = "10-5" ; definition[5] = "Relay Message";
code[6] = "10-6" ; definition[6] = "Busy";
code[7] = "10-7" ; definition[7] = "Out Of Service";
code[8] = "10-8" ; definition[8] = "In Service";
code[9] = "10-9" ; definition[9] = "Repeat";
code[10] = "10-10" ; definition[10] = "Fight In Progress";
code[11] = "10-11" ; definition[11] = "Traffic Stop";
code[12] = "10-12" ; definition[12] = "Standby";
code[13] = "10-13" ; definition[13] = "Gun Shots";
code[15] = "10-15" ; definition[15] = "Subject en Route to station";
code[16] = "10-16" ; definition[16] = "Stolen Vehicle";
code[17] = "10-17" ; definition[17] = "Suspicious Person";
code[19] = "10-19" ; definition[19] = "Active Ride Along";
code[20] = "10-20" ; definition[20] = "location";
code[22] = "10-22" ; definition[22] = "Disregard";
code[23] = "10-23" ; definition[23] = "Arrived on scene";
code[25] = "10-25" ; definition[25] = "Do you have contact with ?";
code[26] = "10-26" ; definition[26] = "ETA";
code[27] = "10-27" ; definition[27] = "Drivers license check for valid";
code[28] = "10-28" ; definition[28] = "license Plate check";
code[29] = "10-29" ; definition[29] = "NCIC Warrant Check";
code[30] = "10-30" ; definition[30] = "Wanted Person";
code[31] = "10-31" ; definition[31] = "Armed Suspect";
code[32] = "10-32" ; definition[32] = "Request Backup, Code 1,2,3";
code[34] = "10-34" ; definition[34] = "Wanted Person";
code[35] = "10-35" ; definition[35] = "Not Wanted No Warrants";
code[38] = "10-38" ; definition[38] = "Suspicious Vehicle";
code[41] = "10-41" ; definition[41] = "Beginning Tour Of Duty";
code[42] = "10-42" ; definition[42] = "Ending Tour Of Duty";
code[43] = "10-43" ; definition[43] = "Information About ?";
code[46] = "10-46" ; definition[46] = "Attempt Of Suicide";
code[49] = "10-49" ; definition[49] = "Drag Racing";
code[50] = "10-50" ; definition[50] = "vehicle Accident";
code[51] = "10-51" ; definition[51] = "Request Towing Service";
code[52] = "10-52" ; definition[52] = "Request EMS";
code[53] = "10-53" ; definition[53] = "Request Fire Department";
code[54] = "10-54" ; definition[54] = "Hit And Run";
code[55] = "10-55" ; definition[55] = "Intoxicated Driver";
code[56] = "10-56" ; definition[56] = "Intoxicated Pedestrian";
code[60] = "10-60" ; definition[60] = "Assault By An Animal";
code[61] = "10-61" ; definition[61] = "Bicycle Theft";
code[62] = "10-62" ; definition[62] = "Kidnapping";
code[63] = "10-63" ; definition[63] = "Radio Check";
code[64] = "10-64" ; definition[64] = "Sexual Assualt";
code[65] = "10-65" ; definition[65] = "Armed Robbery";
code[66] = "10-66" ; definition[66] = "Reckless Driver";
code[67] = "10-67" ; definition[67] = "Fire";
code[70] = "10-70" ; definition[70] = "Foot Pursuit";
code[71] = "10-71" ; definition[71] = "Request Supervisor On Scene";
code[72] = "10-72" ; definition[72] = "Administrative Assistance";
code[73] = "10-73" ; definition[73] = "Advise Status";
code[74] = "10-74" ; definition[74] = "Negative";
code[76] = "10-76" ; definition[76] = "Prowler";
code[80] = "10-80" ; definition[80] = "Vehicle Pursuit";
code[85] = "10-85" ; definition[85] = "Delay Due To";
code[86] = "10-86" ; definition[86] = "Any Traffic For me?";
code[88] = "10-88" ; definition[88] = " Requesting Deputy Chief (Department)";
code[89] = "10-89" ; definition[89] = "Requesting Chief (Department)";
code[90] = "10-90" ; definition[90] = "Warning";
code[91] = "10-91" ; definition[91] = "Unnecessary use of Radio";
code[93] = "10-93" ; definition[93] = "Bank Alarm";
code[97] = "10-97" ; definition[97] = "In route";
code[99] = "10-99" ; definition[99] = "Officer In Distress EXTREME EMERGENCY ONLY";
do
{
answer = myRandom.nextInt(68);
System.out.println("\nCode Is : " + code [answer] + "\n");
for (i = 0;i<Size;i++) {
int j;
do
{
j = myRandom.nextInt(68);
}
while (definitionUsed[j] != 0 || j == answer);
definitionUsed[j] = 1;
listedDefinition[i] = j;
}
listedDefinition[myRandom.nextInt(4)] = answer;
for (i = 0;i<Other;i++)
{
System.out.println((i + 1) + " - " +
definition[listedDefinition[i]]);
}
System.out.print("\nWhat is The definition? (Enter 0 to Stop) ");
definitionSelected = myScanner.nextInt();
if (definitionSelected != 0)
{
if (listedDefinition[definitionSelected - 1] == answer)
System.out.println("That's It Good Job");
}
else
{
System.out.println("Sorry, The answer is " + definition +".");
}
}
while (definitionSelected != 0);
}
}
You have defined an array of size 68 and you are trying to use it beyond this size. Since size of array cannot be dynamically increased. So we get the exception, Array index out of bounds. If you want the size to change dynamically use ArrayList.
You have to fix initial array size.
In your code you have:
code[99] = "10-99"
and
definition[99] = "Officer In Distress EXTREME EMERGENCY ONLY";
In both cases you are trying to assing to position 99 so it means that you have at least 100 element (because for 100 elements positions are from 0 to 99).
So you have to change your initial size from 68 to 100 in those lines:
String[] code = new String[68];
String[] definition = new String[68];
int[] listedDefinition = new int[4];
int[] definitionUsed = new int[68];
double[] alpha = new double[68];
to:
String[] code = new String[100];
String[] definition = new String[100];
int[] listedDefinition = new int[100];
int[] definitionUsed = new int[100];
double[] alpha = new double[100];
This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}
My array has an unfixed size as it depends on the user input for the number of modules entered so I really don't know what to do when I run this code and got this error: ArrayIndexOutOfBoundsException: 0
Module[] array = new Module[moduleno];
String[] a = new String[moduleno];
String[] b = new String[moduleno];
int[] c = new int[moduleno];
String[] Output = new String[moduleno];
String endoutput="";
//Method for input of number of modules
moduleno = Student.modno();
for (int i = 0; i < moduleno; i++) {
modulename = Student.MakingModName(i);
grade = Student.readGrade(i);
cu = Student.readCredits(i);
value = Student.GradeValue(grade);
score = Student.calculateScore(value, cu);
totalScore += score;
totalCu += cu;
GPA = Student.calculateGPA(totalCu, totalScore);
//Error occurs here.
**array[i] = new Module(modulename,grade,cu);**
a[i] = array[i].getModulename();
b[i] = array[i].getGrade();
c[i] = array[i].getCu();
Output[i] = a[i] + " " +b[i]+" " +c[i]+" ";
endoutput = endoutput + Output[i] + "\n";
}
This sequence of statements:
Module[] array = new Module[moduleno];
moduleno = Student.modno();
does not magically resize the array that has been allocated previously. You need to do it the other way round:
moduleno = Student.modno();
Module[] array = new Module[moduleno];
Move the statement
moduleno = Student.modno(); // this should be the value while you initialize the array
before you initialize your arrays.
//Add This line before initialize your array
**moduleno = Student.modno();**
Module[] array = new Module[moduleno];
String[] a = new String[moduleno];
String[] b = new String[moduleno];
int[] c = new int[moduleno];
String[] Output = new String[moduleno];
String endoutput="";
Reason :
By default your moduleno variable contains 0(Zero) size so your all arrays size is also 0(Zero).
And you try to add 1 element in array but size of array is zero so it gives ArrayIndexOutBoundsException.
I have the following little problem... I have this code that uses the method OpenFile() of one class ReadData to read a .txt file and also I have another class ArraysTZones used to create an object that stores 3 arrays (data1,data2,data3) and 3 integers (total1,total2,total3) returned by the method OpenFile(). The problem is that when I try to display each array (data1,data2,data3) using the method getArray() of ArrayTZones it stops and displays the error NullPointerException. Anyone knows how could I fix this?
public static void main (String args[]) throws IOException {
String fileName = ".//data.txt";
int[] def = new int[180];
try {
ReadData file = new ReadData(fileName);
ArraysTZones summaryatz = new ArraysTZones();
summaryatz = file.OpenFile();
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray1()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal1());
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray2()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal2());
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray3()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal3());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
Heres OpenFile()
public ArraysTZones OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
int numberOfTimeZones = 3;
int[] data1 = new int[180];
int[] data2 = new int[180];
int[] data3 = new int[180];
int total1 = 0;
int total2 = 0;
int total3 = 0;
ArraysTZones atz = new ArraysTZones();
for (int i = 0; i < numberOfTimeZones; i++){
if (i == 0) {
String firstTimeZone = textReader.readLine();
String[] val = firstTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total1 += stats;
data1[u] = stats;
}
total1= total1/180;
atz.setTotal1(total1);
atz.setArray1(data1);
}
else
if (i == 1) {
String secondTimeZone = textReader.readLine();
String[] val = secondTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total2 += stats;
data2[u] = stats;
}
total2= total2/180;
atz.setTotal2(total2);
atz.setArray2(data2);
}
else {
String thirdTimeZone = textReader.readLine();
String[] val = thirdTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total3 += stats;
data3[u] = stats;
}
total3= total3/180;
atz.setTotal3(total3);
atz.setArray3(data3);
}
}
textReader.close();
return atz;
}
The getArray()
public int[] getArray1 () {
return data1;
}
And setArray()
public void setArray1 (int[] farray) {
int[] data1 = new int[180];
//int[] farray = new int[180];
data1 = farray;
}
The problem seems to be here
public void setArray1 (int[] farray)
{
int[] data1 = new int[180];
//int[] farray = new int[180];
data1 = farray;
}
You're declaring a new variable called data1 and storing the content of farray to it.
After that method is done, that variable will be removed, due to his scope.
Remove int[] from the line int[] data1 = new int[180]; (or just remove the whole line .. it is unnecessary) and your data will be stored in the correct variable that was declared for the class.
public void setArray1 (int[] farray) {
data1 = farray;
}
You have to initialize ArraysTZones
I'm having one problem in show my ListView correctly
If I declare
String[] cod = {"cod1","cod2", "cod3"};
String[] desc = {"desc1","desc2", "desc3"};
String[] preco = {"1.00","2.00", "3.00"};
My adapter is:
lista = (ListView)findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
It works perfectly!
But if I get the data from a database, the ListView shows only one row.
results = DbHelper.getItemsDao().queryRaw(sqlGetItems);
/*GET ALL RESULTS FROM DATABASE*/
List<String[]> array = results.getResults();
int count = array.size();
String[] cod = null, desc = null, preco = new String[count];
for(int i = 0; i < count; i++) {
String[] res = array.get(i);
cod = new String[]{res[0]} ;
desc = new String[]{res[1]};
preco = new String[]{res[3]};
}
lista = (ListView) findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
Try this solution:
for(int i = 0; i < count; i++) {
String[] res = array.get(i);
cod.add(res[0]) ;
desc.add(res[1]);
preco.add(res[3]);
}
Look at the code carefully:
for(int i = 0; i<count; i++){
String[] res = array.get(i);
cod = new String[]{res[0]} ;
desc = new String[]{res[1]};
preco = new String[]{res[3]} ;
}
lista=(ListView)findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
Here, the varables cod, desc and preco are created every time in the loop. So they are the last one at the end.
You can try like as follows:
String[] cod = new String[count];
String[] desc = new String[count];
String[] preco = new String[count];
for(int i = 0; i<count; i++){
String[] res = array.get(i);
cod[i] = res[0] ;
desc[i] = res[1];
preco[i] = res[3] ;
}