I'm trying to make a program that reads in an external .txt file and manipulates it. The file has 5 different groups of data, 4 lines each (2 are int, 2 string). I need to read in the file using the Scanner class, Make an object to hold each group of data (write a class which stores the data group as a single object (lets call it ProgramData)). Then I need to create a ProgamData object and put that into an ArrayList, and repeat for each of the 5 groups.
I have a text file, and I read it in with the Scanner (I confirmed that I did this right through printing on the command line). I'm completely lost from there. Any help at all would be greatly appreciated.
Not like this will help, but here's my code so far:
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Project1
{
public static void main (String[] args) throws IOException
{
File dataFile = new File("C:\\Users/data.txt");
Scanner fileReader = new Scanner(dataFile);
int firstLine = fileReader.nextInt();
int secondLine = fileReader.nextInt();
String whiteSpace = fileReader.nextLine();
String thirdLine = fileReader.nextLine();
String fourthLine = fileReader.nextLine();
ArrayList<String> newArray = new ArrayList<String>();
}
}
Make sure when you're reading the input file, use the Scanner class's hasNext() method. It detects if there is still a line in the file so you don't reach the end of the file. Use it like so
// get file input
// this will make sure there are still lines left within the
// file and that you have not reached the end of the file
while(fileReader.hasNext()) {
int firstLine = fileReader.nextInt();
int secondLine = fileReader.nextInt();
String whiteSpace = fileReader.nextLine();
String thirdLine = fileReader.nextLine();
String fourthLine = fileReader.nextLine();
}
You need to take the provided above to do the operations you are looking for.
Here are the steps you can follow:
Create a class named as ProgramData
Make a constructor which will accept your group data. -->
What is constructor
Now in Project1 Class read the file properly. --> Scanner Tutorial and Reading a txt file using scanner java
Once you get all the first group data from file pass it to ProgramData class and create instance something like
ProgramData pd1 = new ProgramData (/* list of parameter */)
Add that ProgramData instace to Arraylist like below
// Define Arraylilst
ArrayList<ProgramData > list= new ArrayList<ProgramData >();
// Do some operation like reading or collecting the data and creating object
// shown in step 4
list.add(pd1); // add new object of group to list.
I hope this will help you to achieve your goal. If you have any question just ask. Good luck
Related
I am having a problem with the Scanner class method hasNextLine() (or the hasNext() method). Basically, I am trying to read from a text file that has a list of integer values. I need to read through the text file and store the values that are there in an array (not an arrayList). The code below first goes through the text file to "see" how many values are there. I'm doing this because I can't think of another way to count the total number of integers that are in the text file, and I need to know how long my array has to be.
That being said, once I do that it seems that the hasNextLine() method (or the hasNext() method) "stays" at the bottom of the text file once I loop through:
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException
{
int y = 0; //stores numbers from the text file below
int counter = 0; //stores the number of datapoints in the text file to read from
File f = new File("Test Data.txt");// load an external file into a variable of type File.
Scanner reader = new Scanner(f);//instead of using System.in use f.
while (reader.hasNext()) // this will read the file's contents line-by-line
{
y = reader.nextInt();
counter++;/*stores the total number of integers in the Test Data.txt file so I can
know how long my array that stores the numbers from the txt file needs
to be.*/
}//ends loop
System.out.println("YOU HAVE " + counter + " DATA POINTS IN THE FILE");
int [] myNumbers = new int[counter]; //will store the integers from a data file
for (int i = 0; i < counter; i++){
if (reader.hasNext()){
System.out.println(i);
myNumbers[i] = reader.nextInt();
}//ends if statement
}//ends loop filling array
reader.close();
}
}
Is there a way to send the scanner "back to the top" of the text file WITHOUT creating a new scanner object? I know I could just create a new Scanner object, and then just loop and store each data point in an array, but it seems like there should be another way to do what I need to do. Is there? The documentation for the method in question doesn't mention much detail. I tried using the reset() method but that did not work.
I am not using an ArrayList because of a condition of the project I am working on. I understand that I could use an arrayList and not have to worry about counting the number of data values in the text file. However, the student I am helping has not learned about arrayLists yet as his class does not include them in the beginner course he's taking.
When reading the file for the second pass, just dispose the old scanner and get a new one. It is all in one line:
reader = new Scanner(f);
This will overwrite the reader with a reference to a new Scanner, one that reads from the beginning of the file. The old Scanner instance, which is no longer accessible will automatically be cleared by the garbage collector.
I have an InputStream file, I have to put all the words from that file into a vector of strings.
I tried multiple things to convert the InputStream file to where I can read all the words in it, but no matter what I always end up with a long string with all the words.
How can I separate all the words in the file to that I can put them in a vector of strings?
here is my code for the conversion from InputStream file to string:
public static InputStream vocabDoc = Librarian.class.getClassLoader().getResourceAsStream("Vocabulary.txt");
String str = new Scanner(vocabDoc,"UTF-8").useDelimiter("\\A").next();
System.out.println(str);
this is what the file "vocabDoc" contains (exactly):
file
vocabulary
test
is
one
this
for
if I try to put it in a vector it always come back as:
[file
vocabulary
test
is
one
this
for
]
and if I take out the "\n" it comes out as: [filevocabularytestisonethisfor], my goal is to have something like: [file, vocabulary, test, is, one, this, for] instead.
I'm not sure where to go from here and would really appreciate some help.
For the expected output, simply do it without using any explicit delimiter. Using Scanner#hasNext, you can test if the file more words to read.
Demo:
import java.io.InputStream;
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
InputStream vocabDoc = Main.class.getClassLoader().getResourceAsStream("Vocabulary.txt");
Scanner scanner = new Scanner(vocabDoc);
Vector<String> vector = new Vector<>();
while (scanner.hasNext()) {
vector.add(scanner.next());
}
scanner.close();
System.out.println(vector);
}
}
Output:
[file, vocabulary, test, is, one, this, for]
I've got a Hashset with my dictionary of words in it.
What I'm trying to do is to individually scan words from the file checkMe to see whether they exist in my HashSet.
When a word doesn't exist, I need to trigger a number of actions (which I won't get into).
For now, I'd like some advice as to how I take words from my scanned file and check them against my HashSet.
Something like:
if (dicSet does not contain a word in checkMe) {
da da da
}
Also, I want to be able to loop through checkMe to make sure each word is checked through dicSet until I reach an error.
My code so far:
import java.util.*;
import java.io.*;
public class spelling{
public static void main(String args[]) throws FileNotFoundException {
//read the dictionary file
Scanner dicIN = new Scanner(new File("dictionary.txt"));
//read the spell check file
Scanner spellCheckFile = new Scanner(new File("checkMe.txt"));
//create Hashset
Set <String> dicSet = new HashSet<String>();
//Scan from spell check file
Scanner checkMe = new Scanner(spellCheckFile);
//Loop through dictionary and store them into set. set all chars to lower case just in case because java is case sensitive
while(dicIN.hasNext())
{
String dicWord = dicIN.next();
dicSet.add(dicWord.toLowerCase());
}
//make comparisons for words in spell check file with dictionary
if(dicSet){
}
// System.out.println(dicSet);
}
}
while(checkMe.hasNext())
{
String checkWord = checkMe.next();
if (!dicSet.contains(checkWord.toLowerCase())) {
// found a word that is not in the dictionary
}
}
That's the basic idea at least. For real use, you'd have to add a ton of error-checking and exceptional states handling (what if your input contains numbers? What about ., - etc?)
I want to read words from a text file which looks like:
"A","ABILITY","ABLE","ABOUT","ABOVE","ABSENCE","ABSOLUTELY","ACADEMIC","ACCEPT","ACCESS","ACCIDENT","ACCOMPANY", ...
I read the words using split("\",\"") so I have them in a matrix. Unfortunately I cannot skip reading the first quotation mark, which starts my .txt file, so as a result in my console I have:
"A
ABILITY
ABLE
ABOUT
ABOVE
Do you know how can I skip the first quotation mark? I was trying both
Scanner in = new Scanner(file).useDelimiter("\"");
and parts[0].replace("\"", "");, but it doesn't work.
package list_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class exercise {
public static void main(String[] args) throws FileNotFoundException{
File file = new File("slowa.txt");
Scanner in = new Scanner(file).useDelimiter("\""); //delimiter doesn't work!
String sentence = in.nextLine();
String[] parts = sentence.split("\",\"");
parts[0].replace("\"", ""); //it doesn't work!
for (int i=0; i<10 ; i++){
System.out.println(parts[i]);
}
}
}
Strings are immutable which means that you can't change their state. Because of that replace doesn't change string on which it was invoked, but creates new one with replaced data which you need to store somewhere (probably in reference which stored original string). So instead of
parts[0].replace("\"", "");
you need to use
parts[0] = parts[0].replace("\"", "");
Anyway setting delimiter and using nextLine doesn't make much sense because this method is looking for line separators (like \n \r \r\n), not your delimiters. If you want to make scanner use delimiter use its next() method.
You can also use different delimiter which will represent " or ",". You can create one with following regex "(,")?.
So your code could look like
Scanner in = new Scanner(file).useDelimiter("\"(,\")?");
while(in.hasNext()){
System.out.println(in.next());
}
You can use this regular expression. It works for me:
Scanner in = new Scanner(file).useDelimiter("\"(,\")?");
while(in.hasNext()){
System.out.println(in.next());
}
Preface: This is for an assignment in one of my classes.
I need to parse through a CSV file and add each string to an ArrayList so I can interact with each string individually with pre-coded functions.
My problem is that the final string in each line (which doesn't end with a comma) is combined with the first string in the next line and recognized as being at the same index in the ArrayList. I need to learn how to either add a line break or do something else that will stop my loop at the end of each line and read the next line separately. Perhaps there is a built-in method in the scanner class that I'm unaware of that does this for me? Help is appreciated!
Here is the information in the CSV file:
Fname,Lname,CompanyName,Balance,InterestRate,AccountInception
Sally,Sellers,Seashells Down By The Seashore,100.36,3,7/16/2002
Michael,Jordan,Jordan Inc.,1000000000,3,6/12/1998
Ignatio,Freely,Penultimate Designs,2300.76,2.4,3/13/1991
Here is my code so far
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("smalltestdata-sallysellers.csv"));
// Chomp off at each new line, then add to array or arraylist
scanner.useDelimiter("\n");
ArrayList<String> data = new ArrayList<String>();
while (scanner.hasNext()) {
// Grab data between commas to add to ArrayList
scanner.useDelimiter(",");
// Add grabbed data to ArrayList
data.add(scanner.next());
}
System.out.println(data.get(10));
scanner.close();
}
}
And here is the output
7/16/2002
Michael
It seems like you just need to do...
String s[] = scanner.nextLine().split(",");
Collections.addAll(data, s);