java - Sorting an array of objects? user input and comparator -


this question has answer here:

trying sort array of objects overallvisits greatest smallest error. goal pass in website objects array have them sorted out according greatest overall visit least visit. following error: exception in thread "main" java.lang.nullpointerexception @ java.util.comparabletimsort.binarysort(comparabletimsort.java:258) @ java.util.comparabletimsort.sort(comparabletimsort.java:185) @ java.util.arrays.sort(arrays.java:1246) @ project1.main(project1.java:32)

import java.util.scanner; import java.util.arrays;  public class project1 { public static void main (string args[]) { scanner input = new scanner(system.in);  website [] websites = new website[20];  string temp; string temp2; int days = 4;       for(int i=0; < 10; i++)  {       system.out.println("enter url of website:");       temp = input.nextline();       websites[i] = new website();       websites[i].seturl(temp);        system.out.println("enter name of website:");       temp2 = input.nextline();       websites[i].setname(temp2);    }   arrays.sort(websites);   for(int = 0; i<10; i++)  {       system.out.println("url:" + websites[i].geturl()+ " current visits:" +      websites[i].getcurvisit() + " overall visits:" + websites[i].getovrvisit());        system.out.println("name of website:" + websites[i].getname());   }  } } //class 2:  import java.util.scanner;  import java.util.random;   public class website implements comparable <website> {  private string url;  private string name;  private int currentvisit;  private int overallvisit;   public website()  {    this.url = url;    this.name = name;    this.currentvisit = getrandom1();    this.overallvisit = getrandom2();   }   public string geturl()  {   return url;  }   public void seturl(string s) {   url = s; }    public string getname() {   return name; }  public void setname(string n) {   name = n; }    public int getrandom1() {  random rand = new random();   int num = rand.nextint(4);  return num; }    public int getrandom2() {  random rand = new random();   int num2 = 10 + rand.nextint(11);  return num2; }  public int getcurvisit() {  return currentvisit; }  public int getovrvisit() {   return overallvisit; }  public int compareto(website comparevisit) {   int compareall = ((website) comparevisit).getovrvisit();   return compareall - this.overallvisit; } } 

you're getting java.lang.nullpointerexception because have allocated 20 elements in array have filled 10.

new array

website [] websites = new website[20]; 

filling array

for(int i=0; < 10; i++) 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -