Appending items from a txt file to an array - java

Hey I just started learning how to code. I am using netbeans and I want to transfer some data from a txt.file into an array in java. This might be a really simple fix but i just cant see whats wrong
This is the data in the txt.file:
58_hello_sad_happy
685_dhejdho_sahdfihsf_hasfi
544654_fhokdf_dasfjisod_fhdihds
This is the code I am using however smthg is wrong with the last line of code:
int points = 0;
String name = "";
String a = "";
String b = "";
public void ReadFiles() throws FileNotFoundException{
try (Scanner input = new Scanner(new File("questions.txt"))) {
String data;
while(input.hasNextLine()){
data = input.nextLine();
String[] Questions = data.split("_");
points = Integer.parseInt(Questions[0]);
name= Questions[1];
a = Questions[2];
b = Questions[3];
}
System.out.println(Arrays.toString(Questions));
}
}
This is the error I am getting:
error: cannot find symbol
System.out.println(Arrays.toString(Questions));
Thx soooo much guys.

You can also use the below code if you just want to print the data:
Files.readAllLines(Paths.get("questions.txt")).forEach(line -> {
System.out.println(Arrays.toString(line.split("_")));
});
Output is :
[58, hello, sad, happy]
[685, dhejdho, sahdfihsf, hasfi]
[544654, fhokdf, dasfjisod, fhdihds]
The correct version of your code should be like the below (you must access the variable Question in the declared scope by moving println into end of while loop) :
// definitions...
public void ReadFiles() throws FileNotFoundException{
try (Scanner input = new Scanner(new File("questions.txt"))) {
String data;
while(input.hasNextLine()){
data = input.nextLine();
String[] Questions = data.split("_");
points = Integer.parseInt(Questions[0]);
name= Questions[1];
a = Questions[2];
b = Questions[3];
System.out.println(Arrays.toString(Questions));
}
}
}

Related

Breaking down textfile into Arraylist - Java

I am trying to break down a data text file which is in the format of:
kick, me, 10
kick, you, 20
into arrayList<customlist> = new arrayList
class customlist
{
string something, string something2, int times
}
So my question is how can I get each part of the text file data to each part of the customlist.
eg: kick -> something, me -> something2 and 10 -> times
Try to split each line into its components using String.split(",").
Apply String.trim() to each member in order to get rid of the spaces.
There are many way to solve this type of problem, here you can simply read all text from that text file by using InputStream and BufferReader after geting all text you can do somthing like:-
ArrayList<CustomList> getArrayList(String textFileData)
{
ArrayList<CustomList> customLists = new ArrayList<>() ;
String data[] = textFileData.split(",");
int i = data.length;
int position = 0;
while (position<i)
{
String somthing = data[position];
String somthing1 = data[position+1];
String temp = data[position+2].split(" ")[0];
int times = Integer.parseInt(temp);
CustomList customList= new CustomList();
customList.setSomething(somthing);
customList.setSomething2(somthing1);
customList.setTimes(times);
customLists.add(customList);
position = position+3;
}
return customLists;
}
Note: this is refer if you are using same string pattern as you mention in the above problem
Using a Scanner object to read the lines and breaking up each line using the split() function. Then, create a new customlist object, and add it into your ArrayList<customlist>.
public void readFile(File file, ArrayList<customlist> myList)
{
Scanner sc = new Scanner(file);
String line;
while(sc.hasNextLine())
{
line=sc.nextLine();
String[] fields = line.split(",");
int times = Integer.parseInt(fields[2].trim());
customlist myCustom = new myList(fields[0].trim(), fields[1].trim(),
times);
myList.add(myCustom);
}
sc.close();
}
You may also handle exceptions if you think its necessary.

Null when splitting a string

I need to create my own sort method for an array, and I begin my splitting the text file into an array filled with the words. The file format is: an integer n, followed by n words.
Here's an example: 4 hello hello world hello
However, my array prints: [null4, hello, hello, world, hello]
WHY! I don't understand why there is a null before. And, if I remove the number 4 (which plays no role in my program at the moment) I get: [nullhello, hello, world, hello]
Can you please help me remove this null? Thanks in advance!
public static void main(String[] args) throws FileNotFoundException {
filePath = "***TEXT FILE HERE***";
fileInput = new Scanner(new File(filePath));
convertFile(fileInput);
}
public static void convertFile(Scanner file) {
String line;
while (fileInput.hasNextLine()) {
line = fileInput.nextLine();
fileData = fileData + line;
}
String[] array = createArray(fileData);
System.out.println(Arrays.toString(array));
}
public static String[] createArray(String data) {
String[] dataArray = data.split("\\s+");
return dataArray;
}
You did not initialise the fileData variable before using it.
try
fileData = "";
fileData = fileData + line;
this is not the best choise for building a string... try to replace it with a StringBuilder
StringBuilder fileData = new StringBuilder(); // to instantiate
fileData.append(line + "\n"); // to add lines
String finalString = fileData.toString(); // to build the string
for larger strings your method of concatenation will become very slow

How to read a file with delimiters

If I have a file like this, in which each section is delimited by "**". How can I read each section and put them into different data structures?
AAA
BBB
CCC
**
ccc:cc
ddd:dd
**
xyz;XYZ
abc;ABC
**
Name: John
Email: john#gmail.com
Name: Jack
Email: jack#gmail.com
Name: kate
Email: kake#hotmail.com
**
In a while loop, I can test whether the line equals "**". But since the number of lines in each section is unknown, it seems hard to recognize which section a particular line belongs to?
String line;
while((line=reader.readline()) != null){
if(!line.equals("**"){
// the line has to be parsed and built into different data structures.
For the first section, AAA,BBB,CCC will be added into an ArrayList.
}
}
IMO you should just make the reading method a little bit more clever.
Here is an example (a kind of pseudo code, assuming you have a reader that does an actual IO):
void main() {
List<List<String>> sections = ...
while(reader.hasMoreDataToProcess()) {
sections.add(processSection(reader));
}
}
List<String> processSection(reader) {
List<String> section = ...
do {
String line = reader.readLine();
if(line.equals("**")) { // end of section or whatever delimiter you have
return section;
}
section.addLine(line);
}while(true);
}
Sorry, in a hurry, so pseudocode:
currentSection = []
sections = [currentSection]
for each line:
if line is the separator:
currentSection = []
add currentSection to sections
else:
add line to currentSection
You can use split method of the string class in Java.
String string = "a-b,b-d,c-s,d-w,e-e,f-e";
String[] parts = string.split(",");
String part1 = parts[0]; // a-b
String part2 = parts[1]; // b-d
You should use scanner for this scenario. Here's how you do it. This code is not tested.
File file = new File("somefile.txt");
try {
Scanner sc = new Scanner(file);
sc.useDelimeter("\\*\\*");
while (sc.hasNext()) {
String s = sc.next();
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
You can use a Scanner with a FileInputStream to scan the file, using setDelimiter(String) (which accepts a regex pattern) to set your delimiter.
public class Test {
public static void main(String[] args) {
ArrayList<String> firstList = new ArrayList<>();
ArrayList<String> secondList = new ArrayList<>();
try(Scanner scanner = new Scanner(new FileInputStream(new File("yourFile.txt"))).useDelimiter("[*]+")) {
firstList.add(scanner.next());
secondList.add(scanner.next());
// and so on
scanner.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}
This will take everything above ** and create a String out of it. If you want, you can then split the String, and grab the data from each line.
String[] split = scanner.next().split("\n");
for(String string : split) {
firstList.add(string);
}
In the first example, the regex [*]+ searches for multiple *. Learn more about regex (regular expressions) to add flexibility.

Identifying each word in a file

Importing a large list of words and I need to create code that will recognize each word in the file. I am using a delimiter to recognize the separation from each word but I am receiving a suppressed error stating that the value of linenumber and delimiter are not used. What do I need to do to get the program to read this file and to separate each word within that file?
public class ASCIIPrime {
public final static String LOC = "C:\\english1.txt";
#SuppressWarnings("null")
public static void main(String[] args) throws IOException {
//import list of words
#SuppressWarnings("resource")
BufferedReader File = new BufferedReader(new FileReader(LOC));
//Create a temporary ArrayList to store data
ArrayList<String> temp = new ArrayList<String>();
//Find number of lines in txt file
String line;
while ((line = File.readLine()) != null)
{
temp.add(line);
}
//Identify each word in file
int lineNumber = 0;
lineNumber++;
String delimiter = "\t";
//assess each character in the word to determine the ascii value
int total = 0;
for (int i=0; i < ((String) line).length(); i++)
{
char c = ((String) line).charAt(i);
total += c;
}
System.out.println ("The total value of " + line + " is " + total);
}
}
This smells like homework, but alright.
Importing a large list of words and I need to create code that will recognize each word in the file. What do I need to do to get the program to read this file and to separate each word within that file?
You need to...
Read the file
Separate the words from what you've read in
... I don't know what you want to do with them after that. I'll just dump them into a big list.
The contents of my main method would be...
BufferedReader File = new BufferedReader(new FileReader(LOC));//LOC is defined as class variable
//Create an ArrayList to store the words
List<String> words = new ArrayList<String>();
String line;
String delimiter = "\t";
while ((line = File.readLine()) != null)//read the file
{
String[] wordsInLine = line.split(delimiter);//separate the words
//delimiter could be a regex here, gotta watch out for that
for(int i=0, isize = wordsInLine.length(); i < isize; i++){
words.add(wordsInLine[i]);//put them in a list
}
}
You can use the split method of the String class
String[] split(String regex)
This will return an array of strings that you can handle directly of transform in to any other collection you might need.
I suggest also to remove the suppresswarning unless you are sure what you are doing. In most cases is better to remove the cause of the warning than supress the warning.
I used this great tutorial from thenewboston when I started off reading files: https://www.youtube.com/watch?v=3RNYUKxAgmw
This video seems perfect for you. It covers how to save file words of data. And just add the string data to the ArrayList. Here's what your code should look like:
import java.io.*;
import java.util.*;
public class ReadFile {
static Scanner x;
static ArrayList<String> temp = new ArrayList<String>();
public static void main(String args[]){
openFile();
readFile();
closeFile();
}
public static void openFile(){
try(
x = new Scanner(new File("yourtextfile.txt");
}catch(Exception e){
System.out.println(e);
}
}
public static void readFile(){
while(x.hasNext()){
temp.add(x.next());
}
}
public void closeFile(){
x.close();
}
}
One thing that is nice with using the java util scanner is that is automatically skips the spaces between words making it easy to use and identify words.

removeAll operation on arraylist makes program hang

I'm trying to read in from two files and store them in two separate arraylists. The files consist of words which are either alone on a line or multiple words on a line separated by commas.
I read each file with the following code (not complete):
ArrayList<String> temp = new ArrayList<>();
FileInputStream fis;
fis = new FileInputStream(fileName);
Scanner scan = new Scanner(fis);
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (scan.hasNext()) {
String md5 = scan.next();
temp.add(md5);
}
}
scan.close();
return temp;
Each file contains almost 1 million words (I don't know the exact number), so I'm not entirely sure that the above code works correctly - but it seems to.
I now want to find out how many words are exclusive to the first file/arraylist. To do so I planned on using list1.removeAll(list2) and then checking the size of list1 - but for some reason this is not working. The code:
public static ArrayList differentWords(String fileName1, String fileName2) {
ArrayList<String> file1 = readFile(fileName1);
ArrayList<String> file2 = readFile(fileName2);
file1.removeAll(file2);
return file1;
}
My main method contains a few different calls and everything works fine until I reach the above code, which just causes the program to hang (in netbeans it's just "running").
Any idea why this is happening?
You are not using input in
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (scan.hasNext()) {
String md5 = scan.next();
temp.add(md5);
}
}
I think you meant to do this:
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (input.hasNext()) {
String md5 = input.next();
temp.add(md5);
}
}
but that said you should look into String#split() that will probably save you some time:
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] tokens = line.split(",");
for (String token: tokens) {
temp.add(token);
}
}
try this :
for(String s1 : file1){
for(String s2 : file2){
if(s1.equals(s2)){file1.remove(s1))}
}
}

Categories