I am trying to write a coded that reads in a text file into an array list. However, I am unsure how to parse my text file into strings to correctly be put into an array list. Here is a sample text file that I need to use.
This should be the sample question.
2
one
two
three
four
0
4
6
My Java code below:
package javaapplication8;
import java.util.*;
import java.io.*;
public class JavaApplication8 {
public static void main(String[] args) throws IOException{
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
int numItems = Integer.parseInt(fScan.nextLine());
ArrayList<String> Questions = new ArrayList<String>();
for(int i=0; i < numItems; i++)
{
Questions.add(fScan.nextLine());
}
System.out.print("The array is: " + Questions);
}
From your comment about the variable numLines below, you don't need to parse integers from the content so you can remove the line:
int numItems = Integer.parseInt(fScan.nextLine());
Then to output every line to the array, you can use Scanner.hasNextLine():
while (fScan.hasNextLine()) {
questions.add(fScan.nextLine());
}
Related
I currently have the words reading from a text file into a String ArrayList. My assignment asked me to not use any HashMaps or HashSets, anything of that nature. While counting the occurrences of a word I also have to remove any additionals(, . : [] ; = -) and duplicates of the same word. Just currently having trouble with how to remove the additionals and removing duplicates any help is appreciated (Beginner at Java). Unable to use splits.
Here is my code:
public static void main(String[] args) throws FileNotFoundException, IOException
{
//Create input Scanner
FileInputStream file = new FileInputStream("Assignment1BData.txt");
Scanner input = new Scanner(file);
//Create the ArrayList
ArrayList<String> wordCount = new ArrayList<String>();
ArrayList<Integer> numCount = new ArrayList<Integer>();
//Read through the file and find the words from text
while(input.hasNext())
{
String word = input.next();
//Create index to look through lines of text
if(wordCount.contains(word))
{
int index = numCount.indexOf(word);
numCount.set(index, numCount.get(index) + 1);
}
else
{
wordCount.add(word);
numCount.add(1);
}
}
input.close();
file.close();
//Print output in for loop
for(int i = 0; i < wordCount.size(); i++)
{
System.out.println(wordCount.get(i) + " = " + numCount.get(i));
}
}
indexOf(Object o) method on the ArrayList should solve the problem of duplicates. Before you go on to add the string to the ArrayList simply call this method if that string already exists in the ArrayList it returns the index otherwise it returns -1. Just keep adding the string read from the text file to ArrayList as long as the indexOf method returns -1 otherwise simply ignore(since it already exists).
You can use something like: newList = removeDuplicates(YourList) So that the duplicates would get removed and you get a new list...
Got it here: https://www.geeksforgeeks.org/how-to-remove-duplicates-from-arraylist-in-java/
You can try by creating a list with unique elements using Stream API as,
List<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
List<Integer> listWithoutDuplicates = listWithDuplicates.stream()
.distinct()
.collect(Collectors.toList());
Then iterate over the original array/list (listWithDuplicates ) and get it compared with listWithoutDuplicates and count for the match.
Try this, for replacng special symbols before doing lookup and doing the count .
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class WordCounter {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//Create input Scanner
FileInputStream file = new FileInputStream("/tmp/Assignment1BData.txt");
Scanner input = new Scanner(file);
//Create the ArrayList
ArrayList<String> wordCount = new ArrayList<String>();
ArrayList<Integer> numCount = new ArrayList<Integer>();
//Read through the file and find the words from text
while(input.hasNextLine())
{
String word = input.nextLine();
//Replace all characters
word = word.replaceAll("[,.:;=-\\[\\]]", "");
//Create index to look through lines of text
if(wordCount.contains(word))
{
int index = wordCount.indexOf(word);
numCount.set(index, numCount.get(index) + 1);
}
else
{
wordCount.add(word);
numCount.add(1);
}
}
input.close();
file.close();
//Print output in for loop
for(int i = 0; i < wordCount.size(); i++)
{
System.out.println(wordCount.get(i) + " = " + numCount.get(i));
}
}
}
Im trying to read in a .txt file and make a multi dimensional array out of it. I dont understand why the i and j loops arent populating my array. Any pointers much appreciated....
import java.util.*;
import java.io.*;
public class arrayChallenge {
public static void main(String[] args) throws FileNotFoundException{
File input = new File("input.txt");
Scanner scan1 = new Scanner(input);
int width=10, height=10;
char [][] arrayMulti = new char[width][height];
for(int i=0; i<height; i++){
String x = scan1.next();
char[] chars = x.toCharArray();
for(int j=0; j<width; j++){
arrayMulti[i][j]= chars[j];
}
}
for(char [] xy: arrayMulti){
System.out.println(Arrays.toString(xy));
}
}
}
There is nothing wrong with your i and j loops as far as I can see. As long as the provided path to your file is correct and the file has the needed number of lines (>= your width variable) and each line has the needed number of characters (>= your height variable), it should work fine.
I'm trying to make a method in java that will use a scanner to read a List String. I want the program to divide the array word by word using the delineator "//s". I already got each array by the names of the people in the text file, I am just trying to divide the array further so that way i can sort them by there information (Ex. if they have f for female I would be able to call that specific part of the array using arrayList.get(index) and sort it by gender that way) Here is my code:
Sorry for being unclear, here is my full code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Filereader {
public static void replaceSlash(List<String> array) {
for (int i = 0; i < array.size(); i++)
{
if (array.get(i).contains("-"))
{
array.set(i, array.get(i).replace("-", "/"));
}
}
}
public static void split( List<String> array ) {
Scanner scanner = new Scanner().useDelimiter("\\s");
for (int i= 0; i < array.size(); i++) {
while (scanner.hasNext()) {
array.set(i, scanner.next());
}
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("Please type the name of the file you wish to sort: ");
//get the name of the file
Scanner scanner = new Scanner(System.in);
File fileName = new File(scanner.nextLine());
scanner = new Scanner(fileName).useDelimiter("\\s");
List<String> annaK = new ArrayList<String>();
List<String> martinaH = new ArrayList<String>();
List<String> monicaS = new ArrayList<String>();
while (scanner.hasNextLine()) {
annaK.add(scanner.nextLine());
martinaH.add(scanner.nextLine());
monicaS.add(scanner.nextLine());
}
replaceSlash(annaK);
replaceSlash(martinaH);
replaceSlash(monicaS);
split(annaK);
System.out.println(annaK);
System.out.println(martinaH);
System.out.println(monicaS);
}
}
You can make one scanner for every string within the list, then loop over that
for (String a : array) {
Scanner scanner = new Scanner(a).useDelimiter("\\s");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
}
However, a.split() or StringTokenizer make more sense than a Scanner here
Besides that, array.set won't work because you're assigning the same i value for multiple words within each individual a value... Which will result in only the last value in the scanned string to be assigned to that index of the list
If you're trying to splits all words within a list into a new list, then you'll actually need to create and append values to a separate list object (don't modify your parameters, and don't have methods with side effects)
Basically i added "import java.util.Scanner". but I wanted my code to work without that library and only "import java.io*" . However i want all my words (english word in the dictionary with the total of 109562 words in this case) in my text file to be inside the string array. Hence, in this case, without the scanner. how to do that?
import java.io.*;
import java.util.Scanner;
public class tester{
public static void main (String [] args) throws IOException{
File f = new File("C:/Users/alienware14/Documents/words.txt");
String [] words = new String [109562];
readWords(f , words);
/*
System.out.println("----ALL WORDS IN WORDS.TXT----");
for(int i=0; i<words.length; i++){
System.out.println("");
System.out.print(words[i]);
} */
}
public static String [] readWords(File f , String [] words) throws FileNotFoundException {
Scanner s;
s = new Scanner(f);
for(int i = 0; i < words.length; i++){
while (words[i] == null) {
words[i] = s.next();
}
}
s.close();
return words;
}
}
You could use a java.io.FileReader instead of a Scanner. Just google 'Java read file' to find an example for it (Using a Scanner for reading files is quite exotic). Though I don't really understand why you have a problem with importing a Scanner. Sounds like homework..
Try split method
String[] words = yourtext.split(" "); //user space in split method for words
What im trying to do is make this txt file into an array, then with the numbers that are incorrect(not numbers) put them into the pw wrong.txt and display them
import java.util.*;
import java.io.*;
public class MorenoJonathonTranslator
{
public static void main(String[] args) throws IOException
{
Scanner file = new Scanner(new File("numbers.txt"));
ArrayList<String> alphabeticPhoneNumbers = new ArrayList<String>();
int i = 0;
System.out.println("Original: ");
System.out.println("Numberical: ");
while(file.hasNextLine() ){
alphabeticPhoneNumbers.add(file.next());
alphabeticPhoneNumbers.add(file.next());
file.nextLine();
System.out.println(alphabeticPhoneNumbers.get(i));
i+=2;
}
PrintWriter pw = new PrintWriter("wrong.txt");
for( i = 0; i < 8; i++){
pw.print(alphabeticPhoneNumbers.get(i));
pw.print(alphabeticPhoneNumbers.get(i+1));
pw.println();
i++;
}
pw.close();
}
}
What is it that you're trying to achieve? I'd think that your program is broken and doesn't print anything because you're somehow incrementing i to a value that's already greater than 7 so your second loop doesn't do anything. Just a guess though as I don't know how your data looks like. Try not reusing index variables like i.
I'm not exactly sure what you are trying to achieve. If you only want to display them while the program's execution, you could use a System.out.println within the last for loop.