using java Help me with this question : so if I want to ask the user to guess ho
ID: 3581421 • Letter: U
Question
using java
Help me with this question :
so if I want to ask the user to guess how many words in a file called (texts.txt)
ask the user to have 5 guess between those number ( 20 - 60) words
if they guess right, a message show " that's right! "
if its wrong a message shows " try again" until the 5 guess.
after that it would use the code below to give " the right number of words in the file is "
public static void isPalindrome(String fileName){
int palindrome_cout=0,total_cout=0;
File filename = new File("words.txt");
try {
Scanner input = new Scanner(filename);
while (input.hasNext()) {
total_cout++;
String original, reverse = "";
original = input.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- ){
reverse = reverse + original.charAt(i);
}
if (original.equals(reverse)){
palindrome_cout++;
}
}
System.out.println("There are "+palindrome_cout+" out of "+ total_cout +" words in file words.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any isue.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordGuess {
public static int getTotalWordsCount(String fileName){
int total_cout = 0;
File filename = new File(fileName);
try {
Scanner input = new Scanner(filename);
while (input.hasNext()) {
total_cout++;
input.next();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return total_cout;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter input file name: ");
String fileName= sc.next();
int totalWords = getTotalWordsCount(fileName);
System.out.println(totalWords+" ");
int userGuess;
System.out.println("You have to guess words count in total of 5 guess");
int i = 5;
while(i > 0){
i--;
System.out.println("Enter your guess: ");
userGuess = sc.nextInt();
if(userGuess == totalWords){
System.out.println("You Gussed!!!");
break;
}else{
System.out.println("Incorrect. You have left with "+i+" guess change");
}
}
}
}
/*
Sample run:
Enter input file name: input.txt
22
You have to guess words count in total of 5 guess
Enter your guess:
5
Incorrect. You have left with 4 guess change
Enter your guess:
12
Incorrect. You have left with 3 guess change
Enter your guess:
20
Incorrect. You have left with 2 guess change
Enter your guess:
22
You Gussed!!!
*/
########### input.txt ###########
1967 Green Bay Packers
1968 Green Bay Packers
1969 New York Jets
1970 Kansas City Chiefs
1971 Baltimore Colts
1972 Dallas Cowboys
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.