read random word from CSV file java (wordle project) - java

how do I get this to read from a csv file and choose a random word from a list I have. I can get it to print the first few words but I want it to just choose one randomly. As you can tell Im very new to java.
String csvFile = "src/data/Book1.csv";
WordleWord[] arrays = new WordleWord[6];
FileReader fileReader = new FileReader(csvFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String nextLine = bufferedReader.readLine();
String[] strings1 = nextLine.split(",");
String randomWord = strings1[0];
String randomWord1 = strings1[0];
for (int i = 0; i < arrays.length; i++) {
nextLine = bufferedReader.readLine();
if (nextLine != null) {
String[] strings = nextLine.split(","); //split the string when commas occur
String word = strings[0];
arrays[i] = new WordleWord(word);
arrays[i] = new WordleWord(word);
String chosenRandomWord = Random(arrays[i]);
System.out.println(word);

Related

Split string in Txt files

Lets assume I have a txt file called "Keys.txt":
Keys.txt:
Test 1
Test1 2
Test3 3
I want to split the strings into an array and I dont know how to do it
I want that the result will be
in array like this:
Test
1
Test1
2
Test2
3
I have this started code:
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
br.close();
System.out.println(str);
You could store all the lines on a single string, separated by spaces, and then split it into your desired array.
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str="", l="";
while((l=br.readLine())!=null) { //read lines until EOF
str += " " + l;
}
br.close();
System.out.println(str); // str would be like " Text 1 Text 2 Text 3"
String[] array = str.trim().split(" "); //splits by whitespace, omiting
// the first one (trimming it) to not have an empty string member
You can follow these steps :
read the current line in a String, then split the String on the whitespace (one or more) and you have an array which you can store elements in a List.
repeat the operation for each line.
convert the List to an array(List.toArray()).
For example :
List<String> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("Keys.txt"))) {
String str;
while ((str = br.readLine()) != null) {
String[] token = str.split("\\s+");
list.add(token[0]);
list.add(token[1]);
}
}
String[] array = list.toArray(new String[list.size()]);
Note that by using Java 8 streams and the java.nio API (available from Java 7) you could be more concise :
String[] array = Files.lines(Paths.get("Keys.txt"))
.flatMap(s -> Arrays.stream(s.split("\\s+"))
.collect(Collectors.toList())
.stream())
.toArray(s -> new String[s]);
String str = "Test 1 Test1 2 Test2 3";
String[] splited = str.split("\\s+");
You can use String.split() method (in your case it's str.split("\\s+");).
It will split input string on one or more whitespace characters. As Java API documentation states here:
\s - A whitespace character: [ \t\n\x0B\f\r]
X+ - X, one or more times.
FileReader fr;
String temp = null;
List<String> wordsList = new ArrayList<>();
try {
fr = new FileReader("D://Keys.txt");
BufferedReader br = new BufferedReader(fr);
while ((temp = br.readLine()) != null) {
String[] words = temp.split("\\s+");
for (int i = 0; i < words.length; i++) {
wordsList.add(words[i]);
System.out.println(words[i]);
}
}
String[] words = wordsList.toArray(new String[wordsList.size()]);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
try this out

Converting ArrayLists in Java

I have the following code which counts and displays the number of times each word occurs in the whole text document.
try {
List<String> list = new ArrayList<String>();
int totalWords = 0;
int uniqueWords = 0;
File fr = new File("filename.txt");
Scanner sc = new Scanner(fr);
while (sc.hasNext()) {
String words = sc.next();
String[] space = words.split(" ");
for (int i = 0; i < space.length; i++) {
list.add(space[i]);
}
totalWords++;
}
System.out.println("Words with their frequency..");
Set<String> uniqueSet = new HashSet<String>(list);
for (String word : uniqueSet) {
System.out.println(word + ": " + Collections.frequency(list,word));
}
} catch (Exception e) {
System.out.println("File not found");
}
Is it possible to modify this code to make it so it only counts each occurrence once per line rather than in the entire document?
One can read the contents per line and then apply logic per line to count the words:
File fr = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
// Read the line in the file
String line = null;
while ((line = br.readLine()) != null) {
//Code to count the occurrences of the words
}
Yes. The Set data structure is very similar to the ArrayList, but with the key difference of having no duplicates.
So, just use a set instead.
In your while loop:
while (sc.hasNext()) {
String words = sc.next();
String[] space = words.split(" ");
//convert space arraylist -> set
Set<String> set = new HashSet<String>(Arrays.asList(space));
for (int i = 0; i < set.length; i++) {
list.add(set[i]);
}
totalWords++;
}
Rest of the code should remain the same.

Randomly read text from specific column in a file using Java

I would like to randomly select single name from column1 between Robert,Shawn,John.
Example The File has following names
Robert,Brian
Shawn,Bay
John,Paul
Any Help would be highly appreciated
FileInputStream objfile = new FileInputStream(System.getProperty("user.dir")+path);
in = new BufferedReader(new InputStreamReader(objfile ));
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
String eachRecord[]=line.trim().split(",");
Random rand = new Random();
//trying to randomly select text from specific row in a property file
sendKeys(firstName,rand.nextInt((eachRecord[0]));
line = in.readLine();
}
}
This gets a random name from column 1 into the variable randomName:
final int column = 1;
final String path = "file.ext";
Random rand = new Random();
List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
String randomName = lines.get(rand.nextInt(lines.size())).split(",")[column - 1];
FileReader fr = new FileReader(path_of_your_file);
BufferedReader br = new BufferedReader(fr);
String sCurrentLine;
ArrayList<String> nameList=new ArrayList<String>(); //keep each first column entry inside this list.
while ((sCurrentLine = br.readLine()) != null) {
StringTokenizer st=new StringTokenizer(sCurrentLine, ",");
String name=st.nextToken();
nameList.add(name);
}
System.out.println(nameList.get((int)(Math.random()*nameList.size())));
//close file resources at finally block.

How to read integers from a file that are separated with semi colon?

So in my codes, I am trying to read a file that is like:
100
22
123;22
123 342;432
but when it outputs it would include the ";" ( ex. 100,22,123;22,123,342;432} ).
I am trying to make the file into an array ( ex. {100,22,123,22,123...} ).
Is there a way to read the file, but ignore the semicolons?
Thanks!
public static void main(String args [])
{
String[] inFile = readFiles("ElevatorConfig.txt");
for ( int i = 0; i <inFile.length; i = i + 1)
{
System.out.println(inFile[i]);
}
System.out.println(Arrays.toString(inFile));
}
public static String[] readFiles(String file)
{
int ctr = 0;
try{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()){
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
words[i] = s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;
}
}
public static String[] readFiles(String file)
{
int ctr = 0;
try{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()){
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
words[i] = s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;
}
}
Replace this by
public static String[] readFiles(String file) {
List<String> retList = new ArrayList<String>();
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
String temp = s2.next();
String[] tempArr = se.split(";");
for(int k=0;k<tempArr.length;k++) {
retList.add(tempArr[k]);
}
}
return (String[]) retList.toArray();
}
Use regex. Read the entire file into a String (read each token as a String and append a blank space after each token in the String) and then split it at blank spaces and semi colons.
String x <--- contains all contents of the file
String[] words = x.split("[\\s\\;]+");
The contents of words[] are:
"100", "22", "123", "22", "123", "342", "432"
Remember to parse them to int before using as numbers.
Simple way to use BufferedReader Read line by line then split by ;
public static String[] readFiles(String file)
{
BufferedReader br = new BufferedReader(new FileReader(file)))
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String allfilestring = sb.toString();
String[] array = allfilestring.split(";");
return array;
}
You can use split() to split the string into array according to your requirement using regex.
String s; // string you have read from the file
String[] s1 = s.split(" |;"); // s1 contains the strings separated by space and ";"
Hope it helps
Keep the code for counting the size of the array.
I would just change the way you input your values.
for (int i = 0; i < ctr; i++) {
words[i] = "" + s1.nextInt();
}
Another option is to replace all non digit characters in your complete file string with a space. That way any non number character is ignored.
BufferedReader br = new BufferedReader(new FileReader(file)))
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String str = sb.toString();
str = str.replaceAll("\\D+"," ");
Now you have a string with numbers separated by spaces, we can tokenize them into number strings.
String[] final = str.split("\\s+");
then convert to int datatypes.

How to split a line of a txt file into different variables? [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 7 years ago.
I have a txt that is something like this:
Jhon 113
Paul 024
David 094
Peter 085
and from each line i want to have 2 variables one of the type string for the name and one int for the number
I wrote this code and what it does its take what ever a line says and ands it to an array called names but i will like to khow how to split the line into two different variables.
import java.io.*;
public class Read {
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("test.txt");
BufferedReader reader = new BufferedReader(file);
String names[] = new String[10];
for(int i = 0; i<names.length; i++){
String line = reader.readLine();
if(line != null){
names[i] = line;
}
}
}
}
You should use split() :
String names[] = new String[10];
int numbr[] = new int[10];
for(int i = 0; i<names.length; i++){
String line = reader.readLine();
if(line != null){
names[i] = line.split(" ")[0];
numbr[i] = Integer.parseInt(line.split(" ")[1]);
}
}
Ref : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
It is as intuitive as using the word split in your question. String class has a split function to split strings using a given parameter.
import java.io.*;
public class Read {
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("test.txt");
BufferedReader reader = new BufferedReader(file);
String names[] = new String[10];
int num[] = new int[10];
String lineSplit[] = new String[2];
for(int i = 0; i<names.length; i++){
String line = reader.readLine();
if(line != null){
//splits line using space as the delimeter
lineSplit = line.split("\\s+");
names[i] = lineSplit[0];
num[i] = Integer.parseInt(lineSplit[1]);
}
}
}
}

Categories

Resources