how to call a method through a 2d array error - java

I'm trying to create a new list so that whatever the user enters into the altitude this method should look for the coordinates and return the coordinates below what user has entered. I'm struggling to get this method to run.
static double[][] array;
Map m = new Map();
public static void main(String[] args) throws FileNotFoundException {
m.coordinatesBelow(-2000)
}
public static void readDataArray(String filename) throws FileNotFoundException {
Scanner input = new Scanner(new BufferedReader(new FileReader("sample.xyz")));
int rows = 2500000;
int columns = 3;
double[][] array= new double[rows][columns];
int i = 0;
while (input.hasNextLine()) {
String[] line = input.nextLine().trim().split("\t");
for (int j = 0; j < line.length; j++) {
array[i][j] = Double.parseDouble(line[j]);
}
i++;
}
System.out.println(Arrays.deepToString(array));
}
public List<Double> coordinatesBelow(double altitude) {
List<Double> coordinatesBelow = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
coordinatesBelow.add(array[i][2]);
}
coordinatesBelow.removeIf(b -> b > altitude);
return coordinatesBelow;
}

Your static double[][] array; declared at the first line and double[][] array = new double[rows][columns]; are 2 different variables: the first is static, the second is local. So when you read the values into the local array the static one remains empty.
If you want to save the values into the static array, don't create a new variable, just initialize the static array in your static method - change
double[][] array = new double[rows][columns];
to
array = new double[rows][columns];
UPD: If you are getting a NullPointerException at the line for (int i = 0; i < array.length; i++), the only thing that can be null here is array. So make sure the array is initialized before you call coordinatesBelow. And you initialize it in the readDataArray method, so try calling it first:
public static void main(String[] args) throws FileNotFoundException {
readDataArray("filename.txt");
m.coordinatesBelow(-2000);
}
Bu the way, it looks like the filename argument is not used anywhere, so you can remove it.

You're calling coordinatesBelow as a method of Map. Is this correct? This would need to be a class that you have created yourself like so:
private static class Map {
public List<Double> coordinatesBelow(double altitude) {
List<Double> coordinatesBelow = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
coordinatesBelow.add(array[i][2]);
}
coordinatesBelow.removeIf(b -> b > altitude);
return coordinatesBelow;
}
}

Related

assigning value of one class's instance variable in another class

I am trying to assign value of FileData's instance variable in File class
At first FileData's nextIndex should all be -1, and then it should be assigned the value of counter
I've tried get,set and FileData array to assign value but its not working and
gives NULL POINTER EXCEPTION
I've tried:
class FileData
{
int nextIndex = 0;
public void setIndex()
{
for(int i=0; i<10;i++)
{
nextIndex = -1;
}
}
}
class File
{
public static void main(String args[])
{
FileData[] FD = new FileData[10];
for(int i=0; i<5;i++)
{
FD[i].nextIndex = i;
}
}
}
When working with objects, you first have to create an instance. All I've done is add a declarator in the loop and formatted the code:
class FileData {
int nextIndex = 0;
public void setIndex() {
for (int i = 0; i < 10; i++) {
nextIndex = -1;
}
}
}
class File {
public static void main(String args[]) {
FileData[] FD = new FileData[10];
for (int i = 0; i < 5; i++) {
FD[i] = new FileData();
FD[i].nextIndex = i;
}
}
}
Note that the FileData[] FD = new FileData[10]; bit just declares an array of the type FileData, and does not yet give each object its needed storage space.
The array elements here are null:
FileData[] FD = new FileData[10];
First you need to create the objects:
for(int i=0; i < FD.length ;i++)
{
FD[i] = new FileData();
FD[i].nextIndex = i;
}

Can't use toString to display array

getting the following error message when trying to use toString to display array:
java.lang.NullPointerException
Here's the code:
import java.util.Scanner;
import java.util.Random;
public class RandomArray {
private int data[];
private int value;
public RandomArray(int x)
{
Random gen = new Random();
int[] data = new int[x];
for (int index = 0; index<x; index ++)
data[index] = gen.nextInt(x);
}
public String toString()
{
String output = "";
for(int i = 0; i<data.length; i++)
{
output +=data[i];
}
return output;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x;
int data;
System.out.println("please enter the number of integers you would like to create an array for");
x = scan.nextInt();
RandomArray table = new RandomArray(x);
table.toString();
From what I can tell this error means the toString is throwing null? But I do not know why that is, can anyone help me out?
You are redeclaring your data array which is hiding the one you are filling.
Random gen = new Random();
int[] data = new int[x]; // remove the int[] declaration
Also, it might be easier if you just did the following:
// your toString method
public String toString() {
return Arrays.toString(data);
}
In response to your question, you can do this.
int[] data; // you did this - leave it alone
// and later you should do this.
public RandomArray(int x) {
Random gen = new Random();
data = new int[x]; // designated as an array above
for (int index = 0; index<x; index ++)
data[index] = gen.nextInt(x);
}
}

Manually sorting an ArrayList of strings alphabetically in Java

I am trying to reorder an ArrayList alphabetically for an assignment. I am not allowed to use any methods for automatically sorting, it has to be done manually. This is the code I tried, but it does not even run. I appreciate any input on this.
import java.util.ArrayList;
public class SortArrayList {
public static void main(String[] args) {
ArrayList<String> values = new ArrayList<String>();
public static void main(String[] args) {
ArrayList<String> values = new ArrayList<String>();
values.add("car");
values.add("bear");
values.add("apple");
values.add("xray");
sort(values);
for (int i = 0; i < values.size(); i++)
System.out.println(values.get(i));
}
public static void sort(ArrayList<String> x) {
String temp;
for (int i = 0; i < x.size() - 1; i++) {
for (int j = i + 1; j < x.size(); j++) {
if (x.get(i).compareToIgnoreCase(x.get(j)) > 0) {
temp = x.get(i);
x.add(i,x.get(j));
x.add(j,temp);
}
}
}
}
}
The lines
x.add(i,x.get(j));
x.add(j,temp);
are adding more elements to the ArrayList. You should change them to
x.set(i, x.get(j));
x.set(j, temp);
so that it replaces the elements at those positions.
Unless the multiple calls to public static void main(String[] args) was a typo when you copied it across for your question this would cause issues when running the program as it won't know where to start

I am trying to create a method that calculates the averages of numbers in two arrays

import java.io.*;
import java.util.*;
public class Marks {
public static void main(String[] args) {
Marks r = new Marks();
double[] finalArray = r.openFile();
double[] finalArray2 = r.openFile2();
}
//ID's and first set of grades
private Scanner a;
public double[] openFile() {
ArrayList<String> list1 = new ArrayList<String>(7);
try {
a = new Scanner(new File("IR101.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (a.hasNextLine()) {
list1.add(a.nextLine());
}
String[] arrayOne = list1.toArray(new String[list1.size()]);
Arrays.sort(arrayOne);
//System.out.println(Arrays.toString(arrayOne));
int size = arrayOne.length;
double[] finalArray = new double[size];
for (int j = 0; j < size; j++) {
String word = arrayOne[j];
String newWord = word.substring(6, 10);
double grade = Double.parseDouble(newWord);
finalArray[j] = grade;
}return finalArray;
}
//ID's and second set of grades
private Scanner b;
public double[] openFile2() {
ArrayList<String> list2 = new ArrayList<String>(7);
try {
b = new Scanner(new File("IR102.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (b.hasNextLine()) {
list2.add(b.nextLine());
}
String[] arrayTwo = list2.toArray(new String[list2.size()]);
Arrays.sort(arrayTwo);
//System.out.println(Arrays.toString(arrayTwo));
int size = arrayTwo.length;
double[] finalArray2 = new double[size];
for (int j = 0; j < size; j++) {
String word = arrayTwo[j];
String newWord = word.substring(6, 10);
double grade2 = Double.parseDouble(newWord);
finalArray2[j] = grade2;
}return finalArray2;
}
// ID's and names
private Scanner c;
public void openFile3() {
ArrayList<String> list3 = new ArrayList<String>(7);
try {
c = new Scanner(new File("IRStudents.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (c.hasNextLine()) {
list3.add(c.nextLine());
}
String[] arrayThree = list3.toArray(new String[list3.size()]);
Arrays.sort(arrayThree);
//System.out.println(Arrays.toString(arrayThree));
int size = arrayThree.length;
String[] names = new String[size];
for (int j = 0; j < size; j++) {
names[j] = arrayThree[j].substring(6);
}
String[] IDs = new String[size];
for (int x = 0; x < size; x++){
IDs[x] = arrayThree[x].substring(0,5);
}
System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(IDs));
}
public void calculateAvg() {
}
}
I am trying to access the numbers in finalArray and finalArray2 but I am not sure how to do this when I try to call on the two arrays it does not work I think it is to do with the scope of the arrays.So how do I make the two array accessible to the whole program.
If you want to make the two arrays accessible to the whole program, declare them as static variables outside of the main method and initialize inside like seen here:
public class Marks {
static double[] finalArray;
static double[] finalArray2;
public static void main(String[] args) {
Marks r = new Marks();
finalArray = r.openFile();
finalArray2 = r.openFile2();
While you could make the arrays visible to the whole class, it probably makes more sense to pass them to the method which should access them. So do something like this:
public void calculateAvg(double[] array1, double[] array2) {
// ...
}
You can then call it like this:
public static void main(String[] args) {
Marks r = new Marks();
double[] finalArray = r.openFile();
double[] finalArray2 = r.openFile2();
r.calculateAvg(finalArray, finalArray2);
}

Java Arrays - How to create an array using a static method

I am searching for the lines of code to create a new array using a method called insertRow(int[] row). With this method, users can insert 5 numbers to form an array. Then this array should be named row2. Please help.
public class App
{
public static void main(String[] args)
{
int[] row = new int[5];
int[] row1 = {2,7,1,9,4};
//int[] row2 = insertRow(row); this is wrong
}
public static void insertRow(int[] row)
{
for (int i = 0; i < row.length; i++)
{
int number;
do
number = Integer.parseInt(JOptionPane.showInputDialog("Insert the " + (i+1) + "th positif number"));
while (getal < 0);
row[i] = number;
}
}
}
You were on the right track: change the signature of your method to return int[], allocate the row inside, and put your code in place of ... below:
public static int[] insertRow() {
int[] row = new int[5];
...
return row;
}
Now this will work:
int[] row2 = insertRow(); // this is no longer wrong :)

Categories

Resources