summing column by column in java - java

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.

Related

Read the data from the file and store it in two arrays

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();

reading file and adding into 2 dimensional double array

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

When I run my code I get (0, null) and cant figure out why

I am creating a program that is reading a file of names and ages then printing them out in ascending order. I am parsing through the file to figure out the number of name age pairs and then making my array that big.
The input file looks like this:
(23, Matt)(2000, jack)(50, Sal)(47, Mark)(23, Will)(83200, Andrew)(23, Lee)(47, Andy)(47, Sam)(150, Dayton)
When I am running my code I get the output of (0,null) and I am not sure why. I have been trying to fix it for a while and am lost. If anyone can help that would be great My code is below.
public class ponySort {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
int fileSize = 0;
int[] ages;
String [] names;
String filename = "";
Scanner inputFile = new Scanner(System.in);
File file;
do {
System.out.println("File to read from:");
filename = inputFile.nextLine();
file = new File(filename);
//inputFile = new Scanner(file);
}
while (!file.exists());
inputFile = new Scanner(file);
if (!inputFile.hasNextLine()) {
System.out.println("No one is going to the Friendship is magic Party in Equestria.");
}
while (inputFile.hasNextLine()) {
String data1 = inputFile.nextLine();
String[] parts1 = data1.split("(?<=\\))(?=\\()");
for (String part : parts1) {
String input1 = part.replaceAll("[()]", "");
Integer.parseInt(input1.split(", ")[0]);
fileSize++;
}
}
ages = new int[fileSize];
names = new String[fileSize];
while (inputFile.hasNextLine()) {
String data = inputFile.nextLine();
String[] parts = data.split("(?<=\\))(?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
ages[count] = Integer.parseInt(input.split(", ")[0]);
names[count] = input.split(", ")[1];
count++;
}
}
ponySort max = new ponySort();
max.bubbleSort(ages, names, count);
max.printArray(ages, names, count);
}
public void printArray(int ages[], String names[], int count) {
System.out.print("(" + ages[0] + "," + names[0] + ")");
// Checking for duplicates in ages. if it is the same ages as one that already was put in them it wont print.
for (int i = 1; i < count; i++) {
if (ages[i] != ages[i - 1]) {
System.out.print("(" + ages[i] + "," + names[i] + ")");
}
}
}
public void bubbleSort(int ages[], String names[], int count ){
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
// age is greater so swaps age
if (ages[j] > ages[j + 1]) {
// swap the ages
int temp = ages[j];
ages[j] = ages[j + 1];
ages[j + 1] = temp;
// must also swap the names
String tempName = names[j];
names[j] = names[j + 1];
names[j + 1] = tempName;
}
}
}
}
}
output example
File to read from:
file.txt
(0,null)
Process finished with exit code 0
What your code does is to Scan the file twice.
In the first loop you do
String data1 = inputFile.nextLine();
Code reads first line and then scanner goes to the next (second) line.
Later you do again inputFile.nextLine(); The second line is empty and the code never goes into the second loop and content is never read.
If you can use Lists, you should create two array lists and add ages and names into the arraylists in the first scan, so you scan the file once. When done, you could get the Array out of the arraylist.
If you should only use arrays and you want a simple update, just add another Scanner before the second loop:
ages = new int[fileSize];
names = new String[fileSize];
inputFile = new Scanner(file); // add this line

Method: Taking a text file and storing it in 2d array

I have a text file that I have to store into a 2d array, with 3 columns, and numRecords rows, but is implemented within a method. The parameter numRecords is the number of values to read from the input file. I'm getting an InputMismatchException and I can't figure out why. Any help would be greatly appreciated
public String[][] readFile(File file, int numRecords) throws IOException {
int numRows = numRecords;
int numColumns = 3; // column 1 will be age, column 2 will be height, column 3 will be weight
String[][] data = new String[numRows][numColumns];
try {
Scanner readFile = new Scanner(file);
String line = null;
line = readFile.nextLine().trim();
while (readFile.hasNextLine()) {
line = readFile.nextLine();
String[] str = line.split(",");
for (String element : str) {
element = element + " ";
for (int row = 0; row < data.length; row++) {
for (int column = 0; column < data[0].length; column++) {
data[row][column] = Integer.toString(readFile.nextInt());
data[row][column] = Integer.toString(readFile.nextInt());
data[row][column] = Integer.toString(readFile.nextInt());
}
}
}
}
readFile.close();
}
catch (InputMismatchException e1) {
e1.printStackTrace();
}
return data;
}
You are generating element(s) from your scanner by reading line(s). You are also attempting to then read int(s) from the scanner and ignoring the elements you have read. Another possible issue is your code doesn't test that the file can actually be read before starting. And I would prefer try-with-Resources over explicitly closing the Scanner (as here you leak a file handle whenever there is an exception). Also, why read int(s) and convert them to a String - I would prefer reading into an int[][]. Putting that all together,
public int[][] readFile(File file, int numRows) throws IOException {
if (!file.exists() || !file.canRead()) {
System.err.printf("Cannot find file: %s%n", file.getCanonicalPath());
return null;
}
int numColumns = 3;
int[][] data = new int[numRows][numColumns];
try (Scanner readFile = new Scanner(file)) {
while (readFile.hasNextLine()) {
String line = readFile.nextLine();
String[] tokens = line.split(",");
int row = 0, column = 0;
for (String element : tokens) {
if (column >= numColumns) {
column = 0;
row++;
}
data[row][column] = Integer.parseInt(element);
column++;
}
}
} catch (InputMismatchException e1) {
e1.printStackTrace();
}
return data;
}

How to determine how big is the treasure map (rows and columns) from a textfile?

I'd like to know how to figure out the rows and columns of a passed textfile.
Suppose the textfile looks like this:
X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................
This textfile has 10 rows and 20 columns and I'm facing troubles with how to get those rows and columns for my constructor (DONT WORRY ABOUT "X" symbols). I just would like to know how to get rows and columns from the textfile/ would like to know how to figure out how big the map is.
I need help with the second constructor in the code:
import java.util.Scanner; // Required to get input
import java.io.File; // Required to get input from files
// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it
public TreasureMap(){
int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();
treasureLocations = new Coord[numberOfTreasures];
for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}
// Read the string representation of a map from a file
public TreasureMap(String fileName) throws Exception{
Scanner data = new Scanner(new File(fileName));
int counter = 0;
while(data.hasNextLine())
{
counter++;
}
}
// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}
// Create a string representation of the treasure map
public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
}
Here's some code you can use to read lines from a file:
File file = new File(fileName);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
int rows = 0;
int cols = 0;
while ((line = br.readLine()) != null) {
// process the line
rows++;
cols = line.length(); // always the size of the last line in the file
}
}
br.close();
Based on your implementation, this would give you width and height of your input file.
public TreasureMap(String fileName) throws Exception{
Scanner data = new Scanner(new File(fileName));
int width = 0;
int height = 0;
while(data.hasNextLine())
{
String line = data.nextLine();
width = Math.max(width, line.length());
height++;
}
System.out.println(width + " x " + height);
}

Categories