importing words from text - java

I apologize since I'm always asking n00b questions but I could really use the help. Anyways I'm trying to import words of only a certain length from the dictionary into the variable words which is a hash set. When I run my program and try to print my words aka the hashset of strings. I get nothing in the console and the program does not stop running. How can I fix this? P.S. Also I know part of the JOptionPane code got cut enough, but it's error free and you get the point. Thanks!
Alex
public void inputWords()
{
try
{
frame = new JFrame("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
input = new Scanner(new FileInputStream("dictionary.txt"));
wordLength = Integer.parseInt( JOptionPane.showInputDialog(null,
String importedWords = input.nextLine();
while(stillHasWords==true)
{
if(importedWords.length()==wordLength)
{
words.add(importedWords);
}
else
{
}
}
}
catch(FileNotFoundException f)
{
System.out.println("File does not exist.");
System.exit(0);
}
catch(NoSuchElementException q)
{
stillHasWords=false;
}
public static void main(String[] args)
{
EvilHangman j = new EvilHangman();
System.out.println(stillHasWords);
j.inputWords();
System.out.println(words + " ");
}
}

Regarding:
while(stillHasWords==true)
{
if(importedWords.length()==wordLength)
{
words.add(importedWords);
}
else
{
}
}
I'm not sure what words.add(importedWords) does, but most important to the problem you're experiencing,
Question: Where do you change stillHasWords inside of your loop?
Answer: You don't, and so the loop will never end.
I suggest that first you fix this while loop
As an aside, it's better to avoid using == true in a while loop and instead simply test the boolean:
while (stillHasWords) {
// add a word
// change stillHasWords to false if we've run out of words
}
Edit
You state:
Still has words changes in the catch(NoSuchElementException q)
There is no catch block posted inside of the while loop, and so I submit that still the stillHasWords value cannot change inside of the while loop based on code you've posted so far. If you have more pertinent code, then you'll of course want to show it, else we're reduced to guessing what might be wrong with code not shown. Best to post an SSCCE

Related

No such element exception working with a Scanner

I am having a problem while using a Scanner and I do not know how to solve it, kind of new in Java. I have created a menu to read an input char provided by the user through a Scanner and I read options from the menu with this loop:
/**
* Constant to exit the menu.
*/
private static final char EXIT = 'E';
public void run() {
char option = EXIT;
do {
menu.show();
option = menu.readOption();
try {
processOption(option);
} catch (RuntimeException exception) {
handleSystemError(exception);
} catch (Exception exception) {
handleUserError(exception);
}
} while (option != EXIT);
}
This is what the method readOption does :
public char readOption() {
return Console.readChar(" Option ");
}
And this is what the method readChar does :
public static char readChar(String msg) {
out.println( msg + ": ");
keyboard.useDelimiter(System.lineSeparator());
char res = keyboard.next().charAt(0);
keyboard.reset();
return res;
}
The problem is, the loop in its first performance works perfectly fine. The program works propperly. But after the first performance, when it starts again, in the line where it readsOption, it throws a NoSuchElementException and I have been many hours trying to solve it and I do not know how to. Apparently the problem is in the method readChar, when I try to do "keyboard.next()" it throws the no such element exception. Cannot explain that it works the first time and not a second one. When first performance, it waits for me to introduce a char as I expect, but in the second one,while I wish to be expected to introduce a char, when "keyboard.next()", it throws the mentioned exception. Having an issue clearly with my Scanner, I hope someone can identify the issue here. Thank you very much everyone.
I finally found how to solve it thanks to this page: Solucione el error NoSuchElementException en Java
The issue was that because of the size of this program I had to use 2 scanners at the same time, and when I closed one of them, it caused the other one to stop working, throwing that exception.

Problems with Input and output regarding Java String

Well Hello,
I´m trying to program a kind of game in my free right now.
I started coding some time ago in school but recently we didn´t do much with java so I thought I should do something, so that I don´t forget everything. Well, I still need some since we never did something that's kind of like this. My Problem is that it shows an error and tells me an symbol is missing. The program is supposed to start the game and later interact with different types of objects that contain character information such as stats for both monsters and the player.
import java.util.Scanner;
public class Spiel{
public static void main(String[] args) {
System.out.print("What is your name Adventurer?\n ");
Scanner scanner = new Scanner(System. in);
String Abenteurername = scanner. nextLine();
System.out.println("Adventurer "+Abenteurername+" will you help us clean the dungeon? \n");
String Spielstart = scanner. nextLine();
if (Spielstart.equalsIgnoreCase(ja)) {
System.out.println("Gut");
} else {
System.exit(0);
} // end of if-else
}
}
As you wrote ja without quotes, it expects to find a variable defined with that name, like
String ja = "ja";
if (Spielstart.equalsIgnoreCase(ja)) {
System.out.println("Gut");
}
But what you want is just
if (Spielstart.equalsIgnoreCase("ja")) {
System.out.println("Gut");
} else {
System.exit(0);
} // end of if-else

Java - input data only working if an output statement exists?

EDIT: Made the code a little nicer, deleted backstory, rephrased question.
So I had everything working, but then moved to a different computer, and it stopped working. Because this is for marks, I don't want to hand in a program that could possibly stop not work on my prof's computer.
So here's what I'm trying to do - I want to input data continuously, until enter is pressed on an empty line.
My real question is this. Why does it only work when the print statement is there after readLine command? And why does that not work on someone else's computer ?
(Could it be that I'm running from the IDE? JCreator 4.5 it works, JCreator 4 on the school computer didn't.)
import java.util.*;
import java.io.*;
public class TestIfWorks {
public static ArrayList<String> getArrList() {
String input = "Empty";
ArrayList<String> info = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean go = true;
while (go) {
try {
input = in.readLine();
System.out.print(">"); //This causes it to work on my computer, but not on other computers. What!?!
} catch (Exception e) {
System.out.println("ERROR: key read problem");
}
if (input.equals("")) go = false;
else info.add(input);
}
return info;
}
public static void inputmethod() {
System.out.println("Please enter a brief summary if desired. Press enter on an empty line to stop entering data.");
ArrayList<String> info = new ArrayList<String>();
info = getArrList();
System.out.println("Now printing the arraylist out.");
for (int i = 0; i < info.size(); i++) {
System.out.println(info.get(i));
}
}
public static void main(String[] args) {
inputmethod();
}}
So yeah, it likes to loop once, enter that data fine, then on the second loop it always thinks you're entering nothing, and so only the first data is stored. Unless the output statement is there. Then it likes to work, but only sometimes.
What is happening?
I think you should start using
if(str != null && !str.isEmpty())
in order to see if it's empty or not
also you should add
tempStr = "";
after your if else block because if something goes wrong your tmpStr will still have the value from last loop state.
If i were you i'd try this instead:
String input = System.console().readLine();

Using Scanner to change boolean in java

This is my first post here, so I decided to browse around various posts here in order to try and get a feel for how questions should be posted.
Hence, if I mess up please let me know so I can fix my post accordingly ASAP.
So here is my problem:
I started learning Java today and I'm working on just getting a feel for how everything works. I have the code below set to tell if kids are good or bad and display corresponding replays.
Good kids get candy, bad kids get none. I want to be able to limit the users choices to good or bad and have their answer change the Boolean to true or false to run the right if statement.
I saw a Math.random way of doing it but when I tried it I got more problems.
Thank you for your time.
The following is my code:
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int bad = 1;
String a = sc.nextLine();
int answer = candy / kids;
String answer2 = "No Candy";
boolean good = false;
System.out.println(a);
//closeing the scanner
sc.close();
if(bad == 1) {
System.out.println(answer2);
} else {
if(bad == 2)
good = true;
System.out.println(answer);
}
if(good == true) {
System.out.println("Good Job");
} else {
System.out.println("Try again tomorrow!");
}
}
}
For one, it is not necessary to end the scanner before your code ends. You can leave it around, closing it is not necessary. (Unless your IDE forces you to , then yes, you should, but close it at the end just in case. I have Eclipse, so my code still runs without a glitch.)
Another comment is, just for the sake of aesthetics you should concatenate some kind of string on to the end of answer, so the reader understands what the variable means.
One more thing. I often find it helpful to name my scanner something a little more intuitive, such as input. Because after all, that's what it is. (I'm only commenting a lot about your code because you are just beginning to learn things, so you should get into good habits early.)
What you can do in this situation is convert your string inputs to booleans, by using boolean userInput = Boolean.parseBoolean(answer). Then, depending on the input the user gives by using an if statement, they can control the flow of the code.
I cleaned up your code a little bit, if you don't mind.
import java.util.Scanner;
public class lol {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int answer = candy / kids;
String answer2 = "No Candy";
System.out.println("Are youkids good or bad?");
System.out.println("[1] Good = true");
System.out.println("[2] Bad = false");
String a = sc.nextLine();
boolean userInput = Boolean.parseBoolean(a);
if(userInput== false){
System.out.println(answer2);
System.out.println("Try again tomorrow!");
}
else{
System.out.println("Good Job");
System.out.println("You get" +answer+"pieces.");
}
}
}
Seeing as you're just starting out, I'll try and keep it simple. There are plenty of ways to force your reader to say either "good" or "bad" that are better than below, but they require loops (which I assume you haven't touched yet).
Consider the following:
boolean good = false;
if (a.equals("good")) { // they said good
good = true;
} else if (a.equals("bad")) { // they said bad
good = false;
} else { // they said neither
System.out.println("You didn't say a correct word!");
}
You first specify that you have a boolean good (which you can either give a default value as above, or nothing). Then, depending on the user's input, you can set the boolean to be whatever is appropriate.
The reasoning behind having to declare the boolean good above the if statements has to do with the scope of a variable. If your book/teacher hasn't explained what that is, you should look it up now. The TL;DR is that if you only first declare your variable inside the if statements, then it will disappear as soon as you leave the if statements. You can see how in this case that would basically defeat the purpose of the if statements entirely.
You can limit the input by enclosing it in a loop.
List<String> accepted = new ArrayList<String>();
accepted.add("good");
accepted.add("bad");
System.out.println("Good or bad?");
String input = sc.nextLine();
while(!accepted.contains(input)) {
System.out.println("Invalid query '" + input + "'. Try again.");
input = sc.nextLine();
}
The code you have, well I don't know exactly what it's trying to do. It doesn't look functional at all. So where this fits in I'm not 100% sure.
package test;
import java.util.Scanner;
public class app {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
String a="?";
while(!a.equals("good") && !a.equals("bad")){
System.out.println("Was the kid good or bad ?");
a = sc.nextLine();
}
boolean wasKidGood = a.equals("good");
String result = (wasKidGood ? "Good kid gets candy" : "No candy for bad kid");
System.out.println(result);
sc.close();
}
}
Hello, I wrote something, that will help you grasp a while loop and a ternary operator (alternative version of if loop). You also need to pay attention as to where you are allowed to use == and where you should use the equals() method. Regards

No Such Element Exception?

So here is my code:
public static void getArmor(String treasure)
throws FileNotFoundException{
Random rand=new Random();
Scanner file=new Scanner(new File ("armor.txt"));
while(!file.next().equals(treasure)){
file.next(); //stack trace error here
}
int min=file.nextInt();
int max=file.nextInt();
int defense=min + (int)(Math.random() * ((max - min) + 1));
treasure=treasure.replace("_", " ");
System.out.println(treasure);
System.out.println("Defense: "+defense);
System.out.println("=====");
System.out.println();
}
public static void getTreasureClass(Monster monGet)
throws FileNotFoundException{
Random rand = new Random();
String tc=monGet.getTreasureClass();
while (tc.startsWith("tc:")){
Scanner scan=new Scanner(new File ("TreasureClassEx.txt"));
String eachLine=scan.nextLine();
while(!tc.equals(scan.next())){
eachLine=scan.nextLine();
}
for (int i=0;i<=rand.nextInt(3);i++){
tc=scan.next();
}
getArmor(tc); //stack trace error here
}
}
For some reason I get a No Such Element Exception
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at LootGenerator.getArmor(LootGenerator.java:43)
at LootGenerator.getTreasureClass(LootGenerator.java:68)
at LootGenerator.getMonster(LootGenerator.java:127)
at LootGenerator.theGame(LootGenerator.java:19)
at LootGenerator.main(LootGenerator.java:11)
I'm not sure why though. Basically my program is searching through two text files - armor.txt and TreasureClassEx.txt. getTreasureClass receives a treasure class from a monster and searches through the txt until it reaches a base armor item (a string that does not start with tc:.) It then searches getArmor for an armor that matches the name of the base armor it got in treasure class. Any advice would be appreciated! Thanks!
The link to the txt files is here: http://www.cis.upenn.edu/~cis110/hw/hw06/large_data.zip
It looks like you are calling next even if the scanner no longer has a next element to provide... throwing the exception.
while(!file.next().equals(treasure)){
file.next();
}
Should be something like
boolean foundTreasure = false;
while(file.hasNext()){
if(file.next().equals(treasure)){
foundTreasure = true;
break; // found treasure, if you need to use it, assign to variable beforehand
}
}
// out here, either we never found treasure at all, or the last element we looked as was treasure... act accordingly
I had run into the same issue while I was dealing with large dataset. One thing I've noticed was the NoSuchElementException is thrown when the Scanner reaches the endOfFile, where it is not going to affect our data.
Here, I've placed my code in try block and catch block handles the exception. You can also leave it empty, if you don't want to perform any task.
For the above question, because you are using file.next() both in the condition and in the while loop you can handle the exception as
while(!file.next().equals(treasure)){
try{
file.next(); //stack trace error here
}catch(NoSuchElementException e) { }
}
This worked perfectly for me, if there are any corner cases for my approach, do let me know through comments.
Another situation which issues the same problem,
map.entrySet().iterator().next()
If there is no element in the Map object, then the above code will return NoSuchElementException. Make sure to call hasNext() first.
Looks like your file.next() line in the while loop is throwing the NoSuchElementException since the scanner reached the end of file. Read the next() java API here
Also you should not call next() in the loop and also in the while condition. In the while condition you should check if next token is available and inside the while loop check if its equal to treasure.
I Know this question was aked 3 years ago, but I just had the same problem, and what solved it was instead of putting:
while (i.hasNext()) {
// code goes here
}
I did one iteration at the start, and then checked for condition using:
do {
// code goes here
} while (i.hasNext());
I hope this will help some people at some stage.

Categories