I am making a flashcard like app for my high school software project. I am able to store words and their respective translation by writing them to a file, but I was wondering if there was a possible way to read them into a 2d array.
Could I separate them with commas, or some other character?
Additionally would there be a way to link the words and their respective translations. For example if I called word 'x', is there a function to call word 'translated x' if it is in an array?
Thanks heaps!!
You might want to look at Maps. That way you could look up each word by the word itself rather than iterating through an Array. Maps use Key Value pairs. Unfortunately, they are unidirctional (you can't look up a key by it's value).
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Let's break down the problem a bit.
read the file
parse each line in the file to determine a word and a translation
store the word and the translation in a data structure (#Glen Pierce's suggestion about using a map is a good one)
Let's say our file looks like this, we use a comma to delimit the word and the translation (this is also the extent of my Spanish vocabulary):
hello,hola
good,bueno
Now some code, let's read the file into a map.
// a map of word to translation
Map<String, String> wordMap = new HashMap<String, String>();
// a class that can read a file (we wrap the file reader in a buffered reader because it's more efficient to read a file in chunks larger than a single character)
BufferedReader fileReader = new BufferedReader(new FileReader("my-file.txt"));
// a line from the file
String line;
// read lines until we read a line that is null (i.e. no more lines)
while((line = fileReader.getLine()) != null) {
// split the line, returns an array of parts
String[] parts = line.split(",");
// store the parts in meaningful variables
String word = parts[0];
String translation = parts[1];
// now, store the word and the translation in the word map
wordMap.put(word, translation);
}
// close the reader (note: you should do this with a try/finally block so that if you throw an exception, you still close the reader)
fileReader.close();
So now we have a map that has all the words and translations in the file. Given a word, you can retrieve the translation like this:
String word = "hello";
String translation = wordMap.get(word);
System.out.println(word + " translates to " + translation);
Output:
hello translates to hola
I guess the next step is to have the user give you a word and for you to return the correct translation. I'll leave that to you.
Do you need to store the words in a text file (i.e., do they need to persist), or can you store them in memory?
If they need to be written to a text file, try this:
// Create a file
File file = new File("file.txt");
// Initialize a print writer to print to the file
PrintWriter pw = new PrintWriter(file);
Scanner keyboard = new Scanner(System.in);
// Populate
boolean stop = false;
do {
String word;
String translation;
System.out.print("Enter a word: ");
word = keyboard.nextLine().trim() + " ";
if (!word.equals("quit ")) {
pw.print(word);
System.out.print("Enter its translation: ");
translation = keyboard.nextLine().trim();
pw.println(translation);
} else {
stop = true;
}
} while (!stop);
// Close the print writer and write to the file
pw.close();
// Initialize a scanner to read the file
Scanner fileReader = new Scanner(file);
// Initialize a hash table to store the values from the file
Hashtable<String, String> words = new Hashtable<String, String>();
// Add the information from the file to the hash table
while (fileReader.hasNextLine()) {
String line = fileReader.nextLine();
String[] array = line.split(" ");
words.put(array[0], array[1]);
}
// Print the results
System.out.println("Results: ");
words.forEach((k, v) -> System.out.println(k + " " + v));
fileReader.close();
keyboard.close();
Note that I am using a space to separate the word from its translation. You can just as easily use a comma or a semicolon or what have you. Just replace line.split(" ") with line.split(< your separating character here>) and concatenate it to the end of word = keyboard.nextLine().trim().
If you don't need to save the information and just need to collect the user's input, it's even simpler:
Scanner keyboard = new Scanner(System.in);
// Initialize a hash table to store the values from the user
Hashtable<String, String> words = new Hashtable<String, String>();
// Get the input from the user
boolean stop = false;
do {
String word;
String translation;
System.out.print("Enter a word: ");
word = keyboard.nextLine().trim();
if (!word.equals("quit")) {
System.out.print("Enter its translation: ");
translation = keyboard.nextLine().trim();
words.put(word, translation);
} else {
stop = true;
}
} while (!stop);
// Print the results
System.out.println("Results: ");
words.forEach((k, v) -> System.out.println(k + " " + v));
keyboard.close();
Related
For example, the content of a file is:
black=white
bad=good
easy=hard
So, I want to store in a map this words as key and value (ex: {black=white, bad=good} ). And my problem is when I read string I have to skip a char '=' which disappears key and value. How to make this?
In code below I make a code which read key and value from file, but this code works just when between words is SPACE, but I have to be '='.
System.out.println("File name:");
String pathToFile = in.nextLine();
File cardFile = new File(pathToFile);
try(Scanner scanner = new Scanner(cardFile)){
while(scanner.hasNext()) {
key = scanner.next();
value = scanner.next();
flashCards.put(key, value);
}
}catch (FileNotFoundException e){
System.out.println("No file found: " + pathToFile);
}
Use the split method of String in Java.
so after reading your line, split the string and take the key and value as so.
String[] keyVal = line.split("=");
System.out.println("key is ", keyVal[0]);
System.out.println("value is ", keyVal[1]);
You can change the delimiter for the scanner.
public static void main (String[] args) throws java.lang.Exception
{
String s = "black=white\nbad=good\neasy=hard";
Scanner scan = new Scanner(s);
scan.useDelimiter("\\n+|=");
while(scan.hasNext()){
String key = scan.next();
String value = scan.next();
System.out.println(key + ", " + value);
}
}
The output:
black, white
bad, good
easy, hard
Changing the delimiter can be tricky, and it could be better to just read each line,then parse it. For example, "\\n+|=" will split the tokens by either one or more endlines, or an "=". The end line is somewhat hard coded though so it could change depending on the platform the file was created on.
A simple "if" condition will solve it.
if (key == '='){ break;}
I am working on an assignment where I have to create an interval(which I have already completed) and from a text file, read in the girls names that are found within the interval and put them into an array list. I also have to read in all the male names that start with the letter "J", and then calculate how many male births start with the letter "J" and print out that information. Below is the code I have so far:
public static int generateRandomInt(int lowerLimit, int upperLimit) {
int value = lowerLimit + (int)Math.ceil( Math.random() * ((upperLimit - lowerLimit) + 1)); //generates a random number between 1 and 10
return value;
}// end generateRandomInt
public static void main(String[] args) {
// Read from filename: top20namesNM1994.txt
// Generating a interval, the lower random number comes from 50 to 100, and the upper random number comes from 150 to 200.
// Print out this interval
// Read all the girls names, which birth numbers are inside of the interval you construct, into a array or ArrayList.
// Print out the array.
//Print out all the males names, which start with letter "J".
//Determine how many male births start with names starting with the letter "J", and print out the summary information.
final int LOW1 = 50;
final int LOW2 = 100;
final int HIGH1 = 150;
final int HIGH2 = 200;
ArrayList<String>girlNames = new ArrayList<String>();
String line = "";
int interval_low = generateRandomInt(LOW1, LOW2);
int interval_high = generateRandomInt(HIGH1, HIGH2);
System.out.println("The interval is ( " + interval_low + " , " + interval_high + " )" );
try {
FileReader inputFile = new FileReader("C:\\Users\\drago\\eclipse-workspace-Ch6to7FinalExam2\\MorrisJFinalExam2\\src\\top20namesNM1994.txt");
//Scanner scan = new Scanner (inputFile);
BufferedReader br = new BufferedReader(inputFile);
while((line = br.readLine()) != null) {
line.split("\\s+");
if()
girlNames.add();
}
}
catch(IOException e) {
System.out.println("File not Found!");
}
if()
System.out.println(girlNames.toString());
}
I am stuck on how to get the girl names that are within the interval created and also how to read in the boy names. Attached is the text file.
TextFile
Okay...you know how to read in the text file (somewhat) which is good however you can simplify the code a bit:
ArrayList<String> girlNames = new ArrayList<>();
String filePath = "C:\\Users\\drago\\eclipse-workspace-Ch6to7FinalExam2\\"
+ "MorrisJFinalExam2\\src\\top20namesNM1994.txt";
String line = "";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
while ((line = br.readLine()) != null) {
// .....................
// ..... Your Code .....
// .....................
}
}
catch (IOException ex) {
ex.printStackTrace();
}
Try With Resources is used here so that your BufferedReader is automatically closed. If all your going to do is read the desired text file then the Scanner object you have commented out in your code is also a pretty good alternative for reading text files if properly used.
It's obvious from your incomplete code that each data line within this file is White-Space or Tab delimited simply based on the Regular Expression ("\\s+") used within the String#split() method (the "\\s+" expression will split a string on any number of white-spaces and or tabs that are contained within that string). Do Note however that the code line where you are using the String#split() method is not completed properly.... If you read the linked tutorial you will find that this method is used to fill a String Array which is good because usually, this is what you want to do with file data lines. Doing so of course allows you to retrieve the exact data portion desired from each data file line.
No one here has a clue what is contained within your specific data text file because like so many others the contents within it is obviously so supper-duper classified that not even fictitious data will suffice. Because of this there is in no way a means provide you with an accurate array index value or values to use against your String Array in order to retrieve your desired data from each data file line. This is good however since it is you who needs to figure this out and once you do you will have the task beaten to submission.
I am creating a school program for a project in which I a writing words and translations to a file, (separated by a character). I have read that I can read them via a hash map into an array. I was just wondering if someone could point me in the right direction as how to do this.
If anyone has a better idea of how to store and retrieve the words I would love to learn. The reason I am writing to a file is so the user can store as many words as they want.
Thank-you so much :D
You can use java.util.HashMap to store user words and related translations:
String userWord = null;
String translation = null, translation1 = null;
Map<String, String[]> map = new HashMap();
map.put(userWord, new String[] { translation, translation1 });
String[] translations = map.get(userWord);
This map lets you map single userWord to multiple translations.
Here's a reference for learning how to use BufferedReader: BufferedReader
Here's a reference for learning how to use FileReader: FileReader
import java.io.*;
class YourClass
{
public static void main() throws IOException
{
File f = new File("FilePath"); // Replace every '\' with '/' in the file path
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = "";
String FileString = "";
while((line = br.readLine()) != null)
{
// Now 'line' contains each line of the file
// If you want, you can store the entire file in a String, like this:
FileString += line + "\n"; // '\n' to register each new line
}
System.out.println(FileString);
}
} // End of class
I'm still a newbie, and don't understand much about HashMap, but I can tell you how to store it in a String array:
FileString = FileString.replaceAll("\\s+", " ");
String[] Words = FileString.split(" ");
FileString.replaceAll("\\s+", " ") - Replaces 1 or more spaces with 1 space, so as to avoid any logical errors.
FileString.split(" ") - Returns a String array of each String separated by a space.
You can try something like this
File f = new File("/Desktop/Codes/Text.txt");
// enter your file location
HashMap<String, String[]> hs = new HashMap<String, String[]>();
// throw exception in main method
Scanner sc = new Scanner(f);
String s="";
while(sc.hasNext()){
s = sc.next();
// create a method to search translation
String []trans = searchTrans(s);
hs.put(s, trans);
}
I am having trouble with a programming assignment. I need to read data from a txt file and store it in parallel arrays. The txt file contents are formatted like this:
Line1: Stringwith466numbers
Line2: String with a few words
Line3(int): 4
Line4: Stringwith4643numbers
Line5: String with another few words
Line6(int): 9
Note: The "Line1: ", "Line2: ", etc is just for display purposes and isn't actually in the txt file.
As you can see it goes in a pattern of threes. Each entry to the txt file is three lines, two strings and one int.
I would like to read the first line into an array, the second into another, and the third into an int array. Then the fourth line would be added to the first array, the 5th line to the second array and the 6th line into the third array.
I have tried to write the code for this but can't get it working:
//Create Parallel Arrays
String[] moduleCodes = new String[3];
String[] moduleNames = new String[3];
int[] numberOfStudents = new int[3];
String fileName = "myfile.txt";
readFileContent(fileName, moduleCodes, moduleNames, numberOfStudents);
private static void readFileContent(String fileName, String[] moduleCodes, String[] moduleNames, int[] numberOfStudents) throws FileNotFoundException {
// Create File Object
File file = new File(fileName);
if (file.exists())
{
Scanner scan = new Scanner(file);
int counter = 0;
while(scan.hasNext())
{
String code = scan.next();
String moduleName = scan.next();
int totalPurchase = scan.nextInt();
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
}
}
The above code doesn't work properly. When I try to print out an element of the array. it returns null for the string arrays and 0 for the int arrays suggesting that the code to read the data in isn't working.
Any suggestions or guidance much appreciated as it's getting frustrating at this point.
The fact that only null's get printed suggests that the file doesn't exist or is empty (if you print it correctly).
It's a good idea to put in some checking to make sure everything is fine:
if (!file.exists())
System.out.println("The file " + fileName + " doesn't exist!");
Or you can actually just skip the above and also take out the if (file.exists()) line in your code and let the FileNotFoundException get thrown.
Another problem is that next splits things by white-space (by default), the problem is that there is white-space on that second line.
nextLine should work:
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.parseInt(scan.nextLine());
Or, changing the delimiter should also work: (with your code as is)
scan.useDelimiter("\\r?\\n");
You are reading line so try this:
while(scan.hasNextLine()){
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.pasreInt(scan.nextLine().trim());
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = scan.nextInt();
scan.nextLine()
This will move scanner to proper position after reading int.
So I can search for a string in my text file, however, I wanted to sort data within this ArrayList and implement an algorithm. Is it possible to read from a text file and the values [Strings] within the text file be stored in a String[] Array.
Also is it possible to separate the Strings? So instead of my Array having:
[Alice was beginning to get very tired of sitting by her sister on the, bank, and of having nothing to do:]
is it possible to an array as:
["Alice", "was" "beginning" "to" "get"...]
.
public static void main(String[]args) throws IOException
{
Scanner scan = new Scanner(System.in);
String stringSearch = scan.nextLine();
BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
List<String> words = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
for(String sLine : words)
{
if (sLine.contains(stringSearch))
{
int index = words.indexOf(sLine);
System.out.println("Got a match at line " + index);
}
}
//Collections.sort(words);
//for (String str: words)
// System.out.println(str);
int size = words.size();
System.out.println("There are " + size + " Lines of text in this text file.");
reader.close();
System.out.println(words);
}
To split a line into an array of words, use this:
String words = sentence.split("[^\\w']+");
The regex [^\w'] means "not a word char or an apostrophe"
This will capture words with embedded apostrophes like "can't" and skip over all punctuation.
Edit:
A comment has raised the edge case of parsing a quoted word such as 'this' as this.
Here's the solution for that - you have to first remove wrapping quotes:
String[] words = input.replaceAll("(^|\\s)'([\\w']+)'(\\s|$)", "$1$2$3").split("[^\\w']+");
Here's some test code with edge and corner cases:
public static void main(String[] args) throws Exception {
String input = "'I', ie \"me\", can't extract 'can't' or 'can't'";
String[] words = input.replaceAll("(^|[^\\w'])'([\\w']+)'([^\\w']|$)", "$1$2$3").split("[^\\w']+");
System.out.println(Arrays.toString(words));
}
Output:
[I, ie, me, can't, extract, can't, or, can't]
Also is it possible to separate the Strings?
Yes, You can split string by using this for white spaces.
String[] strSplit;
String str = "This is test for split";
strSplit = str.split("[\\s,;!?\"]+");
See String API
Moreover you can also read a text file word by word.
Scanner scan = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("Your File Path")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(scan.hasNext()){
System.out.println( scan.next() );
}
See Scanner API