Suggestions with Strings from File - java

I am trying to read from a external file. I have successfully read from the file but now I have a little problem. The file contains around 88 verbs. The verbs are written in the file like this:
be was been
beat beat beaten
become became become
and so on...
What I need help with now is that I want a quiz like programe where only two random strings from the verb will come up and the user have to fill inn the one which is missing. Instead of the one missing, I want this("------"). My english is not so good so I hope you understand what I mean.
System.out.println("Welcome to the programe which will test you in english verbs!");
System.out.println("You can choose to be tested in up to 88.");
System.out.println("In the end of the programe you will get a percentage of total right answers.");
Scanner in = new Scanner(System.in);
System.out.println("Do you want to try??yes/no");
String a = in.nextLine();
if (a.equals("yes")) {
System.out.println("Please enter the name of the file you want to choose: ");
} else {
System.out.println("Programe is ended!");
}
String b = in.nextLine();
while(!b.equals("verb.txt")){
System.out.println("You entered wrong name, please try again!");
b = in.nextLine();
}
System.out.println("How many verbs do you want to be tested in?: ");
int totalVerb = in.nextInt();
in.nextLine();
String filename = "verb.txt";
File textFile = new File(filename);
Scanner input = new Scanner(textFile);
for (int i = 1; i <= totalVerb; i++){
String line = input.nextLine();
System.out.println(line);
System.out.println("Please fill inn the missing verb: ");
in.next();
}
System.out.println("Please enter your name: ");
in.next();

You can do something like this
import java.util.Scanner;
import java.io.*;
public class GuessVerb {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = in.nextLine();
File file = new File(fileName);
Scanner input = new Scanner(file);
String guess = null;
int correctCount = 0;
while(input.hasNextLine()) {
String line = input.nextLine(); // get the line
String[] tokens = line.split("\\s+"); // split it into 3 word
int randNum = (int)(Math.random() * 3); // get a random number 0, 1, 2
String newLine = null; // new line
int wordIndex = 0;
switch(randNum){ // case for random number
case 0: newLine = "------ " + tokens[1] + " " + tokens[2];
wordIndex = 0; break;
case 1: newLine = tokens[0] + " ------ " + tokens[2];
wordIndex = 1; break;
case 2: newLine = tokens[0] + " " + tokens[1] + " -------";
wordIndex = 2; break;
}
System.out.println(newLine);
System.out.println("Please fill inn the missing verb: ");
guess = in.nextLine();
if (guess.equals(tokens[wordIndex])){
correctCount++;
}
}
System.out.println("You got " + correctCount + " right");
}
}
Above is complete running program.

Related

Print to console in JAVA

I have a simple question. My program asks the user to type a name, range, and length to generate random numbers. The result will be printed into a file from the console. I want to know is it possible to print to the console that the file has been printed when it's done.
Currently this is my set up to print to a file:
Scanner s = new Scanner(System.in);
System.out.println("-----------------------------------------------");
System.out.println("Choose a name to your file: ");
String fn = s.nextLine();
System.out.println("-----------------------------------------------");
System.out.println("Choose your range: ");
String rn = s.nextLine();
System.out.println("-----------------------------------------------");
System.out.println("Choose your length of array: ");
String ln = s.nextLine();
System.out.println("-----------------------------------------------");
int rangeToInt = Integer.parseInt(rn);
int lengthToInt = Integer.parseInt(ln);
File file = new File(fn +".txt");
PrintStream stream = new PrintStream(file);
//System.out.println("File Has been Printed");
System.setOut(stream);
int[] result = getRandomNumbersWithNoDuplicates(rangeToInt, lengthToInt);
for(int i = 0; i < result.length; i++) {
Arrays.sort(result);
System.out.println(result[i] + " ");
}
System.out.println("Current Time in Millieseconds = " + System.currentTimeMillis());
System.out.println("\nNumber of element in the array are: " + result.length + "\n");
}// end of main
```
Don't call System.setOut. When you do that, you can no longer print to the console. Instead of System.out.println to write to the file, just... stream.println to write to the file. Then you can use System.out to print to the console.

Why will this not only return the string if it is a palindrome?

Below is the code that I wrote in order to have a user input a few different strings, check if each is a palindrome, and only return the palindrome. Currently, all of the entered in strings will be returned. It seems that the IF statement if not working correctly. Any suggestions on how to have the correct strings returned?
import java.util.Scanner;
public class hh {
static void checkPalin () {
// creates a scanner
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";
// asks the user for the number of strings
System.out.print("Enter the number of strings: ");
StringBuilder sentence = new StringBuilder(userInput);
StringBuilder palindrome = new StringBuilder();
// stores the number of strings user will enters
int stringNumber = input.nextInt();
// prompts the user to enter in their sentences
System.out.println("Enter the strings:");
// this loop will go until the number of strings entered are entered
while(i <= stringNumber){
userInput = input.nextLine();
if(sentence.reverse().equals(sentence)){
palindrome.insert(0, " " + userInput);
}
i ++;
}
// if( sentence == sentence.reverse()){
System.out.println("The palindromes are: " + palindrome);
}
public static void main(String[] args) {
checkPalin();
}
}
You need to create the String from the StringBuilder using the toString method before calling equals:
if(new StringBuilder(userInput).reverse().toString().equals(userInput)) { ... }
When you declare
StringBuilder sentence = new StringBuilder(userInput);
The "sentence" variable will not change if userInput changes. You need to recreate the StringBuilder each time you need it.
Here is the fixed code :
static void checkPalin() {
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";
System.out.print("Enter the number of strings: ");
StringBuilder palindrome = new StringBuilder();
int stringNumber = input.nextInt();
System.out.println("Enter the strings:");
while (i <= stringNumber) {
userInput = input.nextLine();
String reversed = new StringBuilder(userInput).reverse().toString();
if (reversed.equals(userInput)) {
palindrome.insert(0, " " + userInput);
}
i++;
}
System.out.println("The palindromes are: " + palindrome);
}
You have to write something like
new StringBuilder(sentence.toString()).reverse().equals(sentence)
in your if

Arrays and Output in Java

So I am trying to write a program that automates making an Operations Order (or OPORD). It is pretty straight forward, but I am having some issues with my arrays, more specifically how to get them to display properly in the output.
Here is my code:
import java.util.*;
import java.util.Scanner;
public class opord {
public static void main(String[] args){
//Variables
int opord_type, phase_a = 0, n = 1, tasks = 0, phase_b = 0, phase_c = 0;
//Strings for paragraph 1
String area_interest = " ", area_ops = " ", enemy_forces = " ", weather = " ", terrain = " ", friendly_forces = " ", civil_consid = " ", attach_detach = " ";
//Strings for paragraph 2
String who = " ", what = " ", where = " ", when = " ", why = " ";
//Strings for paragraph 3
String commander_intent = " ", phases;
Scanner keyboard = new Scanner(System.in);
//Array Lists
ArrayList alist = new ArrayList();
ArrayList blist = new ArrayList();
ArrayList clist = new ArrayList();
//Page One
System.out.println("Welcome to Automated OPORD");
System.out.println("Please choose which type of OPORD you want: (1:Garrison, 2:Tactical)");
opord_type = keyboard.nextInt();
if(opord_type == 1){
//Page Two
System.out.println("Paragraph One: ");
System.out.println("Situation: ");
//Indent One
System.out.println("Enter area of interest: ");
area_interest = keyboard.next();
System.out.println("Enter area of operations: ");
area_ops = keyboard.next();
//Indent Two
System.out.println("Enter weather: ");
weather = keyboard.next();
System.out.println("Enter terrain: ");
terrain = keyboard.next();
//End Indent Two
System.out.println("Enter enemy forces: ");
enemy_forces = keyboard.next();
System.out.println("Enter friendly forces: ");
friendly_forces = keyboard.next();
System.out.println("Enter civil considerations: ");
civil_consid = keyboard.next();
System.out.println("Enter attachments and detachments: ");
attach_detach = keyboard.next();
//End Indent One
//Page Three
System.out.println("Paragraph Two: ");
System.out.println("Mission");
//Indent One
System.out.println("Enter who: ");
who = keyboard.next();
System.out.println("Enter what: ");
what = keyboard.next();
System.out.println("Enter where: ");
where = keyboard.next();
System.out.println("Enter when: ");
when = keyboard.next();
System.out.println("Enter why: ");
why = keyboard.next();
//End Intent One
//Page Four
System.out.println("Paragraph Three: ");
System.out.println("Execution: ");
//Indent One
System.out.println("Enter commander's intent: ");
commander_intent = keyboard.next();
System.out.println("Concept of Operations");
//Indent Two
System.out.println("Enter number of phases: ");
phase_a = keyboard.nextInt();
for (int ph=0; ph<phase_a; ph++) {
System.out.println ("Enter phase " + (ph+1));
alist.add (keyboard.next());
}//End Indent Two
System.out.println("Scheme of Movement and Maneuver");
//Indent Three
System.out.println("Enter number of phases: ");
phase_b = keyboard.nextInt();
for (int p=0; p<phase_b; p++) {
System.out.println ("Enter phase " + (p+1));
blist.add (keyboard.next());
}//End Indent Three
System.out.println("Task to Subordinate Units");
//Indent Four
System.out.println("Enter number of tasks: ");
tasks = keyboard.nextInt();
for (int h=0; h<phase_b; h++) {
System.out.println ("Enter task " + (h+1));
clist.add (keyboard.next());
}
}else if(opord_type == 2){
}
//Output for Garrison
System.out.println("Output for Garrison");
for (int ph=0; ph<phase_a; ph++){
System.out.println("Phase " + n++ + ": " + alist.get(ph));
}
for (int p=0; p<phase_b; p++){
System.out.println("Phase " + n++ + ": " + blist.get(p));
}
for (int h=0; h<phase_c; h++){
System.out.println("Phase " + n++ + ": " + clist.get(h));
}
//Output for Tactical
}
}
I need the output of the phases and the tasks to look like this:
Concept of Operations:
Phase One: Here is some text that the user input
Phase Two: Here is some text that the user input
Phase Three: Here is some text that the user input
Phase (whatever the number the user input): Here is some text that the user input
Scheme of Movement and Maneuver:
Phase One: Here is some text that the user input
Phase Two: Here is some text that the user input
Phase Three: Here is some text that the user input
Phase (whatever the number the user input): Here is some text that the user input
Task to Subordinate Units:
Task One: Here is some text that the user input
Task Two: Here is some text that the user input
Task Three: Here is some text that the user input
Task (whatever the number the user input): Here is some text that the user input
Tactical is mostly mirrored with some changes so don't worry about that, I just need to fix this code so that. I just have to get this code finished, any help would be wonderful!
Thank you!
If I'm understanding you correctly, this is a question about how to create line breaks in the console output of a Java application.
The Character for this is "\n". Put that into print command when you want to do a line break.
//Page Three
System.out.println("\nParagraph Two: ");
System.out.println("Mission");
etc...
Further more, looking at your expected output (I don't know if this is important) but if you want to user input to be next to the text strings, rather than below, use System.out.print (without the ln at the end)
.println will do a line break after finishing the regular print operation

Java - Scanner does not remove all of the desired objects

I am trying to make some kind of 'Evil Hangman game' (nifty Stanford CS exercises). The purpose of the game is to 'cheat' by removing as many possible word solutions as possible so the user cannot guess before the very end.
I have made a loop (below) which seems to remove many of the words possible words but for some reason it does not remove all of them. The input is a dictionary.txt file which contains about 120K words.
When I 'guess' the letter "a" it will take away roughly 60-70% of the words with "a" in them (estimate based on comparisons between the output with the first couple of words in the txt file)
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
I am aware that my code is a bit messy at this point, I am trying to improve everything about my programming so all feedback is greatly appreciated! I have the feeling that I am including stuff that does not have to be there and so on.
I will post the whole code below in case that helps:
import java.util.*;
import java.lang.*;
import java.io.*;
public class EvilHangman
{
public static void main(String[] args) throws IOException
{
// declaring variables
int wordLength;
int guessNumber;
// initiate the scanner
Scanner keyboard = new Scanner( System.in );
// introduction and prompting the user for word length
System.out.println("Welcome to Hangman. Let's play! ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
// prompt the user for number of guesses
System.out.println("How many guesses do you want to have? ");
guessNumber = keyboard.nextInt();
while(guessNumber < 0)
{
System.out.println("Number of guesses has to be a postive integer. ");
System.out.println("Please enter the desired number of guesses: ");
guessNumber = keyboard.nextInt();
}
// count the number of words with the specified length
/* int wordCount = 0;
String word = null;
while ( textScan.hasNext() )
{
word = textScan.next();
if (word.length() == wordLength)
{
wordCount++;
}
}
*/
// prompts the user whether he/she wants a running count of word length - using next() instead of nextLine() to clear buffer
/* System.out.println("Do you want a running total of number of words remaining? ");
String runningTotal = keyboard.next();
if (runningTotal.equalsIgnoreCase("yes"))
System.out.println("Words with that length: " + wordCount);
*/
// create a list (array) of all the words that matches the input length
String word = null;
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
System.out.println(wordList);
Finally figured out it had to do with the scanner. It had to be initiated inside the loop
for(int i = 1; i <= guessNumber; i++)
{
Scanner textScan2 = new Scanner(file1);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
//System.out.print(guess);
while ( textScan2.hasNext() )
{
String word1 = textScan2.next();
if (wordLength != word1.length() || (word1.contains(guess)))
{
wordList.remove(word1);
}
}
}

Exception in main thread java.util.NoSuchElementException

I'm working on this project to improve my skill in Java. My goal is to write a program that reads the line from a specified doc or text file (depending on which the user wants to open; int 2 or 1 respectively.) and then asks the user to input their document name (without the file extension), and then reads the first line in the document or text file. I want it to do this as many times as the user wants. But I keep getting NoSuchElementException while executing the code.
public class switches {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("How many files would you like to scan?");
System.out.println("Enter # of files to scan: ");
int countInput = input.nextInt();
input.close();
for (int count = 0; count < countInput;) {
System.out.println("Please enter a file name to scan. ");
System.out.println("1 for .txt, 2 for .doc");
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
switch (choice) {
default: {
do {
System.out.println("Please pick "
+ "either 1: txt or 2: doc");
choice = keyboard.nextInt();
} while (choice != 1 && choice != 2);
}
case 1: {
System.out.println("Txt file name:");
keyboard.nextLine();
String txtName = keyboard.nextLine();
File openTxtFile = new File("C:/Users/Hp/Documents/" + txtName
+ ".txt");
Scanner firstTxtLine = new Scanner(openTxtFile);
String printedTxtLine = firstTxtLine.nextLine();
firstTxtLine.close();
System.out.println("The first line " + "of your text file is: "
+ printedTxtLine);
keyboard.close();
count++;
break;
}
case 2: {
System.out.println("Doc file name:");
keyboard.nextLine();
String docName = keyboard.nextLine();
File openDocFile = new File("C:/Users/Hp/Documents/" + docName
+ ".doc");
Scanner firstLine = new Scanner(openDocFile);
String printedDocLine = firstLine.nextLine();
firstLine.close();
System.out.println("The first line"
+ " of your word document is: " + printedDocLine);
keyboard.close();
count++;
break;
}
}
}
}
}
If you remove the line input.close(); on line 14. This should solve your problem. According to the documentation, it will throw a NoSuchElementException - "if input is exhausted".

Categories