My school project requires me to modify my last assignment (code below) to pull a random phrase from a list of at least 10 for the user to guess. I drawing a blank on this. Any help would be appreciated. I understand I have to add a class that would import the text file or list, then I would need to modify a loop in order for it to randomly select?
import java.util.Scanner; // Allows the user to read different value types
public class SecretPhrase {
String phrase; //
Scanner scan = new Scanner(System.in);
SecretPhrase(String phrase){
this.phrase = phrase.toLowerCase();
}
public static void main(String args[]){
SecretPhrase start = new SecretPhrase("Java is Great"); // The phrase the user will have identify
start.go(); // Starts Program
}
void go(){
String guess;
String word="";
String[] words = new String[phrase.length()]; // array to store all charachters
ArrayList<String> lettersGuessed = new ArrayList();
for(int i=0;i<phrase.length();i++){
if(phrase.charAt(i)== ' '){words[i] = " ";}
else{words[i] = "*";} // Array that uses * to hide actual letters
}
int Gcount =0; // Records the count
while(!word.equals(phrase)){ // continues the loop
word = "";
int Lcount = 0;
System.out.print("Guess a letter> ");
guess = scan.next();
for(int i=0;i<phrase.length();i++){ // Accounts for any attempts by user to use more than one charachter at a time.
if((guess.charAt(0)+"").equals(phrase.charAt(i)+"")&&(lettersGuessed.indexOf(guess.charAt(0)+"")==-1)){
words[i] = ( guess.charAt(0))+ "";
Lcount++;
}
}
lettersGuessed.add(guess.charAt(0)+""); // Reveals the letter in phrase
System.out.println("You found " + Lcount +" letters"); // Prints out the total number of times the charachter was in the phrase
for(int i=0;i<words.length;i++){
word=word+words[i];
}
System.out.println(word);
Gcount ++;
}
System.out.println("Good Job! It took you " + Gcount + " guesses!" ); // Prints out result with total count
}
}
In the existing code, you are creating a SecretPhrase object with the phrase to guess:
public static void main(String args[]){
SecretPhrase start = new SecretPhrase("Java is Great");
start.go(); // Starts Program
}
You should replace it with a List (either ArrayList or LinkedList would be fine) and populate it with your data (given by either file, user input or hard-coded):
ArrayList<SecretPhrase> phrases = new ArrayList<SecretPhrase>();
//reading from file:
File file = new File("myPhrases.txt");
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String phrase = null;
while ((phrase = br.readLine()) != null) {
phrases.add(new SecretPhrase(phrase));
}
Now either use Random on phrases.size() and execute go on it, or if you're looking for it to be a series of phrases, you can create a permutation and loop over them. I'm not sure what your requirements here are.
Related
I'm write a code that pulls a word from a file and guesses it. For instance the word would be "apple".
The user will see: *****
If they input 'p' as a guess they see: *pp**
So far it's working if I manually the word apple in a variable called secretPhrase, however I'm not sure how to have the program pull the word from a text file and store it into secretPhrase for the user to guess.
public static void main(String args[]) {
String secretPhrase = "apple";
String guesses = " ";
Scanner keyboard = new Scanner(System.in);
boolean notDone = true;
Scanner word = new Scanner(System.in);
System.out.print("Enter a word: ");
while(true) {
notDone = false;
for(char secretLetter : secretPhrase.toCharArray()) {
if(guesses.indexOf(secretLetter) == -1) {
System.out.print('*');
notDone = true;
} else {
System.out.print(secretLetter);
}
}
if(!notDone) {
break;
}
System.out.print("\nEnter your letter:");
String letter = keyboard.next();
guesses += letter;
}
System.out.println("Congrats");
}
You have several options. One is to do the following. It is not complete and doesn't check on border cases. But you can figure that out. It presumes the file contains one word per line.
try {
RandomAccessFile raf = new RandomAccessFile(
new File("wordfile.txt"), "r");
Random r = new Random();
// ensure the length is an int
int len = (int)(raf.length()&0x7FFFFFFF);
// randomly select a location
long loc = r.nextInt(len);
// go to that file location
raf.seek(loc);
// find start of next line
byte c = raf.readByte();
while((char)c != '\n') {
c = raf.readByte();
}
// read the line
String line = raf.readLine();
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}
A much easier solution for perhaps a smaller set of words is to just read them into a List<String> and the do a Collections.shuffle() to randomize them. Then just use them in the shuffled order.
I have done this code, it prints correctly the total number of lines but for the total number of words it always prints total of 1 word. Can someone help me please, Thanks!
import java.util.*;
public class LineAndWordCounter{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String line = scan.next();
linesCounter(scan);
wordsCounter(new Scanner(line) );
}
}
public static void linesCounter(Scanner linesInput){
int lines = 0;
while(linesInput.hasNextLine()){
lines++;
linesInput.nextLine();
}
System.out.println("lines: "+lines);
}
public static void wordsCounter(Scanner wordInput){
int words = 0;
while(wordInput.hasNext()){
words++;
wordInput.next();
}
System.out.println("Words: "+words);
}
}
This looks rather complicated to me.
You can just save each line in an ArrayList and accumulate the words in a variable.
Something like this:
List<String> arrayList = new ArrayList<>();
int words = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String line = scan.nextLine();
arrayList.add(line);
words += line.split(" ").length;
System.out.println("lines: " + arrayList.size());
System.out.println("words: " + words);
}
scan.close();
You should also not forget to call the close() method o the Scanner to avoid a resource leak
scan.next()
returns the next "word".
If you create a new Scanner out of that one word, it will only ever see one word.
This will happen with
String line = scan.next();
wordsCounter(new Scanner(line) );
Disclaimer, I've been at java for about a month. I'm completely lost on this. I'm trying to have a user input a phrase and if any strings in that phrase is found on the array, it returns the corresponding string in one line. if the string isn't found, it would just skip it.
so if someone typed in "dog eat my fish"
and the array holds:
dog perro
eat munched
fish yellow trout
it would return:
perro munched yellow trout
I haven't written the code to print out what I've got yet, but I know this code isn't working.
any help would be greatly appreciated.
import java.io.*;
import java.util.*;
public class ArrayTest2 {
public static void main(String[] args)
throws java.io.IOException {
Scanner input = new Scanner(System.in);
String userString = " ";
userString = englishString();
String[][] wordList = new String[10][2];
loadEnglishString(wordList);
}
public static String englishString() {
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a phrase to translate: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadEnglishString(String[][] wordList)
throws java.io.IOException {
String filName = " ";
filName = ("/home/chrism/ArrayTest2.txt");
Scanner input = new Scanner(new File(filName));
while(input.hasNextLine()) {
String line = input.nextLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
boolean stop = false;
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++)
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
break;
}
}
}
input.close();
}
}
You'll definitely want to change your for loop. Brackets are your friend.
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++) {
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
}
}
The way you had it, both increments were registering as dead code because your second break would always called the first time through the loop, and your else was registering as coupled with the first if(stop).
Edit: don't know for sure about how the else would couple, but the break is definitely called after the first run through.
//package com.myjava.stokenizerr;
import java.util.StringTokenizer;
public class MyStringTokenizer {
public static void main(String a[]){
/* your code for user input string */
/* assume input as dog eat my fish */
String input = "dog eat my fish";
String msg = "dog perro eat munched fish yellow trout";
StringTokenizer st1 = new StringTokenizer(msg," ");
StringTokenizer st2 = new StringTokenizer(input," ");
while(st1.hasMoreTokens()){
System.out.println(st1.nextToken()); // Store this one(first) string array
}
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken()); // Store in another(second) array
}
/* Now Compare both the arrays */
/* If the strings are equal then remove string from second array */\
/* If equal just skip it */
}
}
See the above code st1.nextToken() and st2.Tokens() will give you the values
For comparing take two loops
for(i==0;i<array1length();i++) {
for(j==0;j<array2length();j++) {
// Your code for comparsion
}
}
This program should input a dataset of names followed by the name "END". The program should print out the list of names in the dataset in reverse order from which they were entered. What I have works, but if I entered "Bob Joe Sally Sue" it prints "euS yllaS eoJ boB" insead of "Sue Sally Joe Bob". Help!?
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner kb = new Scanner(System.in);
System.out.println("Enter a list of names, followed by END:");
original = kb.nextLine();
int length = original.length();
while (!original.equalsIgnoreCase("END") ) {
for ( int i = length - 1; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
original = kb.next();
}
System.out.println("Reverse of entered string is: "+reverse);
}
}
I think that you need to use this simple algorithm. Actually you're not using the proper approach.
Take the whole string which contains all the names separated by spaces;
Split it using as a delimiter the space (use the method split)
After the split operation you will get back an array. Loop through it from the end (index:array.length-1) to the starter element (1) and save those elements in another string
public String reverseLine(String currLine) {
String[] splittedLine = currLine.split(" ");
StringBuilder builder = new StringBuilder("");
for(int i = splittedLine.length-1; i >= 1; i--) {
builder.append(splittedLine[i]).append(" ");
}
return builder.toString();
}
I've supposed that each lines contains all the names separated by spaces and at the end there is a string which is "END"
A quick way, storing the result in the StringBuilder:
StringBuilber reverse = new StringBuilder();
while (!original.equalsIgnoreCase("END")) {
reverse.append(new StringBuilder(original).reverse()).append(" ");
original = kb.next();
}
System.out.println("Reverse: " + reverse.reverse().toString());
Using the approach suggested in the comments above is very simple, and would look something like:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
while (sc.hasNext())
{
String name = sc.next();
if (name.equals("END"))
{
break;
}
names.add(name);
}
Collections.reverse(names);
for (String name: names)
{
System.out.println(name);
}
System.out.println("END");
}
Let the Scanner extract the tokens for you, no need to do it yourself.
import java.io.File;
import java.util.Scanner;
public class scoresedit {
public static void main(String[] args) throws Exception{
System.out.println("Reads in a file at the beginning of a loop, displays these top 3 scores by name and their respective score." +
"\nEnter a new name and score following a prompt. " +
"\nIf the new name and score exceeds one of the top three scores," +
"\nplaces the new name in the top three, moving all lower scores down, dropping the lowest score." +
"\nSaves the results in the file top3Scores.txt." +
"\nStops the loop when exit is entered for a name.");
File r = new File ("top3Scores.txt");
System.out.println(r);
String str = readSource (r);
System.out.println(str);
String[] strArray = new String[] {str};
Scanner in = new Scanner(System.in);
System.out.print("Enter a new name and score or 'exit' to quit:");
String nameAndScore = in.nextLine();
String[] nameAndScoreArray = new String[] {nameAndScore};
String nameAndScoreArray1[] = nameAndScore.split(" ");
while (nameAndScore != "exit") {
if (nameAndScoreArray[1] > strArray[1]) }
}
private static String readSource(File r) throws Exception{
Scanner in;
in = new Scanner (r);
String str = "";
while (in.hasNext())
str += in.nextLine() +"\n";
in.close();
return str;
}
}
I keep getting the error "The operator > is undefined for the argument type(s) java.lang.String, java.lang.String" when I try to compare the two arrays and I don't know how to fix it. The code isn't finished; obviously I'm adding more under the if statement but I want to resolve this first.
You are trying to compare nameAndScoreArray[1] and strArray[1] which are strings, I assume they contain the scores of two teams and the one with the highest score wins, so you want to use Integer.parseInt(String string) in order to see which one has the highest score:
if (Integer.parseInt(nameAndScoreArray[1]) > Integer.parseInt(strArray[1]))
You can not compare String with the operators <, >, instead you need to use compareTo.