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)
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));
}
}
}
In the following code I read text file with a list of movies and create a String array of the list of movies using a helper method. Within the method I am able to read and print each line of the file. However, when I attempt to iterate over the returned array in the main method I get only "null". Why is this happening. In my research so far, I have not been able to find a similar problem posted by someone else. Please help. Thanks.
import java.util.Random;
import java.util.Scanner;
import java.io.File;
public class GuessTheMovie {
public static void main(String[] args) throws Exception {
try {
// Create File and Scanner objects
File file = new File("movies.txt");
Scanner scanner = new Scanner(file);
// Create String array to store all movie titles
List<String> movies = createMoviesArray(scanner);
for (String movie : movies) {
System.out.println(movie);
}
/*
String[] movies = createMoviesArray(scanner);
for (int i = 0; i < movies.length; i++) {
System.out.println(movies[i]);
} */
} catch (Exception e) {
System.out.println("Could not find file.");
}
}
////////////////////////// HELPER METHODS ////////////////////////////////////
/*
// Create String array to store all movie titles
private static String[] createMoviesArray(Scanner scanner) {
int count = 0;
String[] movies; // = new String[500];
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(count + " : " + line);
count += 1;
}
movies = new String[count];
return movies;
}*/
private static List<String> createMoviesArray(Scanner scanner) {
List<String> movies = new ArrayList<>();
// get line count for the size of the array
while (scanner.hasNextLine()) {
movies.add(scanner.nextLine());
}
return movies;
}
That is quite normal, since you don't put any values in your array.
private static String[] createMoviesArray(Scanner scanner) {
int count = 0;
String[] movies; // = new String[500];
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(count + " : " + line);
count += 1;
}
movies = new String[count]; // all you do here, is create an array with 'count' spaces, all default values (being null)
return movies;
}
If you want to work like this, you have two options (that immediately jump to mind):
Use an array, and create a new one for after every read. This is very resource consuming, meaning: DON'T DO THIS
Since you don't know the number of elements before all are read: use a List.
private static List<String> createMoviesArray(Scanner scanner) {
List<String> movies = new ArrayList<>();
while (scanner.hasNextLine()) {
movies.add(scanner.nextLine());
}
return movies;
}
Just before return in the createMoviesArray() method you create a new array. You never add anything to that array and thus it is empty after returning from that method. You should make a new array before iterating over the file.
If you don't know the size of the file and how many lines it has you probably should use some Collection with dynamic size, like ArrayList.
With your line movies = new String[count]; you are creating a new array of Strings. At this point in time the array will contain only NULL values which. Nowhere in your code you are actually writing something into the array. Thats why your main method correctly prints null.
This is because you are not adding the data to the movies array, you are only initializing it.
If you were to print the movies object at the end of your helper method you would see that it also is null.
I suggest using an ArrayList as you don't know how large the array needs to be, it would then go something like this:
import java.util.Random;
import java.util.Scanner;
import java.io.File;
public class GuessTheMovie {
public static void main(String[] args) throws Exception {
try {
// Create File and Scanner objects
File file = new File("movies.txt");
Scanner scanner = new Scanner(file);
// Create String array to store all movie titles
ArrayList<String> movies = createMoviesArray(scanner); // change this to ArrayList
for (movie : movies) { // I used a foreach loop
System.out.println(movie);
}
} catch (Exception e) {
System.out.println("Could not find file.");
}
}
////////////////////////// HELPER METHODS ////////////////////////////////////
// Create String array to store all movie titles
private static String[] createMoviesArray(Scanner scanner) {
int count = 0;
ArrayList<String> movies = new ArrayList<String>(); // change to Array List
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(count + " : " + line);
count += 1;
movies.add(line); // Add to end of ArrayList
}
return movies;
}
You can do the same thing in this way also:-
package com.adddemo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GuessTheMovie {
public static void main(String[] args) throws Exception {
try {
// Create File and Scanner objects
File file = new File("C:\\Users\\lenovo\\Desktop\\movies.txt");
Scanner scanner = new Scanner(file);
// Create String array to store all movie titles
List movies = createMoviesArray(scanner);
for (int i = 0; i < movies.size(); i++) {
System.out.println(i+" : "+movies.get(i));
}
} catch (Exception e) {
System.out.println("Could not find file.");
}
}
////////////////////////// HELPER METHODS ////////////////////////////////////
// Create String array to store all movie titles
private static List createMoviesArray(Scanner scanner) {
int count = 0;
List movies = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(count + " : " + line);
count += 1;
movies.add(line);
}
return movies;
}
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class BuildGraph {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner((new File("dictionary.txt")));
ArrayList<String> words=new ArrayList<String>();
while(sc.hasNextLine()){
if(sc.next().length()==4){
words.add(sc.next());
//sc.next();
}
System.out.println(words);
}
// sc.close();
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i));
}
}
}
This is my code, and I am trying to read only 4 letter words from a dictionary file, but when i run my code it gives me all the words from dictionary files
Thank-you in advance.
You code needs some tweaks. Basically you should not be calling sc.next() twice to get the same element as calling next() moves the pointer to the next element
Rewrite your while loop to this:
while(sc.hasNextLine() && sc.hasNext()){
String word = sc.next();
if(word.length()==4){
words.add(word);
}
System.out.println(words);
}
I'm making a translator in Java to translate a fake language that I came up with for fun. I input an English word and it returns it's equivalent word in the other language. It's successfully translating everything, but each new word is on a separate line and I just want the output on one line. I'm still new to Java but here is my code:
import java.io.*;
import java.util.*;
public class Translator {
private static Scanner scan;
public static void main(String[] args) {
HashMap <String, String> XanthiumLang = new HashMap <String, String>();
XanthiumLang.put("hello", "fohran");
XanthiumLang.put("the", "krif");
XanthiumLang.put("of", "ney");
XanthiumLang.put("to", "dov");
XanthiumLang.put("and", "ahrk");
Scanner scan = new Scanner(System.in);
String sentence = scan.nextLine();
String[] result = sentence.split(" ");
for(int i = 0; i < result.length; i++){
if(XanthiumLang.containsKey(result[i])){
result[i] = XanthiumLang.get(result[i]);
}
System.out.println(result[i]);
}
}
}
I only have a few words in the code as of right now and they are stored in a hashmap. Anyways like I said the output of each word is on a separate line, not on just one line. Any ideas or changes to my code would be helpful!
Use System.out.print();. Doing so will print the entire array on one line. System.out.println(); will print the result on a new line each time (hence the ln at the end).
import java.io.*;
import java.util.*;
public class Translator {
private static Scanner scan;
public static void main(String[] args) {
HashMap <String, String> XanthiumLang = new HashMap <String, String>();
XanthiumLang.put("hello", "fohran");
XanthiumLang.put("the", "krif");
XanthiumLang.put("of", "ney");
XanthiumLang.put("to", "dov");
XanthiumLang.put("and", "ahrk");
Scanner scan = new Scanner(System.in);
String sentence = scan.nextLine();
String[] result = sentence.split(" ");
for(int i = 0; i < result.length; i++){
if(XanthiumLang.containsKey(result[i])){
result[i] = XanthiumLang.get(result[i]);
}
System.out.print(result[i]);
}
}
}
More on the different formats here.
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());
}