Im trying to read a file full of coordinates and then putting everything into double 2 dimensional array. When i run the code i get the exception error. Been trying to read the file for hours now(im a noobie in java)
Scanner input = new Scanner(new File(filename));
int row=0;
int col=0;
int rwn=0;
String[] line= new String[rwn];
while(input.hasNextLine()) {
line = input.nextLine().split(" ");//spliting 1
rwn++;
}
double[][] arrayOfEarth = new double[rwn][];//creating array for pairs
//itterating array ^ of splitting 1
for (int i=0;i<rwn;i++){
String[] ln =line[i].split(",");
double a= Double.parseDouble(ln[0]);
double b=Double.parseDouble(ln[1]);
double[] val={a,b};//adding the a and b doubles out of string to the value
arrayOfEarth[i]=val;//add arr to arr of arr
}
for (double[] c:arrayOfEarth){
System.out.println(String.format("%.0f and %.2f",c[0],c[1]));
}
}
catch (Exception e) {
System.out.println("Error bruh: "); e.printStackTrace();
}```
Your code confused me a bit.
But you can try this:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
// Define sample data
String coord = ""
+ "0 90 -4228\n"
+ "0.166666666667 90 -4228\n"
+ "0.333333333333 90 -4228\n"
+ "0.5 90 -4228\n"
+ "0.666666666667 90 -4228";
Scanner input = new Scanner(coord);
int rwn = 0;
// Define a 'arrayOfEarth' as list
ArrayList<Double[]> arrayOfEarth = new ArrayList<>();
while (input.hasNextLine()) {
++rwn;
String[] line = input.nextLine().split(" ");
if (line.length == 0) {
continue;
}
arrayOfEarth.add(parseLine(line, rwn));
}
arrayOfEarth.stream()
.forEach(v -> System.out.println(Arrays.toString(v) + "\n"));
}
private static Double[] parseLine(String[] line, int row) {
if (line.length != 3) {
throw new IllegalArgumentException("Missing valiues in line " + row);
}
Double[] doubles = new Double[3];
for (int i = 0; i < 3; i++) {
try {
doubles[i] = Double.parseDouble(line[i]);
} catch (NumberFormatException e) {
throw new NumberFormatException("NAN in " + row + "/" + i + ". value: " + line[i]);
}
}
return doubles;
}
}
This is not 'clean' code - only an example.
I have used the Stream-API. If you use a Java Version < 8 you have to rewrite it with a traditional for-loop.
Scanner input = new Scanner(new File(filename));
int row=0;
int col=0;
int rwn=0;
//String[] line= new String[rwn]; you created line with zero length;
while(input.hasNextLine()) {
line = input.nextLine().split(" ");//spliting 1
rwn++;
}
String[] line= new String[rwn];
double[][] arrayOfEarth = new double[rwn][];//creating array for pairs
//itterating array ^ of splitting 1
for (int i=0;i<rwn;i++){
String[] ln =line[i].split(",");
double a= Double.parseDouble(ln[0]);
double b=Double.parseDouble(ln[1]);
double[] val={a,b};//adding the a and b doubles out of string to the value
arrayOfEarth[i]=val;//add arr to arr of arr
}
for (double[] c:arrayOfEarth){
System.out.println(String.format("%.0f and %.2f",c[0],c[1]));
}
}
catch (Exception e) {
System.out.println("Error bruh: "); e.printStackTrace();
}```
String[] line= new String[rwn]; has to be under while statement. you created line with 0 length
Related
S.M.Tido,112,145,124
P.julio,178,145,133
Carey,92,100,123
Elain,87,92,92
Theodore,178,155,167
I have read above text file, and tried to find the average values of the 3 readings in every row. But I can only find the average of a single column,because my for loop logic did not work. Can anyone show me how to find the average of every row ?
import java.util.Scanner;
import java.io.*;
public class PatientDetails{
public static void main(String[] args){
String fileName = "patient.txt";
File file = new File(fileName);
try{
Scanner inputStream = new Scanner(file);
int sum = 0;
int noOfReadings = 3;
while(inputStream.hasNext()){
String data = inputStream.next();
String[] values = data.split(",");
int readings1 = Integer.parseInt(values[1]);
int readings2 = Integer.parseInt(values[2]);
int readings3 = Integer.parseInt(values[3]);
sum = readings1 + readings2 + readings3;
}
inputStream.close();
System.out.println("Average = "+sum/noOfReadings);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
Note:
Note : I have not learnt data structures in Java so I cannot use lists
In my code.
Just move you println() into the loop, and after that, change the sum back to 0.
Scanner inputStream = new Scanner(file);
int sum = 0;
int noOfReadings = 3;
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
int readings1 = Integer.parseInt(values[1]);
int readings2 = Integer.parseInt(values[2]);
int readings3 = Integer.parseInt(values[3]);
sum = readings1 + readings2 + readings3;
System.out.println("Average = " + sum / noOfReadings);
sum = 0;
}
inputStream.close();
hello I am having trouble with trying to read a file and take the two columns of the file and put them respectively in their own arrays. Any help would be appreciated! Thanks!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// TODO Auto-generated method stub
System.out.println("Please enter the name of the file to be read");
String fileName = keyboard.nextLine();
Scanner chirping = null;//user input for file name
boolean fileValue = false; //this makes the value false until the correct file name is inputed
while(!fileValue) {
try {
FileReader dates = new FileReader(fileName); // connects to the user inputted file
chirping = new Scanner(dates); //scans the file
fileValue = true; //turns file value to true which takes us out of the while loop
}//end try
catch(IOException e) {
System.out.println("File Not Found, Please Try Again: ");
fileName = keyboard.nextLine();
}//end catch
}// end while
double[] dataSet = new double[30];
double[] chirpFreq = new double[30];
double[] temp = new double[30];
//double[] temp = new double[chirping.nextInt()];
for(int i = 0; chirping.hasNextDouble(); i++) {
dataSet[i] = chirping.nextDouble();
}
for(int j = 0; j <= dataSet.length; j++) {
if(j%2 == 0) {
chirpFreq[j] = dataSet[j];
}
else {
temp[j] = dataSet[j];
}
}
for(int i = 0; i <= chirpFreq.length; i++) {
System.out.print(chirpFreq[i]+ " ");
}
chirping.close();
}
//These are the values i am trying to sort into two separate arrays
20 88.6
16 71.6
19.8 93.3
18.4 84.3
17.1 80.6
15.5 75.2
14.7 69.7
17.1 82
15.4 69.4
16.2 83.3
15 79.6
17.2 82.6
16 80.6
17 83.5
14.4 76.3
I don't usually use nextDouble() to read files so i don't know what your problem is exactly, but you can refactor your code to this:
double[] firstColumn = new double[30];
double[] secondColumn = new double[30];
String line = "";
int i = 0;
// keep reading until there is nothing to read
while( (line = chirping.nextLine()) != null ) {
// this is a regex that splits the line into an array based on whitespace
// just use " " if your data is separated by space or "\t" if tab
String[] columns = line.split("\\s+");
firstColumn[i] = Double.parseDouble(columns[0]);
secondColumn[i++] = Double.parseDouble(columns[1]);
}
chirping.close();
In my code, the method is able to read the .txt file and puts the integers in one side of the array, and the double in another. However, in the output there are duplicates, and i'm trying to put them in ascending order with no duplicates.
public static void readFile(String file) throws FileNotFoundException
{
Scanner s1 = new Scanner(new File(file));
String[][] container = new String[2][2];
int intIndex = 0;
int doubleIndex = 0;
while(s1.hasNextLine())
{
String line = s1.nextLine();
System.out.println(line);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
String[] splitLine = line.split(" ");
for (String text : splitLine) {
if (text.matches("\\d*"))
{
System.out.println(text + " is int");
if (container[0].length == intIndex)
{
container[0] = Arrays.copyOf(container[0], intIndex + 2); //add two more slot to int array
container[1] = Arrays.copyOf(container[1], intIndex + 2); //add two more slot to double array
}
container[0][intIndex] = (text); //add to container
intIndex++; //adjust the index
} else if (text.matches("\\d*.\\d*"))
{
System.out.println(text + " is double");
if (container[1].length == doubleIndex)
{
container[0] = Arrays.copyOf(container[0], doubleIndex + 2); //add two more slot to int array
container[1] = Arrays.copyOf(container[1], doubleIndex + 2); //add two more slot to double array
}
container[1][doubleIndex] = (text); //add to container
doubleIndex++; //adjust the index
} else
{
System.out.println(text + " is not int nor double");
}
}
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
Arrays.sort(container[0], Comparator.nullsLast(Comparator.naturalOrder())); //sort array of int
Arrays.sort(container[1], Comparator.nullsLast(Comparator.naturalOrder())); //sort array of double
System.out.println(Arrays.toString(container[0]));
System.out.println(Arrays.toString(container[1]));
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
The .txt file includes this all in one line, "10 5five 10 1.5 2 2.0 20"
I expect the output to be:
[2, 10, 20]
[1.5, 2.0]
However, the actual output i get is:
[10, 10, 2, 20]
[1.5, 2.0, null, null]
public static void readFile(String file) throws FileNotFoundException
{
Scanner s1 = new Scanner(new File(file));
String[][] container = new String[2][2];
int intIndex = 0;
int doubleIndex = 0;
while(s1.hasNextLine())
{
String line = s1.nextLine();
System.out.println(line);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
String[] splitLine = line.split(" ");
for (String text : splitLine) {
if (text.matches("\\d*"))
{
System.out.println(text + " is int");
//checking the array for duplicates
if (Arrays.stream(container[0]).anyMatch(text::equals)) {
continue;
}
if (container[0].length == intIndex)
{
container[0] = Arrays.copyOf(container[0], intIndex + 2);
container[1] = Arrays.copyOf(container[1], doubleIndex + 2);
}
container[0][intIndex] = (text);
intIndex++; //adjust the index
} else if (text.matches("\\d*.\\d*"))
{
System.out.println(text + " is double");
//checking the array for duplicates
if (Arrays.stream(container[1]).anyMatch(text::equals)) {
continue;
}
if (container[1].length == doubleIndex)
{
container[0] = Arrays.copyOf(container[0], intIndex + 2);
container[1] = Arrays.copyOf(container[1], doubleIndex + 2);
}
container[1][doubleIndex] = (text);
doubleIndex++;
} else
{
System.out.println(text + " is not int nor double");
}
}
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
//compare numerically rather than alphabetically in sorting
Arrays.sort(container[0], Comparator.nullsLast((e1, e2) ->
Integer.valueOf(e1).compareTo(Integer.valueOf(e2))));
Arrays.sort(container[1], Comparator.nullsLast((e1, e2) ->
Double.valueOf(e1).compareTo(Double.valueOf(e2))));
System.out.println(Arrays.toString(container[0]));
System.out.println(Arrays.toString(container[1]));
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
I have a method that works fine and gives desired result. Here is it's code:
public class arraycomparison {
public static void main(String args[]) {
try {
Scanner sc1 = new Scanner(new FileInputStream("/Users/esna786/File1.txt"));
Scanner sc2 = new Scanner(new FileInputStream("/Users/esna786/File2.txt"));
List<String> File1Content = new ArrayList<String>();
List<String> File2Content = new ArrayList<String>();
List<String> commonWords = new ArrayList<String>();
//Getting the contents of File1
while (sc1.hasNext()) {
File1Content.add(sc1.next());
}
String arr1[] = File1Content.toArray(new String[File1Content.size()]);
//Getting the contents of File1
while (sc2.hasNext()) {
File2Content.add(sc2.next());
}
String arr2[] = File2Content.toArray(new String[File2Content.size()]);
int count = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i].equals(arr2[j])) {
commonWords.add(arr1[i]);
count++;
}
}
}
String[] comWords = commonWords.toArray(new String[commonWords.size()]);
System.out.println("Total Number of Common Words are: "+comWords.length);
for (int i = 0; i < comWords.length; i++) {
System.out.println(i + 1 + ": " + comWords[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
it's out put is,
Total Number of Common Words are: 7
1: apple
2: ball
3: cat
4: duck
5: elephant
6: fan
7: goat
BUILD SUCCESSFUL (total time: 0 seconds)
Using the same files when I run the program code below almost same as above:
//Counting the number of matched words
public int getCommonWords(File File1, File File2) throws IOException {
try {
Scanner sc1 = new Scanner(new FileInputStream(File1));
Scanner sc2 = new Scanner(new FileInputStream(File1));
List<String> File1Content = new ArrayList<String>();
List<String> File2Content = new ArrayList<String>();
List<String> commonWords = new ArrayList<String>();
//Getting the contents of File1
while (sc1.hasNext()) {
File1Content.add(sc1.next());
}
String arr1[] = File1Content.toArray(new String[File1Content.size()]);
//Getting the contents of File1
while (sc2.hasNext()) {
File2Content.add(sc2.next());
}
String arr2[] = File2Content.toArray(new String[File2Content.size()]);
int count = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i].equals(arr2[j])) {
commonWords.add(arr1[i]);
count++;
}
}
}
String[] comWords = commonWords.toArray(new String[commonWords.size()]);
System.out.println("Total Number of Common Words are: " + comWords.length);
for (int i = 0; i < comWords.length; i++) {
System.out.println(i + 1 + ": " + comWords[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
it displays following in the output area:
run:
Total words of File1.txt are: 11
Total Number of Common Words are: 11
1: apple
2: ball
3: cat
4: duck
5: elephant
6: fan
7: goat
8: a
9: b
10: c
11: d
it is even displaying the unmatched words as well, why is it so?
Please help.
You are getting the null pointer exception for an obvious reason, the variable commonWord is not pointing to an array (you didn't allocate memory for storing the array strings).
String commonWords[]=null;
You have 2 solutions:
Use fixed memory allocation:
String commonWords[]= new String[Math.min(arr1.length, arr2.length)];
int commonCount = 0;
....
commonWords[commonCount++] = arr2[i]
Use dynamic memory allocation:
ArrayList<String> commonWords = new ArrayList<>();
...
commonWords.add(arr2[i]);
If you want to preserve your logic and data structures, then use something like:
String commonWords[] = new String [Math.min(arr1.length, arr2.length)];
It's far from perfect, but will allow you to assign values to your array.
Then to print:
for(String str : commonWords) {
if (str != null) {
System.out.println(str);
}
}
i have file txt in desktop :
1 5 23
2 5 25
3 30 36
i want sum column by column 1 + 2 + 3 =... and 5 + 5...n and 23,...n
Scanner sc = new Scanner (file("patch");
while (sc.hasNextLine)
{
//each sum by column
}
help me please thanks
I would use a try-with-resources to clean up my Scanner using the File. Also, you could construct a Scanner around the line of input to get your int columns (that doesn't need to be closed because String(s) aren't closable anyway). Something like,
try (Scanner sc = new Scanner(new File("patch"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
long sum = 0;
int count = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (count == 0) {
System.out.print(val);
} else {
System.out.printf(" + %d", val);
}
sum += val;
count++;
}
System.out.println(" = " + sum);
}
} catch (IOException e) {
e.printStackTrace();
}
As the Scanner(String) Constructor Javadoc documents
Constructs a new Scanner that produces values scanned from the specified string.
Edit To sum the columns is a little trickier, but you could read everything into a multidimensional List<List<Integer>> like
try (Scanner sc = new Scanner(new File("patch"))) {
List<List<Integer>> rows = new ArrayList<>();
int colCount = 0;
while (sc.hasNextLine()) {
List<Integer> al = new ArrayList<>();
String line = sc.nextLine();
Scanner row = new Scanner(line);
colCount = 0;
while (row.hasNextInt()) {
colCount++;
int val = row.nextInt();
al.add(val);
}
rows.add(al);
}
for (int i = 0; i < colCount; i++) {
long sum = 0;
for (List<Integer> row : rows) {
sum += row.get(i);
}
if (i != 0) {
System.out.print("\t");
}
System.out.print(sum);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Edit 2 For efficiencies sake, you might prefer to use a Map like
try (Scanner sc = new Scanner(new File("patch"))) {
Map<Integer, Integer> cols = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
int colCount = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (cols.containsKey(colCount)) {
val += cols.get(colCount);
}
cols.put(colCount, val);
colCount++;
}
}
for (int i : cols.values()) {
System.out.printf("%d\t", i);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Please find the code. Please go through the comments.
This is one way of doing for your reference. I want you to try other ways to improve your knowledge rather just using this code.
int sums[] = null;
while (sc.hasNextLine())
{
String row = sc.next();// get first row
String[] values = row.split(" ");// split by space
if(null == sums)
{
sums = new int[values.length];// create sum array with first row size
}
int index = 0;
for (String value : values)
{
sums[index] = sums[index]+Integer.parseInt(value);//adding current row value to current sum
index++;
}
}
if(null != sums)
{
int index=0;
for (int sum : sums)
{
System.out.println("Sum of column "+index+" : "+sum);// Printing each column sum
index++;
}
}
If your file is CSV formatted, then split line by comma(",") and find number of columns based on split array length.
Like below:
String line = sc.next();
String[] lineArr = line.split(",");
int len = lineArr.length;
create array of arraylists of size len and store each column field in the respective arraylist.
finally, at the end apply sum on each arraylist to calculate sum of each column values.