Picking out specific information out a text file with Scanner - java

I am having trouble finding an efficient way to pick out specific data from a text file in this format, with numerous lines.
<"Name" "double" "double" "double" [...]>
The amount of doubles varies on every line of the txt file,
I am only interested to pick out the first double of every line in the txt file.
The way I am trying to do it is with:
Scanner doubleScan = new Scanner(System.in).useDelimiter("(\\w)(\\s+)");
String[] columnOne = elementScan.next().split(" ");
Trying to make the scanner expect with regex but does not really work if unknown amount of doubles in a line. Then trying to store all the picked out (1st of every line) doubles in an array
Would appreciate any suggestions, with Scanner only.

You can use scanner.nextLine() to read line by line and then use plit method and take second element from the array. Alternatively if you are so partcular about using only scanners you can create another scanner for each line and check for double using nextDouble() method. Example.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
try {
File file = new File("test.txt");
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNext()) {
Scanner lineScanner = new Scanner(fileScanner.nextLine());
while (lineScanner.hasNext()) {
if (lineScanner.hasNextDouble()) {
System.out.println("First Double :" + lineScanner.nextDouble());
break;
} else {
lineScanner.next();
}
}
lineScanner.close();
}
fileScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Related

Formatting for each line of the file that's being read into the console

I'm trying to show covid data in each line that will be separated into tabs (like a table) and the numeric values will be divided by the thousands separator.
I'm also trying to use a printf statement so i can specify each line to be formatted in that way but im not sure how to do that.
The result I'm looking for:
Global 213,752,662 4,519,052 655,952
What I'm getting:
Global 213752662 4519052 655952
My Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class COVIDdata {
public static void main(String[] args) throws FileNotFoundException {
//printing header//
System.out.println("Name\t\t\tTotal Cases\tNew Cases\tNew Cases");
System.out.println("\t\t\t\t\t7 Days \t\t24 Hours");
System.out.println("--------------------------------------------------------------------------------------");
//opening the file//
try {
File file = new File("C:\\Desktop\\COVID-19GlobalData.txt");
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
while(scan.hasNext()) {
System.out.printf("%,d\n" , int);
}
scan.close();
} catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
}
}
}
This loop will exhaust the entire file scanner and print the file as-is with no formatting
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
You need to parse the lines then include the tabs in your output between several numbers. Something like
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] parts = line.split("\\s+");
System.out.printf("Global\t%,d\t%,d\n", Long.parseLong(parts[1]), Long.parseLong(parts[2]));
}

Need to get a line from a file onto queue and not the whole file text

I'm having trouble properly getting one line of text at a time from a file onto a queue without taking the whole file into the queue. For example, I'd like only Write a program that reads a Java source file as an argument and produces an index of all identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity, we will consider each string consisting only of letters, numbers, and underscores an identifier.
Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+") Then each call to next returns an identifier.
public class Main { to get added to the queue but instead the whole file text is put into the queue instead of a line at a time. Sorry if my question is unclear
// Write a program that reads a Java source file as an argument and produces an index of all
// identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity,
// we will consider each string consisting only of letters, numbers, and underscores an identifier.
// Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+").
// Then each call to next returns an identifier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class E_15 {
public static void main(String[] args) throws FileNotFoundException
{
// get scanner input from file
Scanner fileInput = new Scanner(new File ("C:/Users/ramir/IdeaProjects/PA_7/src/Main.java"));
Queue<String> test = new LinkedList<String>();
ArrayList<String> phrase = new ArrayList<String>();
/*
List<String> result = new ArrayList<String>();
Scanner s = new Scanner(is);
s.useDelimiter(delimiter);
*/
// Iterates till end of file
while (fileInput.hasNextLine())
{
// Here is the issue. Data will end up
// containing the whole file instead of only that line
String data = fileInput.nextLine();
Scanner in = new Scanner(data);
in.useDelimiter("[^A-Za-z0-9_]+");
// I believe around here or before is the issue that I'm having.
// It adds all the file instead of only that line
// Also trying to figure out how to display each line that it's displayed on
// What the first one should look like for example
// 0: public occurs in:
// public class Main {
// public static void main(String[] args) {
//System.out.println(data);
test.add(data);
while(in.hasNext())
{
// Getting each phrase/word into ArrayList
String token = in.next();
phrase.add(token);
}
in.close();
}
int index = 0;
// This part works fine
for(String num : phrase)
{
// printing the key
System.out.println(index + ": " + num + " occurs in:");
// printing the values
// This to print out what
for(String line : test)
{
System.out.println(line);
}
System.out.println();
++index;
}
}
}
// Just java class get file front
// This is fine
public class Main {
public static void main(String[] args) {
int a_1 = 100;
System.out.println(a_1);``
}
}
I'd like it to only show System.out.println(a_1) because the line that's it's on See This
. I'm also have trouble printing it in all the lines that occur.
import java.io.*;
import java.util.Scanner;
public class ReadLineByLineExample2
{
public static void main(String args[])
{
try
{
//the file to be opened for reading
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
while(sc.hasNextLine())
{
System.out.println(sc.nextLine()); //returns the line that was skipped
}
sc.close(); //closes the scanner
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Try studying the above code. I hope it will help. Otherwise, you might need to open this link for more detail.

Java scanner not starting from beginning of file

First of all this is not a duplicate of other posts, because in my problem the scanner class does not recognize the beginning of the .txt file not the end, instead it starts approximately 1/2 way through the file.
Here is my code:
package Program;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws FileNotFoundException {
String filename = "C:\\Users\\vroy\\Programming\\Text documents\\P&P.txt";
File textFile = new File(filename);
Scanner reader = new Scanner(textFile);
// int value = reader.nextInt();
// System.out.println(value);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
}
}
Here is the .txt document that my program is reading:
http://www.goodreads.com/ebooks/download/1885.Pride_and_Prejudice?doc=2
My program starts printing out lines of text starting at: "with the ill-judged officiousness..."
It should start much further up the document.
Is this a problem with the scanner class?
Is this a problem with the scanner class?
Nope.
I just tested your code. The answer is pretty funny actually - I assume you are running this code in an IDE such as Eclipse. System.out.println() prints to the "Console". The console has a maximum number of lines it shows, and as your file is very long, it doesn't show the start.
It IS looping through all the lines. To prove this, make it increment a digit whenever it prints a line such as:
int counter = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
counter++;
}
You will see that counter is exactly the number of lines in the document.

Creating a constructor to read a txt file

I am creating a program that will produces the statistics of a baseball team
i am trying to create a constructor to read the file into the teamName instance variable and the battingAverages array.
the txt file contains the one word name of the team followed by 20 batting averages.
"Tars 0.592 0.427 0.194 0.445 0.127 0.483 0.352 0.190 0.335 0.207 0.116 0.387 0.243 0.225 0.401 0.382 0.556 0.319 0.475 0.279 "
I am struggling to find how to go about this and get it started?
I ran this and this might be close to what you want. Instead of making a confusing constructor, make a private method that the constructor will call to read in the file into the array.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Baseball {
private File textFile;
private Scanner input;
private String teamName;
//this will only work if you know there will be 20 entries everytime
//otherwise I recommend loading the data into an ArrayList
private double []battingAvgs = new double[20];
public Baseball(String file){
textFile = new File(file);
readInFile(textFile);
}
//private method that reads in the file into an array
private void readInFile(File textFile){
try {
input = new Scanner(textFile);
//read first string into variable teamName
teamName = input.next();
int i=0;
//iterate through rest of file adding it to an ArrayList
while(input.hasNext()){
battingAvgs[i] = input.nextDouble();
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//print out array
public void printArray(){
for(Double a: battingAvgs){
System.out.println(a);
}
}
}
Well, if these are all on one line in a specific file then what you could do is construct a bufferedreader to read the first line of your file, split the line based on spaces, and then parse the teamName and batting averages out.
BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
String[] line = br.readLine().split(" ");
br.close();
teamName = line[0];
battingAverages = new int[20];
for(int i = 0; i < 20; i++)
battingAverages[i] = Integer.parseInt(line[i+1]);
These might throw IOExceptions, which you will need to catch. I think Java 7 has a method to automatically handle these kinds of errors (not sure about this), but as I am new to Java 7's added functionality, I would just manually check for those exceptions.
You need to use the BufferedReader, FileInputStream, and InputStreamReader. Your file.txt should have the batting averages on every line, as shown below.
0.592
0.427
0.194
Here is an example of a class that when created, it will read a text file line by line and add each line to the array list:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Class {
ArrayList<Double> averages;
public Class() {
averages = new ArrayList<Double>();
try {
FileInputStream in = new FileInputStream("inputFile.txt"); //your file path/name
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine())!= null) averages.add(Double.parseDouble(strLine));
}catch(Exception e){
System.out.println(e);
}
}
}
Hope this helps
Try using the Scanner class.
File file=new File("TestFile.txt"); //Create a new file
Scanner scan=new Scanner(file);//Create a Scanner object (Throws FileNotFoundException)
if(scan.hasNext()) //Check to make sure that there is actually something in the file.
{
String line=scan.nextLine(); //Read the line of data
String[] array=line.split(" "); //Split line into the different parts
teamName=array[0]; //The team name is located in the first index of the array
battingAverages=new double[array.length-1];//Create a new array to hold the batting average values
for(int i=0;i<battingAverages.length;i++) //Loop through all of the averages
{
double average=Double.parseDouble(array[i+1]);//Convert the string object into a double
battingAverages[i]=average; //Add the converted average to the array
}
System.out.print(teamName+" "+Arrays.toString(battingAverages)); //[Optional] Print out the resulting values
}

Java Read from file to Array runtime error

import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();

Categories

Resources