For my assignment, I have to read from a file with 25 numbers, then sort it in order, then write it to another file. I can't think of a way to pass the array in my code (to the the string of an array) to write the file in order and for it to write the numbers to a different file.
This is probably a simple question but I am just having a little trouble trying to pass everything.
Thank you in advance.
public static void main(String[] args) throws IOException{
int[] number;
number = processFile ("Destination not specified");
swapIndex(number);
writeToFile ("Destination not specified");
}
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int i = 0;
int[] value = new int [25];
while ( (line = inputReader.readLine()) != null){
int num = Integer.parseInt (line); // Convert string to integer.
value[i] = num;
i++;
System.out.println (num); // Test
}
inputReader.close ();
return value;
// Read the 25 numbers and return it
}
public static void swapIndex (int[] num){ // BUBBLE sort
boolean order = true;
int temp;
while (order){
order = false;
for (int i = 0; i <num.length-1; i++){
if (num[i]> num[i+1]){
temp = num[i]; //set index to temp
num[i] = num [i+1]; // swap
num[i+1]= temp; //set index to the higher number before it
order = true;
}
}
}
} // Method swapIndex
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.write (String.valueOf ()); // Need to take the string value of the array
outputWriter.flush();
outputWriter.newLine ();
}
I would do it this way
Set<Integer> set = new TreeSet<Integer>();
Scanner sc = new Scanner(new File("1.txt"));
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
}
sc.close();
PrintWriter pw = new PrintWriter(new File("2.txt"));
for (int i : set) {
pw.println(i);
}
pw.close();
Instead of swapIndex(number) you used to sort the integer array, you could use Arrays.sort(number) and then pass this integer array(number) as one of the arguments to writeToFile method, iterate over those elements of integer array(number) and can add to the file.
Related
Marks for a class are stored in a text file called “marks3.txt”. The marks are saved in the following format: The first number represents the total number of (two-digit) marks stored sequentially in each line of text. Each line of text represents a set of marks.
For example (the txt file would contain the following numbers)
4567687509
569563
the marks are:
45%, 67%, 68%, 75%, 9%
56%, 95%, 63%
Write a method that will calculate the average of each set of marks as well as the overall average.
Below is the code I have created, I'm confused on how I would loop through the file until I have the two numbers that would make up the mark. Another thing I'm stuck on is how the method would be called.
import java.io.*;
public class ReadFile {
public static int calcAvg (String x) throws IOException {
int avg = 0;
int count = 0;
FileReader fr = new FileReader ("/home/sharma6a/marks.txt");
BufferedReader br = new BufferedReader (fr);
while ((x = br.readLine()) != null) {
if (count <= 2) {
}
}
br.close();
return avg;
}
considering an input file like
45676875
09569563
first I will have a method to read the file and transform it into a better structure to use.
public List<Integer> readFile() throws FileNotFoundException {
List<Integer> numbers = new ArrayList<>();
String line = "";
try {
FileReader fr = new FileReader("src/main/resources/numbers.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
for (int i = 0; i <= line.length() - 2; i+=2) {
char[] chars = line.toCharArray();
int number = Integer.parseInt(String.valueOf(chars[i]) + String.valueOf(chars[i+1]));
numbers.add(number);
}
}
} catch (Exception e) {
System.out.println(e);
}
return numbers;
}
then I will have the method to calculate the AVG
public float calcAvg(List<Integer> numbers) throws IOException {
int sum = 0;
for (int number: numbers){
sum+= number;
}
return sum/(numbers.size());
}
of course, you need a start method to make things happen
something like
public void init() throws IOException {
List<Integer> numbers = readFile();
float result = calcAvg(numbers);
System.out.println(result);
}
It's as easy as that. You practically want people to do stuff for you, but this is a question and answer site. Here you'll see some code for getting the individual percentages. You'll figure the rest out.
File f = new File(path);
try {
Scanner scanner = new Scanner(f);
String line = scanner.nextLine();
for (int i = 0; i < line.length() - 1; i+=2) {
double percentage = Double.parseDouble(line.substring(i, i+2)) / 100.0;
}
} catch (Exception e) {e.printStackTrace();}
Here is the CSV file I am using:
B00123,55
B00783,35
B00898,67
I need to read and store the first value entered in the file e.g. B00123 and store it into an array. A user can add to the file so it is not a fixed number of records.
So far, I have tried this code:
public class ArrayReader
{
static String xStrPath;
static double[][] myArray;
static void setUpMyCSVArray()
{
myArray = new double [4][5];
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "src\\marks.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] InArray = InputLine.split(",");
//copy the content of the inArray to the myArray
for (int x = 0; x < myArray.length; x++)
{
myArray[Rowc][x] = Double.parseDouble(InArray[x]);
}
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (int Rowc = 0; Rowc < 1; Rowc++)
{
for (int Colc = 0; Colc < 5; Colc++)
{
System.out.println(myArray[Rowc][Colc] + " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
This loops round the file but doesn't not populate the array with any data. The outcome is:
****** Setup Array ******
[[D#42a57993
0.0
0.0
0.0
0.0
0.0
There is actually a NumberFormatException happening when in the first row when trying to convert the ID to Double. So I revised the program and it works for me.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ArrayReader
{
static String xStrPath;
static Map<String,Double> myArray = new HashMap<>();
static void setUpMyCSVArray()
{
Scanner scanIn = null;
int Rowc = 0;
int Row = 0;
int Colc = 0;
int Col = 0;
String InputLine = "";
double xnum = 0;
String xfileLocation;
xfileLocation = "/Users/admin/Downloads/mark.txt";
System.out.println("\n****** Setup Array ******");
try
{
//setup a scanner
/*file reader uses xfileLocation data, BufferedRader uses
file reader data and Scanner uses BufferedReader data*/
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
while (scanIn.hasNext())
{
//read line form file
InputLine = scanIn.nextLine();
//split the Inputline into an array at the comas
String[] inArray = InputLine.split(",");
//copy the content of the inArray to the myArray
myArray.put(inArray[0], Double.valueOf(inArray[1]));
//Increment the row in the Array
Rowc++;
}
}
catch(Exception e)
{
System.out.println(e);
}
printMyArray();
}
static void printMyArray()
{
//print the array
for (String key : myArray.keySet()) {
System.out.println(key + " = " + myArray.get(key));
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
Output:
the code can't reader anything ,you file path incorrect.give it absoulte file path.
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
I use opencsv library to read from csv.
import com.opencsv.CSVReader;
public class CSV {
private static String file = <filepath>;
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
list.add(line[0]);
}
Object[] myArray = list.toArray();
System.out.println(myArray.length);
System.out.println(myArray[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output printed as below
3
B00123
I am trying to segregate my data into multiple array list, so that I can use them later-on in my code. But I am not able to put my data in array list.
My code is about segregating the data into three array list of different Subjects (Example:Physics,chemistry) as per various filters, which you will find in my code.
Input data file:
1|150|20150328|20150406|Physics|1600|1600|2|68|92
2|152|20150328|20150406|Physics|1600|1500|2|68|89
3|153|20150328|20150406|Physics|1600|1500|2|68|60
4|155|20150328|20150406|Physics|1600|1600|2|68|72
5|161|20150328|20150406|Chemistry|1600|1600|2|68|77
Here's my code:
Public Class filter{
public static void main(String args[])
BufferedReader in= null;
BufferedWriter out= null;
String in_line;
String PrevRollNo= "";
int PrevDate= 0;
ArrayList<transaction> PhysicsList= new ArrayList<transaction>();
ArrayList<transaction> scList= new ArrayList<transaction>();
ArrayList<transaction> Chemistry= new ArrayList<transaction>();
try{
in = new BufferedReader(new FileReader(Path for input file));
File out_file= new File(Path for output file);
if(!out_file.exists())
{
(!out_file.createNewFile();
}
FileWriter fw=new FileWriter(out_file);
out= new BufferedWriter(fw);
while ((in_line=in.readline())!=null)
{
Transaction transact=new Transaction(in_line);
if(transact.RollNo.equals(PrevRollNo))
{
if(transact.subject.equals("Physics")&& transact.Prs_Date= PrevDate
{
PhysicsList.add(transact);
}
else if(transact.subject.equals("Physics")&&transact.wk_date != PrevDate}
Iterator<Transaction> it;
if(!transact.RoomNo.equals("102")&&!transact.lcl_RoomNo.equals("102");
{
it= scList.iterator();
while(it.hasnext())
{
Transaction sc= it.next();
if(sc.lcl_RoomNo.equals(transact.RoomNo) && sc.l1 equals(tansact.l1) && sc.l2 equals(transact.l2)
if(sc.marks==transact.marks)
{
transact.srsfound= true;
}
else
{
System.out.print.ln( "not found");
}
scList.remove(sc))
out.write(in_line);
break;
}}}}
Static Class Transaction
{
Public String RollNo, Subject, RoomNo, lcl_RoomNo, l1, l2;
Public int wk_date, prs_date;
Public double marks , amt;
Public boolean srcfound, tgtfound;
Public Transaction(String in_line)
{
String [] SplitData= in_line.split("\\|");
RollNo = SplitData[1];
Subject = SplitData[4]
RoomNo = SplitData[5];
lcl_RoomNo = SplitData[6];
l1 = SplitData[7];
l2 = SplitData[8];
wk_date = SplitData[3];
prs_date = SplitData[2];
marks = Double.parsedouble(SplitData[9]);
amt = Double.parsedouble(SplitData[]);
srcfound = false;
tgtfound = false;
}
Kindly help with your expertise.
Use Java 8 NIO and Streams. It will ease the job.
Files.lines(Paths.get("fileName.txt")).map(line -> {
String[] tokens = line.split("|");
//tokens contains individual elements of each line. Add your grouping logic on tokens array
}
I agree with the other answer in some ways. NIO should be used, it makes it a lot easier. However, I would avoid streams and instead use the readAllLines method like so:
try{
List<String> filecontents = new String(Files.readAllLines(file.toPath()); //file is the object to read from.
for(int i = 0; i < filecontents.size(); i++){
String line = lines.get(i);
//New code starts here
if(!line.contains("|") continue; //Ignore that line
//New code ends here
String[] array = line.split("|");
ArrayList<String> list = new ArrayList<String>();
for(int a = 0; a < array.length; a++){
String part = array[a];
list.add(part);
}
Transaction t = new Transaction(line);
if(line.contains("Physics") PlysicsList.add(t);
else if(line.contains("Chemistry") Chemistry.add(t);
else{ //Do nothing}
}
}catch(IOException e){
e.printStackTrace();
}
EDIT: I added a check in there. The reason the first and last lines may not be working is if the lines that are being parsed are not being parsed properly. See if this fixes your issue
I have a text file of names( last and first). I have successfully been able to use RandomAccessFile class to load all the names into an Array of strings. What is left for me to do, is to assign each of the first names to an Array of first names and each of the last names in the list to an array of Last Names. Here is what I did but Im not getting any desired result.
public static void main(String[] args) {
String fname = "src\\workshop7\\customers.txt";
String s;
String[] Name;
String[] lastName, firstName;
String last, first;
RandomAccessFile f;
try {
f = new RandomAccessFile(fname, "r");
while ((s = f.readLine()) != null) {
Name = s.split("\\s");
System.out.println(Arrays.toString(Name));
for (int i = 0; i < Name.length; i++) {
first = Name[0];
last = Name[1];
System.out.println("last Name: " + last + "First Name: "+ first);
}
}
f.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Please help me out I seem to be confused on what kind of collection to use and how to go about it Thanks
You could create a method to read a file and put the data in an Array, but, if you are determined to use an Array you are going to have to create it at a fixed size b/c arrays are immutable in java
public class tmp {
public static void main(String[] args) throws FileNotFoundException {
//problem you have to create an array of fixed size
String[] array = new String[4];
readLines(array);
}
public static String[] readLines(String[] lines) throws FileNotFoundException {
//this counter can be printed to check the size of your array
int count = 0; // number of array elements with data
// Create a File class object linked to the name of the file to read
java.io.File myFile = new java.io.File("path/to/file.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(myFile);
/* This while loop reads lines of text into an array. it uses a Scanner class
* boolean function hasNextLine() to see if there another line in the file.
*/
while (infile.hasNextLine()) {
// read a line and put it in an array element
lines[count] = infile.nextLine();
count++; // increment the number of array elements with data
} // end while
infile.close();
return lines;
}
}
However, the preferred method is to use an ArrayList which is an object that uses dynamically resizing arrays as data is added. In other words, you don't need to worry about having different size text files.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("path/of/file.txt"));
String str;
ArrayList<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
A little about random access.
Classes like BufferedReader and FileInputStream use a sequential process of reading or writing data. RandomAccess, on the other hand, does exactly as the name implies, which is to permit non-sequential, random access to the contents of a file. However, Random access is typically used for other applications like reading and writing to zip files. Unless you have speed concerns I would recommend using the other classes.
public static void main(String[] args) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader("src\\workshop7\\customers.txt"));
String str;
String names[];
List<String> firstName = new ArrayList();
List<String> lastName = new ArrayList();
try {
while ((str = in.readLine()) != null) {
names = str.split("\\s");
int count = 0;
do{
firstName.add(names[count]);
lastName.add(names[count+1]);
count = count + 2;
}while(count < names.length);
}
} catch (IOException e) {
e.printStackTrace();
}
// do whatever with firstName list here
System.out.println(firstName);
// do whatever with LastName list here
System.out.println(lastName);
}
I am trying to figure out how to make a program that reads data from a text file, and fills a Jtable with it, I will need to be able to search the table, and do some calculations with the numbers.
A row in the text file would contain:
name, country, gender, age, weight
The number of rows is unknown (I need to count the number of rows).
This is what I tried, but it seems to crash. I need to count the # of rows, and then fill the array with the content from the rows.
package Jone;
import java.io.*;
import java.util.*;
public class Jone {
public static void main (String [] args)throws IOException{
int rows = 0;
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine()){rows++;}
Object[][] data = new Object[rows][5];
System.out.print(rows);
file.nextLine();
for(int i = 0;i<rows;i++)
{
String str = file.nextLine();
String[] tokens= str.split(",");
for (int j = 0;j<5;j++)
{
data[i][j] = tokens[j];
System.out.print(data[i][j]);
System.out.print(" ");
}
}
file.close();
}
}
change your code as follows
package Jone;
import java.io.*;
import java.util.*;
public class Jone {
public static void main (String [] args)throws IOException{
try{
int rows = 0;
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine())
{
rows++;
file.nextLine();
}
file = new Scanner (new File("data.txt"));
System.out.println(rows);
Object[][] data = new Object[rows][5];
for(int i = 0;i<rows;i++)
{
String str = file.nextLine();
String[] tokens= str.split(",");
for (int j = 0;j<5;j++)
{
data[i][j] = tokens[j];
System.out.print(data[i][j]);
System.out.print(" ");
}
}
file.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
You create an array with 0 rows and then you try to access the empty array dimension.
Also I suppose you should reset the pointer of the scanner after counting the rows.
ArrayList should be more useful for your goal.
class Person {
String name, country, gender;
int age;
double weight;
public Person(String n, String c, String g, int a, double w) {
name = n;
country = c;
gender = g;
age = a;
weight = w;
}
}
Would properly model your data better when you are extracting from the file (I took a guess at Person but call it what you will). We then use ArrayList like so:
public static void main (String[] args) throws IOException {
ArrayList<Person> people = new ArrayList<Person>();
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine()) {
String str = file.nextLine();
String[] tokens= str.split(",");
people.add(new Person(tokens[0], tokens[1], tokens[2],
Integer.parseInt(tokens[3], Double.parseDouble(tokens[4]))));
}
file.close();
Person[] arrayPeople = people.toArray();
}
ArrayLists are far more powerful than arrays as you can perform all sorts of operations on them like sorts and searches and of course you don't have to worry about their initial size because they just grow as you add new elements.
Maroun is right, you really need to use some Collections to help you with that :
public static void main(String[] args) throws Exception {
List<String[]> lines = readFiles(new File("data.txt"));
String[][] data = lines.toArray(new String[0][]);
}
public static List<String[]> readFiles(File file) {
List<String[]> data = new LinkedList<>();
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] tokens = line.split(",");
data.add(tokens);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
return data;
}
Note that you can use some third party libraries like Commons IO to read the file's lines :
List<String> lines = org.apache.commons.io.FileUtils.readLines(new File("data.txt"));)
Less code = less bugs!
Hope it helps
Move this line
Object[][] data = new Object[rows][5];
below
System.out.print(rows);
But as per answers above, we suggest change the code to use array lists if possible.