Replace letters with * - java

Making a hangman style of game
I have the random word now. How do I replace the letters of the word with an asterix * so that when the program starts the word is shown as *.
I assume that when someone inputs a letter for the hangman game you get the index of that character in the word and then replace the corresponding *.
public class JavaApplication10 {
public static String[] wordArray = new String[1];
public static String file_dir = "Animals.txt";
public static String selectedWord = "";
public static char[] wordCharacter = new char[1];
Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
wordArray = get_word(file_dir);
selectedWord = select_word(wordArray);
System.out.println(selectedWord);
}
public static String[] get_word(String file_dir) throws IOException {
FileReader fileReader = new FileReader(file_dir);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static String select_word(String[] wordArray) {
Random rand = new Random();
int lines = Math.abs(rand.nextInt(wordArray.length)- 1);
return wordArray[lines];
}
}

If you know how many lines are there you could use Random method in java with a specific range to pick out a line at random.
Then you could read the file line-by-line till you reach that random line and print it.
// Open the file
FileInputStream fstream = new FileInputStream("testfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int counter=0;
//While-loop -> Read File Line By Line till the end of file
//And will also terminate when the required line is printed
while ((strLine = br.readLine()) != null && counter!=randomValue){
counter++;
//You need to set randomValue using the Random method as suggested
if(counter==randomValue)
// Print the content on the console
System.out.println (strLine+"\n");
}
//Close the input stream
br.close();

Assuming Java 8:
// Loading ...
Random R = new Random(System.currentTimeMillis());
List<String> animals = Files.readAllLines(Paths.get(path));
// ...
// When using
String randomAnimal = animals.get(R.nextInt(animals.size()));

Answer of your first question :
First you have to get the total number of lines
Then you have to generate a random number between 1 and that total number.
Finally, get the required word
try {
InputStream is = new BufferedInputStream(new FileInputStream("D:\\test.txt"));
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
int noOfLines = count+1;
System.out.println(noOfLines);
Random random = new Random();
int randomInt = random.nextInt(noOfLines);
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader bufferedReader =
new BufferedReader(fr);
String line = null;
int counter =1;
while((line = bufferedReader.readLine()) != null) {
if(counter == randomInt)
{
System.out.println(line); // This the word you want
}
counter++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
//is.close();
}

Related

How to read float values from a file and initialize array?

i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
}
You need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]

Array CompareFind Equals words only using array not array list

Have a two text file with words list. need save both file in two array.I know how to do it using list and set.. but here I want know how to do it using only arrays.Only array and no predefined functions such as Arrays.sort() or Collections.sort() can be used
no list no ArrayList or no class from Java Collection Frameworks can be used.
public class Main {
public static Set<String> setlist1= new HashSet<>();
public static String[] arrayList=new String[file1count];
public static String[] array2=new String[file2count];
public static int file1count=0;
public static int file2count=0;
public static void main(String[] args) {
try {
/*read the files*/
Scanner rf= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt")));
Scanner rf2= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt")));
String line;
String line2;
while(rf.hasNext()){
line=rf.nextLine();
file1count++;
}
while(rf2.hasNext()){
line2=rf2.nextLine();
file2count++;
}
rf.close();
rf2.close();
}catch(IOException e){
System.out.println(e);
}
}
}
The problem with using arrays is that you don't know in advance what length to allocate.
You basically have two options:
read each file twice
allocate an array of some initial length, and reallocate is as needed (that's what an ArrayList does.)
Second option: let's have a method readFile that reads all the lines from a file and returns an array:
public static String[] readFile(String fileName) throws IOException {
try (Reader reader = new FileReader(fileName);
BufferedReader in = new BufferedReader(reader)) {
String[] lines = new String[10]; // start with 10
int count = 0;
String line;
while ((line = in.readLine()) != null) {
if (count >= lines.length) {
lines = reallocate(lines, count, 2*lines.length);
}
lines[count++] = line;
}
if (count < lines.length) {
// reallocate to the final length;
lines = reallocate(lines, count, count);
}
return lines;
}
}
private static String[] reallocate(String[] lines, int count,
int newLength) {
String[] newArray = new String[newLength];
for (int i = 0; i < count; ++i) {
newArray[i] = lines[i];
}
lines = newArray;
return lines;
}
BufferedReader reader1 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt"));
BufferedReader reader2 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt"));
String line1 = reader1.readLine();
String[] array1 = new String[10000000];
String[] array2 = new String[10000000];
String line2 = reader2.readLine();
boolean areEqual = true;
int lineNum = 1;
while (line1 != null || line2 != null) {
if (line1 == null || line2 == null) {
areEqual = false;
break;
} else if (!line1.equalsIgnoreCase(line2)) {
areEqual = false;
break;
}
if (line1 != null) {
array1[lineNum] = line1;
}
if (line1 != null) {
array2[lineNum] = line2;
}
line1 = reader1.readLine();
line2 = reader2.readLine();
lineNum++;
}
if (areEqual) {
System.out.println("Same content.");
} else {
System.out.println("different content");
}
reader1.close();
reader2.close();
You can simply try above code.
Here I had used only WHILE loop, BufferedReader and FileReader.

combine two methods in Java together in this Java code

I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!

How do you store each value separately using comma then they store into separate array?

A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.

Find a specific line of a text file (not by line_number) and store it as a new String

I am trying to read a text file in java using FileReader and BufferedReader classes. Following an online tutorial I made two classes, one called ReadFile and one FileData.
Then I tried to extract a small part of the text file (i.e. between lines "ENTITIES" and "ENDSEC"). Finally l would like to tell the program to find a specific line between the above-mentioned and store it as an Xvalue, which I could use later.
I am really struggling to figure out how to do the last part...any help would be very much apprciated!
//FileData Class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "C:/Point.txt";
try {
ReadFile file = new ReadFile (file_name);
String[] aryLines = file.OpenFile();
int i;
for ( i=0; i < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch (IOException e) {
System.out.println(e.getMessage() );
}
}
}
// ReadFile Class
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.lang.String;
public class ReadFile {
private String path;
public ReadFile (String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader (path);
BufferedReader textReader = new BufferedReader (fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
String nextline = "";
int i;
// String Xvalue;
for (i=0; i < numberOfLines; i++) {
String oneline = textReader.readLine();
int j = 0;
if (oneline.equals("ENTITIES")) {
nextline = oneline;
System.out.println(oneline);
while (!nextline.equals("ENDSEC")) {
nextline = textReader.readLine();
textData[j] = nextline;
// xvalue = ..........
j = j + 1;
i = i+1;
}
}
//textData[i] = textReader.readLine();
}
textReader.close( );
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader (path);
BufferedReader bf = new BufferedReader (file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine()) != null ) {
numberOfLines ++;
}
bf.close ();
return numberOfLines;
}
}
I don't know what line you are specifically looking for but here are a few methods you might want to use to do such operation:
private static String START_LINE = "ENTITIES";
private static String END_LINE = "ENDSEC";
public static List<String> getSpecificLines(Srting filename) throws IOException{
List<String> specificLines = new LinkedList<String>();
Scanner sc = null;
try {
boolean foundStartLine = false;
boolean foundEndLine = false;
sc = new Scanner(new BufferedReader(new FileReader(filename)));
while (!foundEndLine && sc.hasNext()) {
String line = sc.nextLine();
foundStartLine = foundStartLine || line.equals(START_LINE);
foundEndLine = foundEndLine || line.equals(END_LINE);
if(foundStartLine && !foundEndLine){
specificLines.add(line);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return specificLines;
}
public static String getSpecificLine(List<String> specificLines){
for(String line : specificLines){
if(isSpecific(line)){
return line;
}
}
return null;
}
public static boolean isSpecific(String line){
// What makes the String special??
}
When I get it right you want to store every line between ENTITIES and ENDSEC?
If yes you could simply define a StringBuffer and append everything which is in between these to keywords.
// This could you would put outside the while loop
StringBuffer xValues = new StringBuffer();
// This would be in the while loop and you append all the lines in the buffer
xValues.append(nextline);
If you want to store more specific data in between these to keywords then you probably need to work with Regular Expressions and get out the data you need and put it into a designed DataStructure (A class you've defined by our own).
And btw. I think you could read the file much easier with the following code:
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
...
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
Then you don't have to read first how many lines the file has. You just start reading till the end :).
EDIT:
I still don't know if I understand that right. So if ENTITIES POINT 10 1333.888 20 333.5555 ENDSEC is one line then you could work with the split(" ") Method.
Let me explain with an example:
String line = "";
String[] parts = line.split(" ");
float xValue = parts[2]; // would store 10
float yValue = parts[3]; // would store 1333.888
float zValue = parts[4]; // would store 20
float ... = parts[5]; // would store 333.5555
EDIT2:
Or is every point (x, y, ..) on another line?!
So the file content is like that:
ENTITIES POINT
10
1333.888 // <-- you want this one as xValue
20
333.5555 // <-- and this one as yvalue?
ENDSEC
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
// read next line
line = reader.readLine();
if(line.equals("10") {
// read next line to get the value
line = reader.readLine(); // read next line to get the value
float xValue = Float.parseFloat(line);
}
line = reader.readLine();
if(line.equals("20") {
// read next line to get the value
line = reader.readLine();
float yValue = Float.parseFloaT(line);
}
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
If you have several ENTITIES in the file you need to create a class which stores the xValue, yValue or you could use the Point class. Then you would create an ArrayList of these Points and just append them..

Categories