Hey everyone so I have a very large array that has names and popularity ranks listed in them, and generally the lower the number the more popular that name is. I need a way to search through the array to find 20 of the lowest numbers for a certain decade. So let me show you what my list looks like and my code.
This is my list.
And here is my code:
Name
public class Name{
private String givenName;
private int[] ranks = new int[11];
public Name(String name, int[] popularityRanks){
givenName = name;
for (int i = 0; i < 11; i++){
ranks[i] = popularityRanks[i];
}
}
public String getName(){
return givenName;
}
public int getPop(int decade){
if (decade >= 1 && decade <= 11){
return ranks[decade];
}
else{
return -1;
}
}
public String getHistoLine(int decade){
String histoLine = ranks[decade] + ": ";
return histoLine;
}
public String getHistogram(){
String histogram = "";
for (int i = 0; i < 11; i++){
histogram += ranks[i] + ": " + this.getHistoLine(i)
+ "\n";
}
return histogram;
}
}
And then NameApp:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NameApp{
private static boolean validInput;
private static boolean stillWorking = true;
private static boolean validDecade;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException{
String[] nameArray = readNamesFile();
Name[] list = new Name[nameArray.length];
loadNames(list, nameArray);
char choice;
do {
do {
displayMenu();
choice = getUserInput();
} while (!validInput);
switch (choice){
case 'A':
displayHistogram(list);
break;
case 'B':
compareTwoNames(list);
break;
case 'C':
displayTopTenNames(list);
break;
case 'D':
writeAnomaliesToFile(list);
stillWorking = false;
break;
default:
break;
}
} while (stillWorking);
}
private static String[] readNamesFile() throws FileNotFoundException{
String[] nameArray = new String[4429];
Scanner inputStream = null;
String fileName = "names.txt";
inputStream = new Scanner (new File(fileName));
int i = 0;
while (inputStream.hasNextLine()){
nameArray[i] = inputStream.nextLine();
i++;
}
inputStream.close();
return nameArray;
}
private static void loadNames(Name[] list, String[] nameArray){
int length;
int spacePos;
int[] popRanks = new int[11];
String name;
String linePop;
for (int i = 0; i < nameArray.length; i++){
length = nameArray[i].length();
spacePos = nameArray[i].indexOf(" ");
name = nameArray[i].substring(0,spacePos);
linePop = nameArray[i].substring(spacePos + 1, length);
for (int j = 0; j < 11; j++){
popRanks[j] = Integer.parseInt(linePop.split(" ")[j]);
}
list[i] = new Name(name, popRanks);
}
}
private static void displayMenu(){
System.out.println("Enter the character corresponding to your selection:");
System.out.println("\ta - Print histogram for a name");
System.out.println("\tb - Compare two names in a decade");
System.out.println("\tc - Print top ten names for a decade");
System.out.println("\td - Quit (display file anomalies)");
}
private static char getUserInput(){
String selection = keyboard.nextLine();
System.out.println(" Your selection: " + selection);
checkUserInput(selection);
char choice = stringToChar(selection);
return choice;
}
private static boolean checkUserInput(String selection){
if (!selection.equalsIgnoreCase("a") && !selection.equalsIgnoreCase("b") && !selection.equalsIgnoreCase("c") && !selection.equalsIgnoreCase("d")){
System.out.println("Invalid input. Try again...");
return validInput = false;
}
else {
return validInput = true;
}
}
private static char stringToChar(String selection){
char choice = selection.charAt(0);
choice = Character.toUpperCase(choice);
return choice;
}
private static void displayHistogram(Name[] list){
String nameInput;
String histogram;
int nameLocation;
nameInput = nameEntry();
nameLocation = checkListArray(nameInput, list);
histogram = list[nameLocation].getHistogram();
System.out.println("Histogram for name, " + list[nameLocation].getName() + ":");
System.out.println(histogram);
}
private static void compareTwoNames(Name[] list){
String nameOne;
String nameTwo;
String oneHistoLine;
String twoHistoLine;
int oneLocation;
int twoLocation;
int decade;
nameOne = nameEntry();
oneLocation = checkListArray(nameOne, list);
nameTwo = nameEntry();
twoLocation = checkListArray(nameTwo, list);
decadeMenu();
decade = decadeSelection();
oneHistoLine = list[oneLocation].getHistoLine(decade);
twoHistoLine = list[twoLocation].getHistoLine(decade);
System.out.println("Data for " + list[oneLocation].getName());
System.out.println(" " + oneHistoLine);
System.out.println("Data for " + list[twoLocation].getName());
System.out.println(" " + twoHistoLine);
}
private static void displayTopTenNames(Name[] list){
int decade;
int temp = 1000;
int tempTwo;
String[] topTen = new String[20];
decadeMenu();
decade = decadeSelection();
for (int i = 0; i < 20; i++){
for (int j = 0; j < list.length; j++){
if (list[j].getPop(decade) > 0 && list[j].getPop(decade) < temp){
temp = list[j].getPop(decade);
tempTwo =
}
}
}
}
private static void writeAnomaliesToFile(Name[] list){
}
private static String nameEntry(){
String nameInput = "";
System.out.println("Enter a name: ");
nameInput = keyboard.nextLine();
return nameInput;
}
private static int checkListArray(String nameInput, Name[] list){
int nameLocation = -1;
int listLength = list.length;
for (int i = 0; i < listLength; i++){
if (nameInput.equalsIgnoreCase(list[i].getName())){
return nameLocation = i;
}
}
if (nameLocation == -1){
System.out.println("The name, " + nameInput + ", was not found!");
return nameLocation;
}
return nameLocation;
}
private static void decadeMenu(){
System.out.println("Enter number correpsonding to your decade:");
System.out.println(" 1 - 1900-1909");
System.out.println(" 2 - 1910-1919");
System.out.println(" 3 - 1920-1929");
System.out.println(" 4 - 1930-1939");
System.out.println(" 5 - 1940-1949");
System.out.println(" 6 - 1950-1959");
System.out.println(" 7 - 1960-1969");
System.out.println(" 8 - 1970-1979");
System.out.println(" 9 - 1980-1989");
System.out.println(" 10 - 1990-1999");
System.out.println(" 11 - 2000-2005");
}
private static int decadeSelection(){
String decadeChoice;
int decade;
do {
System.out.println("Enter a decade: ");
decadeChoice = keyboard.nextLine();
decade = checkDecade(decadeChoice);
} while (!validDecade);
return decade;
}
private static int checkDecade(String decadeChoice){
int decade = 0;
try {
decade = Integer.parseInt(decadeChoice);
}
catch (Exception e){
System.out.println("That is not an integer. Please try again.");
return decade;
}
if (decade < 1 || decade > 11){
System.out.println("Enter an integer between 1 and 11");
validDecade = false;
return decade;
}
else {
validDecade = true;
return decade;
}
}
}
so where I need help at is the displayTopTenNames method. I was sort of messing around with it a bit earlier but every loop that I have come up with always makes duplicates that I don't want... Anyway my output should look like this:
Ten most popular names (male and female) during the decade 1910-1919 were:
John (1) Mary (1)
Helen (2) William (2)
Dorothy (3) James (3)
Margaret (4) Robert (4)
Joseph (5) Ruth (5)
George (6) Mildred (6)
Anna (7) Charles (7)
Edward (8) Elizabeth (8)
Frances (9) Frank (9)
Marie (10) Walter (10)
so yeah help would be much appreciated and thanks in advance.
There are probably more efficient ways to do this, but this shows the theory. You maintain a small list of 20 items. You scan your large list to see if its a candidate for your short list. If the list is small than 20, anything gets added. If it has reached 20, you check to see if anything in the list is larger than the item you would like to add. if it is, this item is evicted and replaced with the smaller value.
public class Low20 {
private List<Integer> list = new ArrayList<Integer>();
public static final void main(String[] args) {
new Low20();
}
public Low20() {
Random random = new Random();
for (int x=0;x<100000;x++) {
add(random.nextInt(100000));
}
System.out.println(list);
}
public void add(int value) {
if (list.size() < 20) {
list.add(value);
} else {
for (int x=0;x<list.size();x++) {
if (list.get(x) > value) {
list.remove(x);
list.add(value);
return;
}
}
}
}
}
The result. (random numbers, but the lowest 20). You could then sort these, or incorporate sort into the eviction algorithm.
[6, 0, 5, 17, 18, 11, 10, 27, 22, 27, 28, 16, 34, 33, 0, 8, 28, 0, 15, 14]
The benefit of this method over using a blanket sort on your list, is that your list doesn't have to fit in memory and can be applied from a file or database scan.
Check out Arrays.sort() method:
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
Related
In this program, I want the user to type in 20 product names. from the main method. which will pass down to the method named searchProducts. But for some reason, it doesn't work. It only let me type in once, and then it prints out all 16 products.
public static void main(String[] args) {
String[] products= {"Pencil pouch", "pen", "Pencil sharpener", "High lighters", "Markers", "Erasers",
"Binder", "Notebooks", "Index cards", "Folders", "Glue", "Ruler", "Scissors", "Calculator",
"Calendar", "Backpack"};
System.out.println("Unordered list");
displayProducts(products);
sortProducts(products, 16);
System.out.println("");
System.out.println("Ordered list");
displayProducts(products);
}
private static int searchProducts(String[] products) {
Scanner sc = new Scanner(System.in);
String x = sc.nextLine();
System.out.println("Enter name of product: ");
for (int i = 0; i < products.length; i++) {
if (products[i].equals(x))
return i;
}
return -1;
}
private static void sortProducts(String products[],int n) {
for(int i = 0; i < n - 1; i++) {
int minindex = i;
String minStr = products[i];
for(int j = i + 1; j < n; j++) {
if(products[j].compareTo(minStr) < 0)
{
minStr = products[j];
minindex = j;
}
}
if(minindex != i)
{
String temp = products[minindex];
products[minindex] = products[i];
products[i] = temp;
}
}
}
private static void displayProducts(String[] products) {
for(int i = 0; i < products.length; i++){
System.out.println(products[i] + " ");
}
}
The way you pass array parameter is just good.
There are several ways to pass arrays as parameter:
(/*Other params,*/ String[] param) // this way
(String[] param /*, Other params*/) // or
(/*Other params,*/ String param[]) // this way
(String param[] /*, Other params*/) // or
// special case
// only as unique or last param of the params
// because with it you can enter several String params as individuals
(/*Other params, */ String... param)
// arrays of arrays
(String[] param[])
(String[][] param)
(String param[][] )
This is your problem:
sortProducts(products, 20);
...
private static void sortProducts(String products[],int n) {
You pass 20 although your array is 16 sized. So error.
Change this way to not depend on the size.
sortProducts(products);
....
private static void sortProducts(String products[]) { // no size passed
int n = products.length; // read the size from the array
EDIT 1 -------------
In the code below, the user to type in N products. Then the array is printed, sorted and printed. (NOT TESTED)
public static void main(String[] args) {
int N = 20;
String[] products = new String[N];
Scanner sc = new Scanner(System.in);
for(int i=0; i < N; i++) {
System.out.println("Enter name of product "+ (i+1) +" : ");
String x = sc.nextLine();
products[i] = x;
}
System.out.println("Unordered list");
displayProducts(products);
sortProducts(products);
System.out.println("");
System.out.println("Ordered list");
displayProducts(products);
// search block
}
To search in the array, you can do something like that (NOT TESTED):
public static void main(String[] args) {
// ... previous code
// search block in main method
System.out.println("Enter name of product to search, or \"stop\" to stop : ");
String y = sc.nextLine();
while(y != "stop") {
int index = searchProducts(products, y);
if( index == -1 )
System.out.println("Product "+ y +" is not in array");
else
System.out.println("Product "+ y +" is at position "+ index);
System.out.println("Enter name of product to search, or \"stop\" to stop : ");
y = sc.nextLine();
}
}
private static int searchProducts(String[] products, String p) {
for (int i = 0; i < products.length; i++) {
if (products[i].equals(p))
return i;
}
return -1;
}
This is the Main.java
Scanner input = new Scanner(System.in);
String in="t";
String [] t=new String[15];
int c=0;
int p=0;
String n="p";
for(int i=0;i<15;i++){
System.out.print("Enter a topping (or type quit):");
n=input.nextLine();
if(n.equals("quit")){
i=16;
p=1;
}else
t[i]=n;
c++;
}
String [] q=new String[c];
if(t[c-1]==null){
q=new String[c-1];
for(int u=0;u<c-1;u++){
q[u]=t[u];
}
Arrays.sort(q);
if(p==0){
System.out.println("No more toppings allowed.");
}
for(int o=0;o<c-1;o++){
System.out.println((o+1)+". "+q[o]);
}
}
else{
q=new String[c];
for(int u=0;u<c;u++){
q[u]=t[u];
}
Arrays.sort(q);
if(p==0){
System.out.println("No more toppings allowed.");
}
for(int o=0;o<c;o++){
System.out.println((o+1)+". "+q[o]);
}
}
BinarySearch bs = new BinarySearch();
System.out.println("\nWhat do you want to search for?");
String search = input.nextLine();
System.out.println("BinarySearch: "+bs.binarySearch(q, search));
This is the BinarySearch.java class
public void printTopping() {
}
public boolean addTopping(String top) {
}
public int binarySearch(String[] words, String key) {
int left = 0;
int right = words.length - 1;
int mid = 0;
while (left <= right) {
mid = (left + right) / 2;
if ((words[mid] + "").trim().compareTo(key.trim()) < 0) {
left = mid + 1;
} else if ((words[mid] + "").trim().compareTo(key.trim()) > 0) {
right = mid - 1;
} else {
return mid;
}
}
return -1;
}
How do I use the addTopping method to add an topping into the q array in main without there being a String array parameter in the addTopping method? Can I get help writing this method? Then How would i do printTopping() method?
This is the direction :
In main:
String[] toppingStringArray = Arrays.copyOf(q, q.length + 1);
In addTopping:
toppingStringArray[toppingStringArray.length - 1] = top;
I am making a multiple string input random swap without using a temp variable.
But when I input, this happens a few times:
This happens more frequently... (note that the first output is always null and some outputs occasionally repeat)
My code:
import java.util.Arrays;
import java.util.Scanner;
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
String[] swappedInput = new String[input.length];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter > 0) {
do{
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + swappedInput[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}
Because of randomality some times useCounter is the same as swapCounter and now look at those lines (assume useCounter and swapCounter are the same)
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
In the second line you are changing the value of xxx#www to be www so in the third line when doing split you dont get an array with two values you get an empty result thats why exception is thrown in addition you should not use swappedInput because it beats the pourpuse (if i understand correctly yoush shoud not use temp values while you are using addition array which is worse) the correct sollution is to only use input array here is the solution
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter >= 0) {
do {
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
// Skip if results are the same
if (useCounter == swapCounter) {
swapCounter++;
continue;
}
input[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
input[useCounter] = input[swapCounter].split("#")[0];
input[swapCounter] = input[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + input[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}
i was wondering how can i create a method where i can get the single instance from a string and give it a numericValue for example, if theres a String a = "Hello what the hell" there are 4 l characters and i want to give a substring from the String a which is Hello and give it numeric values. Right now in my program it gets all the character instances from string so the substring hello would get number values from the substring hell too because it also has the same characters.
my code :
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "help + me = please";
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c) - 9;
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Long.parseLong(first)+ Long.parseLong(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("One word can only be less than 18 chars");
}
}
return words;
}
Program has to solve the word puzzles where you have to guess which digit corresponds to which letter to make a given equality valid. Each letter must correspond to a different decimal digit, and leading zeros are not allowed in the numbers.
For example, the puzzle SEND+MORE=MONEY has exactly one solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, giving 9567+1085=10652.
import java.util.ArrayList;
public class main {
private static String ChangeString;
private static String[] ArrayA;
private static String a;
private static int wordnumber;
private static String temp;
public static void main(String[] args) {
// TODO Auto-generated method stub
a = "hello what the hell";
wordnumber = 0;
identifyint(a,wordnumber);
}
public static void identifyint (String a, int WhichWord){
ChangeString = a.split(" ")[WhichWord];
ArrayA = a.split(" ");
replaceword();
ArrayA[wordnumber] = ChangeString;
//System.out.print(ArrayA[wordnumber]);
a = "";
for(int i = 0; i<ArrayA.length;i++){
if(i==wordnumber){
a = a.concat(temp+ " ");
}
else{
a = a.concat(ArrayA[i]+" ");
}
}
System.out.print(a);
}
public static void replaceword(){
temp = "";
Character arr[] = new Character[ChangeString.length()];
for(int i = 0; i<ChangeString.length();i++){
arr[i] = ChangeString.charAt(i);
Integer k = arr[i].getNumericValue(arr[i])-9;
temp = temp.concat(""+k);
}
a = temp;
}
}
Change wordnumber to the word you want to replace each time. If this is not what you have asked for, please explain your question in more detail.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
Below is the error:
Exception in thread "main" java.lang.NullPointerException
at CellularData.addCountry(CellularData.java:34)
at CellularData.addCountry(CellularData.java:24)
at TestCSVReader.main(TestCSVReader.java:35)
I keep getting the error above but seem to have trouble fixing it. I am reading from a csv file and displaying the data on the screen. Basically it reads country, the year, and it stats of a cellular data in double. Below is CellularData class:
public class CellularData {
private Object [][]array;
private int year;
public CellularData(int rows, int columns, int year)
{
array = new Object[rows+1][columns+1]; //add +1 because initializes the header.
this.year = year;
for(int i=1;i<=columns;i++)
{
array[0][i] = year++; //increments the year
}
}
public void addCountry(String country, double []num)
{
for(int i=0;i<array.length;i++)
{
if(array[i][0] == null) //checks if the first row is empty
{
//CellularData.addCountry(CellularData.java:24)
addCountry(country, num, i); //inserts the data
break;
}
}
}
private void addCountry(String country, double []num, int row)
{
array[row][0] = country;
for(int j = 1;j<array[row].length;j++)
{
array[row][j] = num[j-1]; //CellularData.addCountry(CellularData.java:34)
}
}
public double getNumSubscriptionsInCountryForPeriod(String country, int sYear, int eYear)
{
double sum = 0;
for (int i = 1; i < array.length; i++) {
if (country.equalsIgnoreCase((String) array[i][0])) { //matches with the parameters passed ignoring CAPS
int start = 1 + sYear - year; //first index position of the year
int end = start + (eYear - sYear); //end position of the year
if (start >= 0 && end < array[i].length) { //checks to see if index position is out of bounds
for (int k = start; k <= end; k++) {
// System.out.println(">> " + country + " adding " + array[i][k]);
sum += (Double) array[i][k]; //sum of the stats
}
}
else {
//returns Error messgae and -1
System.out.println("ERROR : requested year "+sYear+" from "+ country+" is less than starting year "+this.year);
sum = -1;
}
}
}
return sum;
}
public String toString()
{ //prints the array.
for(Object []a: array)
{
for(Object k:a)
{
System.out.print(k + "\t");
}
System.out.println();
}
return " ";
}
}
Here is my csv reader file and this where i read from the file:
public class CSVReader {
String[] countryNames;
int[] yearLabels;
double[][] cellularDatatables;
Scanner scan;
public CSVReader(String filename)// throws FileNotFoundException
{
try{
File file = new File(filename);
scan = new Scanner(file);
scan.nextLine();
String numLine = scan.nextLine();
final int n = Integer.parseInt(numLine.split(",")[1]); //Number is the string portion after the first comma
//Allocate arrays with length n
countryNames = new String[n];
cellularDatatables = new double[n][];
//Read in the header line of years, parse and copy into yearNum
String[] yearHeaders = scan.nextLine().split(",");
final int m = yearHeaders.length-1;
yearLabels = new int[m];
for(int i=0;i<m;i++)
{
yearLabels[i] = Integer.parseInt(yearHeaders[i+1]); //i+1 to skip the first entry in the string arr
}
//Now read until we run out of lines - put the first in country names and the rest in the table
int c = 0;
while(scan.hasNext())
{
String[] inputArr = scan.nextLine().split(",");
countryNames[c] = inputArr[0];
cellularDatatables[c] = new double[m];
for(int i = 0; i < m; i++)
{
cellularDatatables[c][i] = Double.parseDouble(inputArr[i+1]);
}
}
scan.close();
}
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
public String[] getCountryNames(){
return countryNames;
}
public int[] getYearLabels(){
return yearLabels;
}
public double[][] getParsedTable(){
return cellularDatatables;
}
public int getNumberOfYears()
{
return yearLabels.length;
}
}
And also TestCSVReader file:
public static void main(String[] args)
{
final String FILENAME = "data/cellular.csv";
CSVReader parser = new CSVReader(FILENAME);
String [] countryNames = parser.getCountryNames();
//System.out.println(countryNames.length);
int [] yearLabels = parser.getYearLabels();
//System.out.print(yearLabels.length);
double [][] parsedTable = parser.getParsedTable();
CellularData datatable;
int numRows = parsedTable.length;
int numColumns =parser.getNumberOfYears();
int startingYear = yearLabels[0];
datatable = new CellularData(numRows, numColumns, startingYear);
for (int countryIndex = 0; countryIndex < countryNames.length; countryIndex++)
{
double [] countryData = parsedTable[countryIndex];
datatable.addCountry(countryNames[countryIndex], countryData);//Error TestCSVReader.java:35
}
System.out.printf(countryNames[0] + " (1960 to 2012): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod(countryNames[0],1960,2012));
// the output is: Aruba (1960 to 2012): 1170.50
array[row][0] = country;
for(int j = 1;j<array[row].length;j++)
{
array[row][j] = num[j-1]; //CellularData.addCountry(CellularData.java:34)
}
Since the first line doesn't give NullPointerException, we know that array is not null and array[row] is not null. Therefore, num must be null.