Dereferncing Error In Java Array HW - java

I'm getting an error about dereferencing in the following code (I've commented out where it gets caught up)
The main method works fine, but the Mply method is causing me lots of headaches. Hope this is sort of clear.
//multiply matrixes
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.*;
import java.util.StringTokenizer;
public class Assignment1 {
public static void main(String[] args){
int a=5;
int b=2;
int x[][] = new int[a][b];
for(int i=0;i<a;i++)
for(int j=0;j<b;j++)
x[i][j]=0;
System.out.println(x[1][1]);
/*
for(int j= 0; j<
for (int i = 0; i < array.length; i++)
array[i] = s.nextInt();
*/
// read from file
FileInputStream fstream=null;
try{
fstream = new FileInputStream("C:\\javastuff\\principles\\input.txt");
}
catch (Exception e){
System.out.println(e.getMessage());
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(fstream))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
/* StringTokenizer tokenizer = new StringTokenizer(line, " ");
while (tokenizer.hasMoreElements()) {
// parse each integer in file
int i = Integer.parseInt(tokenizer.nextToken());
System.out.println("Number " + i);
}
*/
}
br.close();
}
catch(Exception e){
}
// write to file
BufferedWriter outputWriter = null;
try{
outputWriter = new BufferedWriter(new FileWriter("C:\\javastuff\\principles\\output.txt"));
for (int i = 0; i < a; i++) {
outputWriter.write(Integer.toString(x[i][0]));
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
catch (Exception e){
}
}
public static void Mply(int x[][], int a, int b){ //multiplies arraries and checks if they are same values
int aRows = a.length;
int aColumns = a[0].length;//starts dereferecning herer
int bRows = b.length;
int bColumns = b[0].length;
for (int i=0; i<a; ++i)
for (int j=0; j<b; ++j)
for (int k=0; k<a[0][0].length(); ++k)
x[i][k] += a[i][k] * b[k][j];
}
}

based on the method header for Mply
public static void Mply(int x[][], int a, int b)
The type of x is int[][], the type of a is int, and the type of b is int. Specifically, note that a and b are not arrays.
Thus trying to access them as arrays by using a[0] is illegal.
If you want a and b to be 2-dimensional arrays, you have to update your method header to say that.
public static void Mply(int[][] x, int[][] a, int[][] b)

Related

Read from a text file, sort it, and write it again

So our professor has assigned us with a program which reads a text file he has provided us with; it sorts it, and creates a new file with the sorted stuff. He wants us to call three methods from the main i.e. read, sort, and write
I have done some of the work, but i'm confused what arguments to provide for io.sort. And how do i convert that text thing into an array to provide an argument Here's my code:
public void read() {
try {
Scanner myLocal = new Scanner(new File("dictionary.txt"));
while (myLocal.hasNextLine()) {
System.out.println(myLocal.nextLine());
}
} catch (IOException e) {
System.out.println(e);
}
}
public void sort(String[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
/* ERROR: When j == 0, j - 1 == -1, which is out of bounds */
if (arr[j - 1].compareTo(arr[j]) > 0) {
swap(j, arr);
}
}
}
}
public void swap(int j, String[] arr) {
String temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
public void write() {
try {
PrintStream writer = new PrintStream(new File("sorted.txt"));
for (int i = 0; i < 100; i++) {
writer.println(i);
}
writer.close();
} catch (IOException e) {
System.out.println(e);
}
}
Here is how i've changed my read() method:
public void read()
{
String[] myArray = new String[1000];
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
String a = myLocal.nextLine();
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
class IO{
String[] myArray = new String[30000];
public void read()
{
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
String a = myLocal.nextLine();
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
public void sort()
{
int n = myArray.length;
for (int i=0; i<n-1; i++){
for(int j=0; j<n-i-1; j++){
if(myArray[j+1].compareTo(myArray[j])<0){
String temp = myArray[j];
myArray[j] = myArray[j+1];
myArray[j+1] = temp;
//toLower
}
}
}
}
public void swap(int j, String[] arr)
{
String temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
public void write()
{
try{
PrintStream writer = new PrintStream(new File("sorted.txt"));
for (int i=0; i<myArray.length; i++){
writer.println(myArray[i] + "\n");
}
writer.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
CORRECT CODE (SOLVED)
class IO{
String[] myArray = new String[30000];
public void read()
{
try {
Scanner myLocal = new Scanner( new File("dictionary.txt"));
while (myLocal.hasNextLine()){
for (int i=0; i<myArray.length; i++){
String a = myLocal.nextLine();
myArray[i] = a;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
public void sort()
{
int n = myArray.length;
for (int i=0; i<n; i++){
for(int j=1; j<n-i; j++){
if (myArray[j-1].compareTo(myArray[j])>0){
swap(j, myArray);
}
}
}
}
public void swap(int j, String[] myArray)
{
String temp = myArray[j-1];
myArray[j-1]=myArray[j];
myArray[j]=temp;
}
public void write()
{
try{
PrintStream writer = new PrintStream(new File("myIgnoreNew.txt"));
for (int i=0; i<myArray.length; i++){
writer.println(myArray[i] + "\n");
}
writer.close();
}
catch(IOException e){
System.out.println(e);
}
}
}

Reading a CSV in Java / Jython

Here's a simple problem:
public static double[] stringsToDoubles(String[] inputArr) {
double[] nums = new double[inputArr.length];
for (int i = 0; i < nums.length; i++) {
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
Scanner sc = new Scanner(filename);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
from jython I import properly, and then call the function as
readPointCloudFile("points.txt", 3)
This gives the error
java.lang.NumberFormatException: java.lang.NumberFormatException: For input string: "points.txt"
You never read from the file. You pass the file name to the Scanner and assume that this string is your csv data, but it is just the filename.
Reading a file can be done as follows when you use Java 8:
import java.nio.file.Files;
import java.nio.file.Paths;
[...]
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
String filecontent = new String(Files.readAllBytes(Paths.get(filename)));
Scanner sc = new Scanner(filecontent);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
Here's my solution in the spirit of solving your own problems, but I'll give someone else credit because the other solutions are probably better.
public static double[] stringsToDoubles(String[] inputArr){
double[] nums = new double[inputArr.length];
for(int i = 0; i < nums.length; i++){
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) throws FileNotFoundException{
double[][] points = new double[n][];
String delimiter = ",";
try{
Scanner sc = new Scanner(new File(filename));
for(int i = 0; i < n; i++){
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
} catch (FileNotFoundException e){
System.err.println(e.getMessage());
} finally {
return points;
}
}

I am trying to print a 2D array to a file

I want to print 2D array to txt file on my desktop. It is important, that the output is formatted in way, that is in code, because it represents rows and seats.
Code:
package vaja15;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Vaja15
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Vnesi velikost dvorane (vrste/sedezi): ");
Scanner sc = new Scanner(System.in);
Random r = new Random();
int vrst = sc.nextInt();
int sedezev = sc.nextInt();
int [][] dvorana = new int [vrst][sedezev];
File file = new File ("C:/users/mr/desktop/dvorana.txt");
for(int i = 0; i<dvorana.length; i++)
{
System.out.println();
for (int j = 0; j<dvorana.length; j++)
{
dvorana [i][j] = r.nextInt(3);
System.out.print(dvorana[i][j]);
PrintWriter out = new PrintWriter(file);
out.println(dvorana[i][j]);
out.close();
}
}
}
}
You should not open and close a file in your loop: open a file before the loop, write your array, close the file. Otherwise it will overwrite the file over and over again.
Try this:
PrintWriter out = new PrintWriter(file);
for(int i = 0; i<vrst; i++)
{
System.out.println();
out.println();
for (int j = 0; j<sedezev; j++)
{
dvorana [i][j] = r.nextInt(3);
System.out.print(dvorana[i][j]);
out.print(dvorana[i][j]);
}
}
out.close();
Try the following idea:
try {
File file = new File(path);
FileWriter writer = new FileWriter(file);
BufferedWriter output = new BufferedWriter(writer);
for (int[] array : matrix) {
for (int item : array) {
output.write(item);
output.write(" ");
}
output.write("\n");
}
output.close();
} catch (IOException e) {
}

How do I find the number of lines of a file and input the number into the array size in Java?

this is a relatively simple question but I'm stuck for one hour for some reason. What silly mistake am I making??? Please help!
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Program2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int count = 0;
while (scanner.hasNext()) {
count ++;
scanner.nextLine();
}
int[] array = new int[count];
for (int i = 0; i < array.length; i++) {
array[i] = scanner.nextInt();
}
for (int i = array.length - 1; i >= 0; i--) {
System.out.println(array[i]);
}
}
}
Ohh... I had to scan the file twice -.- FML...
Answer posted:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Program2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int count = 0;
while (scanner.hasNext()) {
count ++;
scanner.nextLine();
}
Scanner scanner1 = new Scanner(new File("numbers.txt"));
int[] array = new int[count];
for (int i = 0; i < array.length; i++) {
array[i] = scanner1.nextInt();
}
for (int i = array.length - 1; i >= 0; i--) {
System.out.println(array[i]);
}
}
}
I'm not very familiar using Scanner, i'd rather prefer user BufferReader. Here es my code, let's see if it's useful to solve your problem.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class CoountingLines {
public static void main(final String[] args) throws FileNotFoundException {
final BufferedReader br = new BufferedReader(new FileReader(new File("/Volumes/nuquer/work/numbers.txt")));
String line;
Integer count = 0;
final HashMap<Integer, String> map = new HashMap<Integer, String>();
try {
while ((line = br.readLine()) != null) {
map.put(count, line.toString());
count++;
}
final int[] array = new int[count];
for (int i = 0; i < array.length; i++) {
array[i] = new Integer(map.get(i));
}
for (int i = array.length - 1; i >= 0; i--) {
System.out.println(array[i]);
}
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Converting CSV File to Java - Copied in Backwards

I previously asked a question about converting a CSV file to 2D array in java. I completely rewrote my code and it is almost reworking. The only problem I am having now is that it is printing backwards. In other words, the columns are printing where the rows should be and vice versa. Here is my code:
int [][] board = new int [25][25];
String line = null;
BufferedReader stream = null;
ArrayList <String> csvData = new ArrayList <String>();
stream = new BufferedReader(new FileReader(fileName));
while ((line = stream.readLine()) != null) {
String[] splitted = line.split(",");
ArrayList<String> dataLine = new ArrayList<String>(splitted.length);
for (String data : splitted)
dataLine.add(data);
csvData.addAll(dataLine);
}
int [] number = new int [csvData.size()];
for(int z = 0; z < csvData.size(); z++)
{
number[z] = Integer.parseInt(csvData.get(z));
}
for(int q = 0; q < number.length; q++)
{
System.out.println(number[q]);
}
for(int i = 0; i< number.length; i++)
{
System.out.println(number[i]);
}
for(int i=0; i<25;i++)
{
for(int j=0;j<25;j++)
{
board[i][j] = number[(j*25) + i];
}
}
Basically, the 2D array is supposed to have 25 rows and 25 columns. When reading the CSV file in, I saved it into a String ArrayList then I converted that into a single dimension int array. Any input would be appreciated. Thanks
so you want to read a CSV file in java , then you might wanna use OPEN CSV
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CsvFileReader {
public static void main(String[] args) {
try {
System.out.println("\n**** readLineByLineExample ****");
String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] col = null;
while ((col = csvReader.readNext()) != null)
{
System.out.println(col[0] );
//System.out.println(col[0]);
}
csvReader.close();
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae+" : error here");
}catch (FileNotFoundException e)
{
System.out.println("asd");
e.printStackTrace();
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
}
}
and you can get the related jar file from here

Categories

Resources