Here's my code i need help on how to properly tokenize each token and put them on a array in each cycle of my loop and also how to get the sum of the array and how to get the farest distant value?
import java.io.*;
import java.util.*;
public class Data{
public static void main ( String[] args ) throws IOException{
String Filename = "Data.txt" ;
String line;
FileReader Filereader = new FileReader(Filename);
BufferedReader input = new BufferedReader(Filereader);
line = input.readLine();
System.out.println("--- oOo ---");
System.out.println("AVERAGE ACID LEVEL");
System.out.println("--------------------------------------------");
double[] nums = new double[13];
int sum = 0;
while ( line != null ) // continue until end of file
{
StringTokenizer token = new StringTokenizer(line);
for ( int i = 0; i < nums.length; i++ )
{
String temp = input.readLine();
nums[i] = Double.parseDouble(temp);
System.out.println(nums[i]);
}
}
input.close();
}
}
oh! heres the data on data.txt
5.6
6.2
6.0
5.5
5.7
6.1
7.4
5.5
5.5
6.3
6.4
4.0
6.9
any help would be greatly appreciated...
THANKS
Well since your data values are on a new line each time, you don't need StringTokenizer as you can just read the value from the line
You also dont need to have a nested for loop in your while loop, each line is read once by the while loop, so basically within your while loop do this
Read value
Add to array (use an ArrayList so can have a dynamic length)
Add to sum
Compare if it is farest
Try this,
while ((line = input.readLine()) != null)
instead of
line = input.readLine(); // it having the first value
because, You must read the file line by line.
while ( line != null ) // so only your loop is unbreakable
Dont copy and paste. Try to understand.
while ((line = input.readLine()) != null) // This will read the file line by line till last value.
{
values[i] = Double.valueOf(line);
i++; // This is for finding the total number of values from the file.
}
Double sampleInput = 0.0;
for(Double valueArray : values)
{
sampleInput = sampleInput + valueArray; // Atlast we sum all the array values.
}
Double output = (double) sampleInput/values.length;
Related
I have different text files I would like to read, and I am using BufferedReader for it like this:
int theMax = 0;
int theTypes = 0;
int []theSlices = {};
/*
INPUT1:
17 4
2 5 6 8
INPUT2:
100 10
4 14 15 18 29 32 36 82 95 95
*/
try {
FileReader reader = new FileReader("INPUT1.in");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println(numbers[0]);
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
;
My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.
Example for INPUT1:
theMax = 17
theTypes = 4
theSlices = 2 5 6 8
Very simple: you keep track yourself.
String line;
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println("Linenumber " + currentLine);
System.out.println(numbers[0]);
System.out.println(line);
currentLine ++;
}
reader.close();
Not sure I totally understand what you are after, but for just keeping track of the line numbers, create a variable that you increment in your while loop
i.e.
try {
FileReader reader = new FileReader("INPUT1.in");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
long currentLineNr = 0;
while ((line = bufferedReader.readLine()) != null) {
currentLineNr++;
String[] numbers = line.split(" ");
System.out.println(numbers[0]);
System.out.println(line);
//Use the currentLineNr how you like
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
First of all, as far as I know (and having read the official Java documentation for it here - https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html), the BufferedReader class does not in itself give you a mechanism (e.g. a getCurrentLine() method) to determine the current line.
However, there is absolutely nothing stopping you from keeping track of current line number yourself through, say, a counter variable.
Therefore, the relevant section of your code would look like:
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
currentLine++;
String[] numbers = line.split(" ");
/* NOTE: this can be numbers.length >= 2 if you don't care to enforce
having exactly 2 numbers as the first line
*/
if(currentLine == 1 && numbers.length == 2) {
theMax = Integer.valueOf(numbers[0]);
theTypes = Integer.valueOf(numbers[1]);
} else {
for(int index = 0; index < numbers.length; index++) {
theSlices[index] = Integer.valueOf(numbers[index]);
}
}
}
// do something with read values
I would also like to mention that your code could be improved here and there, for example:
You can replace your try with a try-with-resources, such that your readers are managed/closed automatically even if an exception occurs.
If you decide not to use try-with-resources, then you'll need to move your reader.close() method call in a finally block, because if an exception actually occurs you are never closing your resource.
These 2 lines
FileReader reader = ;
BufferedReader bufferedReader = new BufferedReader(reader);
can be simplified into:
BufferedReader bufferedReader = new BufferedReader(new FileReader("INPUT1.in"));
and then you only need to manage the bufferedReader instance if sticking to try instead of try-with-resources.
Hope this helps.
PS: not saying that my code snippet above is perfect, I'm sure it can be written more cleanly
Use java.io.LineNumberReader.
LineNumberReader is a subclass of BufferedReader that keeps track of line numbers. It provides a getLineNumber() method for getting the current line number.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/LineNumberReader.html
Example:
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class Example {
public static void main(String[] args) throws IOException {
try (FileReader fr = new FileReader("input.txt");
LineNumberReader r = new LineNumberReader(fr)) {
String next;
while ((next = r.readLine()) != null) {
System.out.println("line number " + r.getLineNumber() + " = " + next);
}
}
}
}
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.
I want to sequentially read each line of an input unsorted file into consecutive elements of the array until there are no more records in
the file or until the input size is reached, whichever occurs first. but i can't think of a way to check the next line if its the end of the file?
This is my code:
Scanner cin = new Scanner(System.in);
System.out.print("Max number of items: ");
int max = cin.nextInt();
String[] input = new String[max];
try {
BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"));
for(int i=0; i<max; i++){ //to do:check for empty record
input[i] = br.readLine();
}
}
catch (IOException e){
System.out.print(e.getMessage());
}
for(int i=0; i<input.length; i++){
System.out.println((i+1)+" "+input[i]);
}
the file has 205 lines, if I input 210 as max, the array prints with five null elements like so..
..204 Seychelles
205 Algeria
206 null
207 null
208 null
209 null
210 null
Thanks for your responses in advance!
From the docs:
public String readLine()
Returns: A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has
been reached
In other words, you should do
String aux = br.readLine();
if(aux == null)
break;
input.add(aux)
I recomend you use a variable-size array (you can pre-allocated with the requested size if reasonable). Such that you get either the expected size or the actual number of lines, and can check later.
(depending on how long your file is, you might want to look at readAllLines() too.)
Please refer this Number of lines in a file in Java and modify your for loop to take whatever is the least out of the entered max value or the no.of lines in the file.
Use List<String>
List<String> lines = new ArrayList<>(); // Growing array.
try (BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"))) {
for(;;) {
String line = br.readLine();
if (line == null) {
break;
}
lines.add(line);
}
} catch (IOException e) {
System.out.print(e.getMessage());
} // Closes automatically.
// If lines wanted as array:
String[] input = lines.toArray(new String[lines.size()]);
Using a dynamically growing ArrayList is the normal way to deal with such problem.
P.S.
FileReader will read in the current platform encoding, i.e. a local file, created locally.
You could do a null check in your first for-loop like:
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
System.out.print("Max number of items: ");
int max = cin.nextInt();
BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"));
List<String> input = new ArrayList<>();
String nextString;
int i;
for (i = 0; i < max && ((nextString = br.readline()) != null); i++) {
input.add(nextString);
}
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + " " + input.get(j));
}
}
Try :
for(int i=0; i<max; i++){ //to do:check for empty record
if(br.readLine()!=null)
input[i] = br.readLine();
else
break;
}
int i=0;
for(; i<max; i++){ //to do:check for empty record
String line=br.readLine();
if(line==null){
break;
}
input[i] = line;
}
//i will contain the count of lines read. indexes 0...(i-1) represent the data.
Hi im currently trying to do a hackerearth challenge sum of medians and it involves me reading from a text file and storing the values in an array. The first value has to be stored in a variable N which i am able to do but the the remaining values have to be stored in an array. This is where i become stuck. i have to read each value line by line and then store it in the array .
this is my code that i have been trying to get it working on but i just cant see where im going wrong.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass {
public static void main(String args[] ) throws Exception {
// read number of data from system standard input.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
int i = 1;
int[] myIntArray = new int[N];
// median sum
long SumMedians = 0;
int median = 0;
while (i<N)
//read one line file and parse as an integer
//store the value in an array
{
myIntArray [i] = Integer.parseInt(line);
i = i + 1; // increment i so i is the total numbers read
}
so as i said i must increment through the text file storing each value on the line in an array. Any help would be amazing thanks
The text file will look like this
5
10
5
1
2
15
one string per line, which i have to pass into an integer.
what i will be doing is after i store the value from the line into the array i will be sorting it and finding its medium and then repeat this process until all the values from the text file have been read.
The problem which i am trying to do is this one
http://www.hackerearth.com/problem/algorithm/sum-of-medians-1/
If you're reading from a text file (and not from standard input which is what you're doing at the moment) then you want something like:
// Warning: this could fail if the filename is invaild.
BufferedReader br = new BufferedReader(new FileReader("inputFileName.txt"));
To then read in each line, you can use the following in the while loop:
// Warning: this will crash the program if the line contains anything other than integers.
myIntArray[i] = Integer.parseInt(br.readLine())
i = i + 1; // increment i so i is the total numbers read
You should also close the reader at the end:
try{
br.close();
} catch (IOException e)
{
System.out.println("Error, program exit!");
System.exit(1);
}
The import should be swapped from import java.io.InputStreamReader
to: import java.io.FileReader
Since you are only reading 1 line therefore I suspect it to be a single line delimited by colon/semicolon or other character.. try looking into StringTokenizer and Scanner classes
N = the number from parsing a string to a number
In the first part of your program it N = 5
Why are you using while(i<5)?
If anything you should be
r = number of lines in text file;
while (i< r)
{
readline;
parseline;
store in array;
}
and then sort
Adapting the example they gave you
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass {
public static void main(String args[] ) throws Exception {
/*
* Read input from stdin and provide input before running
*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
//create storage array
int[] myIntArray = new int[N];
//read remainder of file
for (int i = 0; i < N; i++) {
String line = br.readLine();
myIntArray[i] = Integer.parseInt(line);
}
// close file
br.close();
//Perform median calculations
int median = 0;
...
System.out.println(median);
}
}
Input would look like
a b c d 4
e f g h 2
where each line would be read like a list and integer representing as an index in the list
I first try to read the file line be line and store it in the list. Heres what i have
public class FileReader {
public static void main(String[] args) {
String line = null;
List<String> list = new ArrayList<String>();
try {
FileInputStream fstream = new FileInputStream("test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// File file = new File("test.txt");
// Scanner scanner = new Scanner(file);
while ((line = br.readLine()) != null) {
list.add(line);
}
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now i want to remove the white spaces from the list and store the values in char array and then i was planning on traversing that array backwards till the nth element, depending on the input for n.
String[] elements = line.trim().split("\\s");
char[] chars = new char[elements.length - 1];
int i= Integer.parseInt(elements[elements.length - 1]);
for (i = 0; i < elements.length - 1; i++)
char[i] = elements[i].charAt(i);
Someone provided me this piece of code earlier and i tried it and it throws a nullpointerexception at String[] elements.
It's because you are running until line is null here
while((line = br.readLine()) != null)
{
list.add(line);
}
And then you are trying to call .trim() on it.
Do you mean to be processing the strings in list instead?
If so try looping over you list, you are already splitting it correctly and getting the last element. All you need to do is caluclate the offset, in this case it will be the length - 1 - the last element, in you String[] elements and you can print that out.
for (int i = 0; i < list.size(); i++)
{
String currentLine = list.get(i);
String[] elements = currentLine.trim().split("\\s");
int lastElement = Integer.parseInt(elements[elements.length - 1]);
String desiredValue = elements[elements.length - 1 - lastElement];
System.out.println("desiredValue = " + desiredValue);
}
You can avoid most of the work you're doing. I don't know if your input will require much flexibility (code to that if necessary) but in your example you only have 1 digit for the index.
Just avoid all the traversing and looping entirely:
String currentLine = file.nextLine();
//Find value from last space in the string, until the end of the string (will be the number)
int index = Integer.parseInt(currentLine.substring(
currentLine.lastIndexOf(' ') + 1, currentLine.length()));
//Remove all spaces from the current line
currentLine = currentLine.replaceAll("\\s+","");
//Remove the index at the end from the string, leaving only the characters
currentLine = currentLine.substring(0, currentLine.indexOf(index + ""));
char desiredValue = currentLine.charAt(currentLine.length() - index);
System.out.println("desiredValue = " + desiredValue);
This saves a lot of adding stuff to arrays if none of that is needed later, just do it all the first time through.