Reading data from file without manually inputing the length it the array - java

Please I will like to adjust this code that reads integers from a file.
I will like the code to detect the number (n) of the dataset instead of having to put in figures manually as done below (4000 )
double[] tall = new double[4000];
public class Extracto {
public static void main(String[] args) throws IOException {
File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
double[] tall = new double[4000];
String s = in.readLine();
int i = 0;
while (s != null) {
// Skip empty lines.
s = s.trim();
if (s.length() == 0) {
continue;
}
tall[i] = Double.parseDouble(s); // This is line 19.
// System.out.println(tall[i]);
s = in.readLine();
i++;
}
I am expecting the adjusted code to obtain the data length without manually putting it in like in as shown in the code below for the 4000 length.
double[] tall = new double[4000];

As Thomas mentioned, use a list, instead of an array.
File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
ArrayList<Double> tall = new ArrayList<>();
while(in.ready()){
String s = in.readLine().trim();
if(!s.isEmpty()){
tall.add(Double.parseDouble(s);
}
}
your codes can be further compacted if you use a list.
also do add a try-catch in the event when the String read is not a number.

Related

I need to take all the lines at once and work with them, but I get line-by-line reception

when there is a reading of lines and work with them continues line by line
I need to accept multi-line input first and only then to work the code
public class OrderRestaurant {
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader);
String line = null;
TreeMap<String, LinkedList<Integer>> orderMap = new TreeMap<String, LinkedList<Integer>>();
Set<Integer> tableSet = new TreeSet<Integer>();
while ((line = in.readLine()) != null) {
String[] orders = line.split(",");
for (int i = 0; i < orders.length; i++) {
tableSet.add(Integer.parseInt(orders[1]));
}
if (!(orderMap.containsKey(orders[2]))) {
LinkedList<Integer> numbersTables = new LinkedList<>();
numbersTables.add(Integer.parseInt(orders[1]));
orderMap.put(orders[2], numbersTables);
} else {
orderMap.get(orders[2]).addLast(Integer.parseInt(orders[1]));
}
StringBuilder sBuilder = new StringBuilder("Table");
Set<String>keysOrderMapSet=orderMap.keySet();
for (String keyString : keysOrderMapSet) {
sBuilder.append(',').append(keyString);
}
for(Integer key : tableSet){
sBuilder.append("\n").append(key);
for(Map.Entry<String, LinkedList<Integer>> entry : orderMap.entrySet())
{
LinkedList<Integer> numbersOrder = entry.getValue();
int counterOrder = 0;
for (int i = 0; i < numbersOrder.size(); i++) {
if(numbersOrder.get(i)==key) {
counterOrder++;
}
}
sBuilder.append(',').append(counterOrder);
}
}
System.out.println(sBuilder.toString());
}
}
}
all input is green, further you can see that the output after the program runs is formed in parts and only at the end is displayed in its entirety.
What I understand from the question is that you want to read all lines from the console first then need to do any operation or work and after that, you want to print the result for each line on the console. If that is the case then you need to create an intermediate array or list to hold the data of each line. Please refer below steps:
Create an empty list as readLineByLineString that holds your input line by line.
Read line from the console using Scanner or BufferedReader.
Add that line to the list by readLineByLineString.add(line);
Read all the lines and add to the list until all test cases satisfy or required conditions.
Now you have all your data line by line in an intermediate list i.e. readLineByLineString, just do the required operation.
Print your result after each operation.
End
You can read for example 1024 bytes at a time.
char[] myBuffer = new char[512];
int bytesRead = 0;
BufferedReader in = new BufferedReader(new FileReader(reader));
while ((bytesRead = in.read(myBuffer,0,1024)) != -1)
{ ... }

How can I read only one thing in from a textfile?

I can read in from the file and am able to change the amount of lines given by changing the number in the for loop but I don't want all the numbers in my file displayed side by side like that. I need them all going down one by one randomly.
public class Assignment2 {
public static void main(String[] args) throws IOException
{
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while( line != null ) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
Random r = new Random();
for (int p = 0; p<3; p++)
{
String randomString = lines.get(r.nextInt(2));
System.out.println(lines);
}
}
}
I think what you want to print is
String randomString = lines.get(r.nextInt(2));
System.out.println(randomString);
To display only the first 20 random lines from this list of maybe 100
for (int i = 0; i < 20; i++) {
int rowNum = r.nextInt(lines.size ());
System.out.println(lines.get(rowNum);
}

Take values from a text file and put them in a array

For now in my program i am using hard-coded values, but i want it so that the user can use any text file and get the same result.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class a1_12177903
{
public static void main(String [] args) throws IOException
{
if (args[0] == null)
{
System.out.println("File not found");
}
else
{
File file = new File(args[0]);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
while (br.ready())
{
line += br.readLine();
}
String[] work = line.split(",");
double[] doubleArr = new double[work.length];
for (int i =0; i < doubleArr.length; i++)
{
doubleArr[i] = Double.parseDouble(work[i]);
}
double maxStartIndex=0;
double maxEndIndex=0;
double maxSum = 0;
double total = 0;
double maxStartIndexUntilNow = 0;
for (int currentIndex = 0; currentIndex < doubleArr.length; currentIndex++)
{
double eachArrayItem = doubleArr[currentIndex];
total += eachArrayItem;
if(total > maxSum)
{
maxSum = total;
maxStartIndex = maxStartIndexUntilNow;
maxEndIndex = currentIndex;
}
if (total < 0)
{
maxStartIndexUntilNow = currentIndex;
total = 0;
}
}
System.out.println("Max sum : "+ maxSum);
System.out.println("Max start index : "+ maxStartIndex);
System.out.println("Max end index : " +maxEndIndex);
}
}
}
I've fixed it so it takes in the name of the text file from the command line. if anyone has any ways to improve this, I'll happily accept any improvments.
You can do this with Java8 Streams, assuming each entry has it's own line
double[] doubleArr = Files.lines(pathToFile)
.mapToDouble(Double::valueOf)
.toArray();
If you were using this on production systems (rather than as an exercise) it would be worth while to create the Stream inside a Try with Resources block. This will make sure your input file is closed properly.
try(Stream<String> lines = Files.lines(path)){
doubleArr = stream.mapToDouble(Double::valueOf)
.toArray();
}
If you have a comma separated list, you will need to split them first and use a flatMap.
double[] doubleArr = Files.lines(pathToFile)
.flatMap(line->Stream.of(line.split(","))
.mapToDouble(Double::valueOf)
.toArray();
public static void main(String[] args) throws IOException {
String fileName = "";
File inputFile = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(inputFile));
// if input is in single line
StringTokenizer str = new StringTokenizer(br.readLine());
double[] intArr = new double[str.countTokens()];
for (int i = 0; i < str.countTokens(); i++) {
intArr[i] = Double.parseDouble(str.nextToken());
}
// if multiple lines in input file for a single case
String line = "";
ArrayList<Double> arryList = new ArrayList<>();
while ((line = br.readLine()) != null) {
// delimiter of your choice
for (String x : line.split(" ")) {
arryList.add(Double.parseDouble(x));
}
}
// convert arraylist to array or maybe process arrayList
}
This link may help: How to use BufferedReader. Then you will get a String containing the array.
Next you have several ways to analyze the string into an array.
Use JSONArray to parse it. For further information, search google for JSON.
Use the function split() to parse string to array. See below.
Code for way 2:
String line="10,20,50";//in fact you get this from file input.
String[] raw=line.split(",");
String[] arr=new String[raw.length];
for(int i=0;i<raw.length;++i)arr[i]=raw[i];
//now arr is what you want
Use streams if you are on JDK8. And please take care of design principles/patterns as well. It seems like a strategy/template design pattern can be applied here. I know, nobody here would ask you to focus on design guidelines.And also please take care of naming conventions. "File" as class name is not a good name.

Average of stacked integers from a txt file using BufferedReader class and Integer.parseInt

I'm supposed to somehow get the average of the stacked integers in the text file. I'm new to this and even getting them to print was difficult for me. I have to use something like this number = Integer.parseInt(readLine); there somewhere but I just don't know how. If anyone could give some hint of what to do I would be most thankful.
The text file has just a dozen integers stacked as in one number on one line. Nothing else. Here's my code so far:
import java.io.*;
public class GradesInFile {
public static void main(String[] args) throws IOException {
String fileName = "grades.txt";
String readRow = null;
boolean rowsLeft = true;
BufferedReader reader = null;
FileReader file = null;
file = new FileReader(fileName);
reader = new BufferedReader(file);
System.out.println("Grades: ");
while (rowsLeft) {
readRow = reader.readLine();
if (readRow == null) {
rowsLeft = false;
} else {
System.out.println(readRow);
}
}
System.out.println("Average: ");
reader.close();
}
}
You are almost there just think how to keep track of the values you have so once you get out of the while loop you can return the average. (Hint Hint keep a list of the numbers)
So:
while (rowsLeft) {
readRow = reader.readLine();
if (readRow == null) {
rowsLeft = false;
} else {
//Convert the String into a Number (int or float depending your input)
//Saving it on a list.
System.out.println(readRow);
}
}
//Now iterate over the list adding all your numbers
//Divide by the size of your list
//Voila
System.out.println("Average: ");
reader.close();

Using Java to read and process textfile with custom column and row separators

I have a text file which contains content scraped from webpages. The text file is structured like this:
|NEWTAB|lkfalskdjlskjdflsj|NEWTAB|lkjsldkjslkdjf|NEWTAB|sdlfkjsldkjf|NEWLINE|lksjlkjsdl|NEWTAB|lkjlkjlkj|NEWTAB|sdkjlkjsld
|NEWLINE| indicates the start of a new line (i.e., a new row in the data)
|NEWTAB| indicates the start of a new field within a line (i.e. a new column in the data)
I need to split the text file into fields and lines and store in an array or some other data structure. Content between |NEWLINE| strings may contain actual new lines (i.e. \n), but these don't indicate an actual new row in the data.
I started by reading each character in one by one and looking at sets of 8 consecutive characters to see if they contained |NEWTAB|. My method proved to be unreliable and ugly. I am looking for the best practice on this. Would the best method be to read the whole text file in as a single string, and then use a string split on "|NEWLINE|" and then string splits on the resulting strings using "|NEWTAB|"?
Many thanks!
I think that the other answers will work too, but my solution is as follows:
FileReader inputStream = null;
StringBuilder builder = new StringBuilder();
try {
inputStream = new FileReader(args[0]);
int c;
char d;
while ((c = inputStream.read()) != -1) {
d = (char)c;
builder.append(d);
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
String myString = builder.toString();
String rows[] = myString.split("\\|NEWLINE\\|");
for (String row : rows) {
String cols[] = row.split("\\|NEWTAB\\|");
/* do something with cols - e.g., store */
}
You could do something like this:
Scanner scanner = new Scanner(new File("myFile.txt"));
List<List<String>> rows = new ArrayList<List<String>>();
List<String> column = new ArrayList<String>();
while (scanner.hasNext()) {
for (String elem : scanner.nextLine().split("\\|")) {
System.out.println(elem);
if (elem.equals("NEWTAB") || elem.equals(""))
continue;
else if (elem.equals("NEWLINE")) {
rows.add(column);
column = new ArrayList<String>();
} else
column.add(elem);
}
}
Took me a while to write it up, since I don't have IntelliJ or Eclipse on this computer and had to use Emacs.
EDIT: This is a bit more verbose than I like, but it works with |s that are part of the text:
Scanner scanner = new Scanner(new File("myFile.txt"));
List<List<String>> rows = new ArrayList<List<String>>();
List<String> lines = new ArrayList<String>();
String line = "";
while (scanner.hasNext()) {
line += scanner.nextLine();
int index = 0;
while ((index = line.indexOf("|NEWLINE|")) >= 0) {
lines.add(line.substring(0, index));
line = line.substring(index + 9);
}
}
if (!line.equals(""))
lines.add(line);
for (String l : lines) {
List<String> columns = new ArrayList<String>();
for (String column : l.split("\\|NEWTAB\\|"))
if (!column.equals(""))
columns.add(column);
rows.add(columns);
}

Categories