JAVA: Word game query - java

Hello my fellow programmers!
I have this code so far:
public class Levels {
int cLevel;
public void newGame() {
boolean newGame = true;
if (newGame) {
cLevel = 1;
List<String> list = new ArrayList<String>();
try {
BufferedReader bf = new BufferedReader(new FileReader(
"src/WordGuess/ReadFile/LevelFiles/Level_" + cLevel
+ ".txt"));
String cLine;
while ((cLine = bf.readLine()) != null) {
list.add(cLine);
}
String words[] = new String[list.size()];
words = list.toArray(words);
System.out
.println("These are your help letters so you can beat that level: "
+ words[0]);
for (int i = 1; i < words.length; i++) {
char[] replaceChar = words[i].toCharArray();
for (int x = 0; x < replaceChar.length; x++) {
replaceChar[x] = '*';
}
String replacement = new String(replaceChar);
System.out.println("\f" + replacement);
}
System.out.println("\t Score: " + Score(0) + ";\t Lives: "
+ Lives(5) + ";");
System.out.println("\n Enter Word:");
System.in.read();
} catch (Exception e) {
System.out
.println("Oh! Something went terribly wrong. A team of highly trained and koala-fied koalas have been dispatched to fix the problem. If you dont hear from them please restart this program.");
e.printStackTrace();
}
}
}
private int Lives(int lives) {
int wrongTries = 0;
boolean correctWord;
int counter = 0;
String livesForm[] = new String[lives];
// for (int i = 0; i == lives; i++) {
// livesForm[i] = "♥";
// }
return lives;
}
private int Score(int score) {
return score;
}}
So my query is as follows.
I want to show the lives as the heart symbol and still keep the integer value of it for functioning purposes. So as shown in my code example 5 lives to be represented by 5 hearts but still keep the int lives value of 5. As shown also in my example i also tried with an array of strings the size of the integer value 'lives' and to be replaced by hearts. As far as i ran the code no error was displayed whatsoever so i would assume that the array has been populated but i couldn't figure out how to display the array in the console as "Lives: ♥♥♥♥♥".
I have tried with the regular:
System.out.println(livesForm[i]);
But it did not display anything. I don't know if i have structured my question perfectly clear. I will be glad if any of you fellas can give me an advice or hint. Thank you for spending time on this question!

Why not:
public String getLivesAsString(int lives) {
StringBuilder sb = new StringBuilder(lives);
for(int i = 0; i < lives; i++) {
sb.append("♥");
}
return sb.toString();
}
?
Not sure why you need an array to display an amount of '♥'-symbols defined by an integer?

Related

Implementing While loop so my code repeats itself properly

In my code:
public static String input() {
Scanner input = new Scanner(System.in);
while(true) {
int qcount = 0;
String key = input.nextLine();
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
//Here the while loop is supposed to break
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
int[] radie = new int[(keyCharArray.length)/2];
int[] höjd = new int[(keyCharArray.length)/2];
int counter = 0;
for(int i = 0; i < keyCharArray.length; i++){
if(i % 2 == 0){
radie[i/2] = keyCharArray[i] - '0';
}
else if(i % 2 != 0){
höjd[i/2] = keyCharArray[i] - '0';
}
}
for(int i = 0; i < (keyCharArray.length)/2; i++) {
System.out.print("r = " + radie[i] + " " + "h = " + höjd[i] + "\n\r" + "Basytans area: " + area(radie[i], höjd[i]) + "\n\r" + "Mantelytans area:" + area(radie[i]) + "\n\r" + "Volym: " + volume(radie[i], höjd[i]) + "\n\r");
}
return key;
}
}
The While loop is supposed to repeat the content until keyCharArray[i] =='q' -> There after the while loop is supposed to break
How can I make this work? Thanks
I have tried everything, yet I can't seem to solve it.
Appreciate any efforts, Thanks alot
Tried everything, doesn't work
sadasd
dsadsa
sdadsa
asdsda
You current code is (partially) like this:
public static String input(){
Scanner input = new Scanner(System.in);
while(true){
int qcount = 0;
String key = input.nextLine();
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
// The rest...
}
}
The problem with this is that the break only breaks the inner for loop.
The simplest solution is to use the qcount variable you already have, and after the for loop check if it's non-zero to break out of the while loop:
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
if (qcount > 0) {
break; // Breaks out of the while loop
}
As for my suggestion in the comment it would be something like this instead:
private boolean shouldBreak(String key) {
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
return true; // Return that we should break the while loop
}
}
return false; // Do not break the while loop
}
public static String input(){
Scanner input = new Scanner(System.in);
while(true){
String key = input.nextLine();
if (shouldBreak(key)) {
break; // Breaks out of the while loop
}
// The rest...
}
}
I personally recommend something like this, as it makes the code cleaner and easier to read and understand and maintain.

Getting names from text file shifts names 1 place to the left (in array)

I was trying to solve problem 22 of Euler Project. Description of what I'm trying to solve is here:
https://projecteuler.net/problem=22
Where's the problem?: I've got the names from the text file, put them on one string,
edited the string so that the names are separated by one space.
After getting those names on an array of Strings, I sort them. After finishing the program and getting the result wrong, I started testing different parts of the program and notice that the name "COLIN", which by eulerproject page is said to be the 938th, is 937th on my array. I can't seem to get why is it happening and how to fix this. Help would be much appreciated.
Here is the code:
package Project022;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class NameScore {
private long scoreSum;
private LinkedList<String> allNames;
private String[] sortedNames;
private int[] nameScores;
public NameScore(){
scoreSum = 0;
allNames = new LinkedList<>();
getNames();
}
private void getNames(){
List<String> content = null;
File names;
// read "names.txt" file and put all the names in one line(not effective when line
// length surpasses String maximum character range(2^31 - 1) but is good enough for us
// for now)
try {
names = new File("Project022\\names.txt");
content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
} catch (Exception e){
System.out.println("something went wrong while getting the file");
}
assert content != null;
//replace (",") with a space ( )
String filtered = content.get(0).replaceAll("\",\"", " ");
//then remove first and last (")
filtered = filtered.substring(1, filtered.length() - 1);
//declare "tempName" as a helper string
StringBuilder tempName = new StringBuilder();
//get every name and put it on the LinkedList
for (int i = 0; i < filtered.length(); i++) {
if (filtered.charAt(i) != ' '){
tempName.append(filtered.charAt(i));
} else {
allNames.add(tempName.toString().trim());
tempName = new StringBuilder();
}
}
//now we use an pre defined array since it is faster.
sortedNames = new String[allNames.size()];
for (int i = 0; i < sortedNames.length; i++) {
sortedNames[i] = allNames.get(i);
}
//make the new array worthy of its name
Arrays.sort(sortedNames);
System.out.println(sortedNames[937]);
System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
}
public void calculate(){
//we set the score for each name
nameScores = new int[sortedNames.length];
//
for (int i = 0; i < nameScores.length; i++) {
setScore(sortedNames[i], i + 1);
}
for (int i = 0; i < nameScores.length; i++) {
scoreSum += nameScores[i];
}
}
private void setScore(String name, int n) {
int sc = 0;
for (int i = 0; i < name.length(); i++) {
sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
}
sc *= n;
nameScores[n-1] = sc;
}
#Override
public String toString(){ return "the score of all names is: " + scoreSum; }
public static void main(String[] args) {
NameScore name = new NameScore();
name.calculate();
System.out.println(name);
}
}
What I've ruled out as a problem:
the setScore() method which gives a score for every name, because I tested it with examples by hand and by program and got same results.
the calculate() method, since what it does is gets the score for each name and adds to the total sum.
This works for me.
Path p = Paths.get("p022_names.txt");
try {
List<String> lines = Files.readAllLines(p); // throws java.io.IOException
System.out.println(lines.size()); // Only one line in file.
// Remove all " (double quotes) characters.
String tmp = lines.get(0).replaceAll("\"", "");
String[] names = tmp.split(",");
System.out.println(names.length);
Arrays.sort(names);
// Test against example given in problem description.
System.out.println(names[937]); // Should be COLIN
char[] lett = names[937].toCharArray();
int sigma = 0;
for (int k = 0; k < lett.length; k++) {
sigma += lett[k] - 'A' + 1; // Since only uppercase letters in file.
}
int score = sigma * (937 + 1);
System.out.println(score); // Should be 49714
// Now obtain answer, i.e. the total of all the name scores in the file.
int total = 0;
for (int i = 0; i < names.length; i++) {
char[] letters = names[i].toCharArray();
int sum = 0;
for (int j = 0; j < letters.length; j++) {
sum += letters[j] - 'A' + 1;
}
total += sum * (i + 1);
}
System.out.println(total);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
Output obtained when running above code is as follows.
1
5163
COLIN
49714
871198282
I didn't want to make too many changes to your code, so just removed your replacement of "," and instead just removed all ". Then I added ALONSO in the end after the loop.
I figure if we're all in consensus about the total score of all the names, then we're doing it right :)
It prints:
-- Where's ALONSO ?
sortedNames[145] = ALONA
sortedNames[146] = ALONSO
sortedNames[147] = ALONZO
-- Where's COLIN ?
sortedNames[936] = COLETTE
sortedNames[937] = COLIN
sortedNames[938] = COLLEEN
-- Where's MARY ?
sortedNames[3361] = MARX
sortedNames[3362] = MARY
sortedNames[3363] = MARYA
-- sortedNames.length = 5163
the score of all names is: 871198282
I also called it Project022:
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
//public class NameScore {
public class Project022 {
private long scoreSum;
private LinkedList<String> allNames;
private String[] sortedNames;
private int[] nameScores;
public Project022(){
scoreSum = 0;
allNames = new LinkedList<>();
getNames();
}
private void getNames(){
List<String> content = null;
File names;
// read "names.txt" file and put all the names in one line(not effective when line
// length surpasses String maximum character range(2^31 - 1) but is good enough for us
// for now)
try {
// names = new File("Project022\\names.txt");
names = new File("resource\\p022_names.txt");
content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
} catch (Exception e){
System.out.println("something went wrong while getting the file");
}
assert content != null;
//replace (",") with a space ( )
// String filtered = content.get(0).replaceAll("\",\"", " ");
String filtered = content.get(0).replaceAll("\"", "");
// //then remove first and last (")
// filtered = filtered.substring(1, filtered.length() - 1);
//declare "tempName" as a helper string
StringBuilder tempName = new StringBuilder();
//get every name and put it on the LinkedList
for (int i = 0; i < filtered.length(); i++) {
// if (filtered.charAt(i) != ' '){
if (filtered.charAt(i) != ','){
tempName.append(filtered.charAt(i));
} else {
allNames.add(tempName.toString().trim());
tempName = new StringBuilder();
}
}
allNames.add(tempName.toString().trim()); // added to include ALONSO
//now we use an pre defined array since it is faster.
sortedNames = new String[allNames.size()];
for (int i = 0; i < sortedNames.length; i++) {
sortedNames[i] = allNames.get(i);
}
//make the new array worthy of its name
Arrays.sort(sortedNames);
System.out.println("\n -- Where's ALONSO ?");
for (int i = 145; i < 148; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- Where's COLIN ?");
for (int i = 936; i < 939; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- Where's MARY ?");
for (int i = 3361; i < 3364; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- sortedNames.length = " + sortedNames.length + "\n");
// System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
}
public void calculate(){
//we set the score for each name
nameScores = new int[sortedNames.length];
//
for (int i = 0; i < nameScores.length; i++) {
setScore(sortedNames[i], i + 1);
}
for (int i = 0; i < nameScores.length; i++) {
scoreSum += nameScores[i];
}
}
private void setScore(String name, int n) {
int sc = 0;
for (int i = 0; i < name.length(); i++) {
sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
}
sc *= n;
nameScores[n-1] = sc;
}
#Override
public String toString(){ return "the score of all names is: " + scoreSum; }
public static void main(String[] args) {
Project022 name = new Project022();
name.calculate();
System.out.println(name);
}
}

UVa 11616 Roman Numerals Time Limit Exceeded - I am receiving Time Limit Exceeded consistently

I am working on a problem on UVa for general programming practice, as I want to get better at programming competitively. However I am having trouble with this problem - Roman Numerals. In this problem the goal is to take input which will be in the form of either a Roman numeral or Arabic numeral and then I must convert from one to the other. I feel that my code should not have trouble in processing fast enough yet according to the online judge, it does not process fast enough. I need to help finding out how I may optimize my code so that it will run faster and not receive TLE.
Below is my program, any help as to explaining why I am receiving Time Limit Exceeded would be greatly appreciated. Thanks in advance.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
private static String order = "IVXLCDM";
private static String order2 = "IXCM"; // These chars are the result of 10^n (n depending on index in the string)
private static String order3 = "VLD"; // These chars are products of 5*10^n (n depending on index in the string)
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String ans = "";
while (true) {
String read = "";
int aNum = 0;
String rNum = "";
try {
read = br.readLine();
if (read=="")
break;
} catch (IOException e) {
if (read=="")
break;
e.printStackTrace();
}
try {
aNum = Integer.parseInt(read);
// System.out.println(aNum);
int thousands = aNum/1000;
// System.out.println(thousands);
int hundreds = aNum/100;
hundreds = hundreds%10;
// System.out.println(hundreds);
int tens = aNum%100;
tens = tens/10;
// System.out.println(tens);
int ones = aNum%10;
// System.out.println(ones);
rNum+= a2R(thousands,"M");
rNum+= a2R(hundreds,"C");
rNum+= a2R(tens,"X");
rNum+= a2R(ones,"I");
// System.out.println(rNum);
ans+=(rNum+"\n");
// System.out.print(ans);
} catch (NumberFormatException c) {
rNum = read;
if (rNum.equals(""))
break;
aNum = r2A(rNum);
// System.out.println(aNum);
ans+=(aNum+"\n");
// System.out.print(ans);
}
}
System.out.print(ans);
}
private static int r2A(String rNum) {
int aNum = 0;
for (int i = order.length()-1; i >= 0; i--) {
char curChar = order.charAt(i);
while (rNum.indexOf(curChar)!=-1) {
if (rNum.indexOf(curChar)==0) {
if (order2.indexOf(curChar)!=-1) {
aNum+=((int)Math.pow(10, order2.indexOf(curChar)));
}
else if (order3.indexOf(curChar)!=-1) {
aNum+=(5*((int)Math.pow(10, order3.indexOf(curChar))));
}
rNum = rNum.substring(1);
}
else if (rNum.indexOf(curChar)==1) {
if (order2.indexOf(curChar)!=-1) {
aNum+=((int)(Math.pow(10, order2.indexOf(curChar))-Math.pow(10, order2.indexOf(curChar)-1)));
}
else if (order3.indexOf(curChar)!=-1) {
aNum+=((int)((5*Math.pow(10, order3.indexOf(curChar)))-Math.pow(10,order3.indexOf(curChar))));
}
rNum = rNum.substring(2);
}
}
}
return aNum;
}
private static String a2R(int num, String theNum) {
// num is the digit of an Arabic digit number to be replaced by Roman Numerals for that digit
// theNum is the value of Roman Numerals that would go into the specific digit place (tens, ones,...)
String rNum = "";
if (!theNum.equals("M")) {
if (num==9) {
rNum = theNum + order.charAt(order.indexOf(theNum)+2);
}
else if (num==4) {
rNum = theNum + order.charAt(order.indexOf(theNum)+1);
}
else if (num>=5) {
rNum+= order.charAt(order.indexOf(theNum)+1);
for (int i = 0; i < num-5; i++) {
rNum+=theNum;
}
}
else {
for (int i = 0; i < num; i++) {
rNum+=theNum;
}
}
}
else {
for (int i = 0; i < num; i++) {
rNum+=theNum;
}
}
return rNum;
}
}
`
I expect the TLE is being caused by your program never terminating.
Currently you have a while (true) loop, which breaks when you see a blank line.
According to the problem however...
The input consists of several lines, each one containing
either an Arabic or a Roman number n, where 0 < n < 4000.
Nowhere does it state that there will be an extra blank line terminating the input.
So your program will not terminate, forever waiting until an extra blank line has been entered.
Instead of reading your input like this
while (true) {
String read = "";
int aNum = 0;
String rNum = "";
try {
read = br.readLine();
if (read=="")
break;
} catch (IOException e) {
if (read=="")
break;
e.printStackTrace();
}
//etc
try this instead
String read = "";
while ((read = br.readLine()) != null) {
int aNum = 0;
String rNum = "";
//etc
I solved my problem by going about it in a different manner, I used a couple of HashMaps to map Roman numeral values to Arabic numeral values and vice versa. I had four helper methods: one would set up the hashmaps, another would convert from Roman numeral to Arabic numeral, and the other two would work together to convert from Arabic numeral to Roman numeral.
The method that converted from Roman to Arabic would go through the string in a for loop starting from the beginning of the string. It would check if the length of the string was greater than one, and if so it would then check if the substring of the first two values are in the Roman to Arabic hashmap. If so, it would then add the value that the Roman numeral value equates to to an int variable. The method would also check substrings of length 1.
In the methods that converted from Arabic to Roman, the input integer would first be analyzed then it would be torn apart into its little pieces. In the first method, four integer values would first be produced: the thousands value, the hundreds value, the tens value, then the ones value. The second method would organize these values into the correct Roman numeral form.
Thanks to everybody who helped me solve this problem, I did not realize some of the mistakes that I made, probably due to my inexperience in programming so this was a great learning experience for myself.
Below is my solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
class Main {
private static HashMap<String,Integer> r2A = new HashMap<String,Integer>();
private static HashMap<Integer,String> a2R = new HashMap<Integer,String>();
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
makeMaps();
String read;
StringBuilder answers = new StringBuilder("");
while ((read=br.readLine())!=null) {
int aNum = 0;
String rNum = "";
try {
aNum = Integer.parseInt(read);
System.out.println(arab2Roman(aNum));
} catch (NumberFormatException c) {
rNum = read;
int ans = roman2Arab(rNum);
System.out.println(ans);
}
}
}
private static int roman2Arab(String rNum) {
int aNum = 0;
for (int i = 0; i < rNum.length(); i++) {
boolean done = false;
String theNum = rNum.substring(i,i+1);
if (i < rNum.length()-1) {
String part = rNum.substring(i, i+2);
if (r2A.containsKey(part)) {
aNum+=r2A.get(part);
i++;
done = true;
}
}
if (!done) {
if (r2A.containsKey(theNum)) {
aNum+=r2A.get(theNum);
}
}
}
return aNum;
}
private static String arab2Roman(int num) {
StringBuilder rNum = new StringBuilder("");
int thousands = num-(num%1000);
int hundreds = ((num/100)%10)*100;
int tens = ((num/10)%10)*10;
int ones = num%10;
rNum.append(simpleConv(thousands,"thousands"));
rNum.append(simpleConv(hundreds,"hundreds"));
rNum.append(simpleConv(tens,"tens"));
rNum.append(simpleConv(ones,"ones"));
return rNum.toString();
}
private static String simpleConv(int num, String place) {
StringBuilder ans = new StringBuilder("");
int pNum = (place.equals("thousands")) ? 1000 : (place.equals("hundreds")) ? 100 : (place.equals("tens")) ? 10 : 1;
if (a2R.containsKey(num)) {
ans.append(a2R.get(num));
}
else {
if (num/pNum>=5) {
ans.append(a2R.get(5*pNum));
for (int i = 0; i < ((num/pNum)-5); i++) {
ans.append(a2R.get(pNum));
}
}
else {
for (int i = 0; i < num/pNum; i++) {
ans.append(a2R.get(pNum));
}
}
}
return ans.toString();
}
private static void makeMaps() {
// First r2A
r2A.put("I", 1);
r2A.put("IV", 4);
r2A.put("V", 5);
r2A.put("IX", 9);
r2A.put("X", 10);
r2A.put("XL", 40);
r2A.put("L", 50);
r2A.put("XC", 90);
r2A.put("C", 100);
r2A.put("CD", 400);
r2A.put("D", 500);
r2A.put("CM", 900);
r2A.put("M", 1000);
// Second a2R
a2R.put(1, "I");
a2R.put(4, "IV");
a2R.put(5, "V");
a2R.put(9, "IX");
a2R.put(10, "X");
a2R.put(40, "XL");
a2R.put(50, "L");
a2R.put(90, "XC");
a2R.put(100, "C");
a2R.put(400, "CD");
a2R.put(500, "D");
a2R.put(900, "CM");
a2R.put(1000, "M");
}
}

changing 'invisible' chaaracters to letters, game of hangman

so in my program im trying to incorporate a couple of different classse into my main program which i am coming up with the code.
What i am given
Dictionary() {
dictionary = new String[NUMBER_OF_WORDS];
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(FILE_NAME));
}catch (FileNotFoundException e) {
System.out.println("Dictionary class cannot find file \"dictionaryData.txt\".");
System.out.println("Please make sure that the file is in the project folder.");
System.exit(0);
}
for (int i = 0; i < NUMBER_OF_WORDS; i++) {
dictionary[i] = inputStream.next();
}
}
public String getRandomWord(){
Random generator = new Random();
String temp = new String();
temp += dictionary[generator.nextInt(NUMBER_OF_WORDS)];
return temp;
}
public boolean find(String word) {
int count = 0;
int lowerIndex = 0;
int upperIndex = NUMBER_OF_WORDS - 1;
int middleIndex;
while(lowerIndex <= upperIndex){
middleIndex = (lowerIndex + upperIndex) / 2;
count++;
if(word.equalsIgnoreCase(dictionary[middleIndex])) { // found it
return true;
}
else if (word.compareToIgnoreCase(dictionary[middleIndex]) < 0) { // word smaller than middle
upperIndex = middleIndex - 1;
}
else { // word is larger than middle
lowerIndex = middleIndex + 1;
}
}
return false;
}
}
along with another class WordHider
WordHider() {
secretWord = new String();
wordMask = new String();
}
public String getWordMask() {
return wordMask;
}
public String getSecretWord() {
return secretWord;
}
public void setSecretWord(String newSecretWord) {
secretWord = newSecretWord.toLowerCase();
if (secretWord.length() > 0) {
wordMask = HIDE_CHAR;
for (int i = 1; i < secretWord.length(); i++) {
wordMask += HIDE_CHAR;
}
}
}
public boolean isHiddenWordFound() {
for (int i = 0; i < wordMask.length(); i++) {
if(wordMask.charAt(i) == HIDE_CHAR.charAt(0)) {
return false;
}
}
return true;
}
public int revealLetter(String letter) {
int count = 0;
String newFoundWord = "";
if (letter.length() == 1) {
for (int i = 0; i < secretWord.length(); i++) {
if ((secretWord.charAt(i) == letter.charAt(0))
&& (wordMask.charAt(i) == HIDE_CHAR.charAt(0))) {
count++;
newFoundWord += letter;
}
else {
newFoundWord += wordMask.charAt(i);
}
}
}
wordMask = newFoundWord;
return count;
}
}
and using those classes i have to come up with code that looks like this:
Word: ********** Guesses Left: 5
Enter your guess: a
Miss!
Word: ********** Guesses Left: 4
Enter your guess: e
Miss!
Word: ********** Guesses Left: 3
Enter your guess: i
Word: i**i*i**** Guesses Left: 3
Enter your guess: o
Word: i**i*i*o** Guesses Left: 3
And ive got a couple of questions about this,
1) i have a dictionaryData.text that i was given and have to implement
that into my code. it contains a list of 81thousand words and im not
sure how to have my program recognize its there. Dictionary class
cannot find file "dictionaryData.txt". Please make sure that the file
is in the project folder. ^ i get that error when i try and print a
random word
2) How do i get my program to change the letters of a word to
stars(Hide the word)
3) put it all in a loop?
Parts of the Dictionary class and the WordHider class are missing. Nevertheless, I'll try and answer your questions.
1) Like I said, you're missing part of the Dictionary class. You incorporate the class like this:
Dictionary dictionary = new Dictionary();
String word = dictionary.getRandomWord();
2) Like this:
wordHider.setSecretWord(word);
3) I'm not sure what "it" is, but yes, your user has to guess a letter. Then you have to check to see if the letter is in the word. Like this:
wordHider.revealLetter(letter);
Then you have to display the word and let the user guess another letter. This guess / check / display has to be in a loop.

Null Pointer Exceptions Without Apparent Reason

StackOverflow. I am attempting to make a program that uses a text menu to to a multitude of things to manipulate a single string. One of the methods turns the string into an array of strings. This works fine. However, all of the methods that manipulate it as an array(one prints it out, one reverses the word order, and one sorts them using an exchange sorting method) return a NullPointerException when called. I have looked all through the code and do not see where it is coming from. Here is the .Java file containing all of the code. My problem is only happening when I call the printArray(), reverse(), and sort() methods, near the bottom. Any and all help is appreciated. Sorry for the sloppy code, I have not cleaned it up yet.
Code:
/*
Computer Programming Lab 11
Jim Kimble
3 Mar 2013
Work with strings and implementing a menu.
Acknowledgements:
Uses main structure of HUTPanel as designed at UMU, 2002-2012
*/
import java.io.*;
import java.awt.*;
import javax.swing.*;
public class HUTPanel extends JPanel
{
/***************************************************
* Class-level data members should be declared here.
***************************************************/
int numVowels;
String[] words;
String str;
String vowels;
String menuChoice;
String oString = "A tong lime ago, a daggy shog bossed a cridge over a pillmond,\n"
+"When in the course of human events\n"
+"Mary had a little lamb.\n"
+"The girls' basketball team repeated as tournament champion this weekend.";
public HUTPanel(JFrame frame)
{
// Set panel background color
setBackground(Color.WHITE);
setLayout(null);
setPreferredSize(new Dimension(810, 410));
/***************************
* Now add your code below:
***************************/
// Create a frame around this panel.
frame.setTitle("Computer Programming Lab/Program # 11");
frame.getContentPane().add(this);
str = "A tong lime ago, a daggy shog bossed a cridge over a pillmond,\n"
+"When in the course of human events\n"
+"Mary had a little lamb.\n"
+"The girls' basketball team repeated as tournament champion this weekend.";
System.out.println("Lab 11: Text Manipulation");
//getTheText();
System.out.println("The string is: '"+str+"'.");
handleTheMenu();
} // end of constructor
/*************************
* Add your methods here:
*************************/
// Get a text sequence from the keyboard and put it in str
public void getTheText()
{
Boolean inputDone = false;
while (!inputDone)
{
System.out.print("Enter your text: ");
inputDone = grabText();
}
}
private Boolean grabText()
{
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
menuChoice = inputReader.readLine();
return true;
}
catch(IOException e)
{
System.out.println("Error reading input. Please try again.");
}
return false;
}
public void handleTheMenu()
{
int choice = -1;
Boolean OK;
while (choice != 0)
{
choice = -1;
System.out.println("Menu:");
System.out.println();
System.out.println(" 1. Count the vowels"); //"There are ... vowels in the text."
System.out.println(" 2. Remove all letter e's"); //then print it.
System.out.println(" 3. Replace all t's with '+'"); //then print it
System.out.println(" 4. Search for a requested word (will reset the string)"); //Does 'word' exist in the text?
System.out.println(" 5. Print the words on individual lines");
System.out.println(" 6. Reset the string.");//Reset the string to the original
System.out.println(" 7. Put the words in an array"); //then print it
System.out.println(" 8. Reverse the text word order"); //then print it
System.out.println(" 9. Sort the words in an array"); //Once the words are put into an array
System.out.println();
System.out.print(" 0 to quit --> ");
OK = grabText();
if (OK)
{
try
{
choice = Integer.parseInt(menuChoice);
}
catch(NumberFormatException e)
{
System.out.println("Not a number; please try again.");
System.out.println();
}
switch(choice)
{
case 0: System.out.println();
System.out.println("Thank you.");
break;
case 1: countVowels();
break;
case 2: removeAllEs();
break;
case 3: changeTToPlus();
break;
case 4: find();
break;
case 5: listWords();
break;
case 6: reset();
break;
case 7: makeArray();
break;
case 8: reverse();
break;
case 9: sort();
break;
default: System.out.println("Not a valid choice; please try again.");
}
}
}
}
private void countVowels() {
//count the vowels in str
vowels = "aeiouAEIOU";
numVowels = 0;
for( int i = 0; i < vowels.length(); i ++) {
for(int j = 0; j < str.length(); j++) {
if (str.charAt(j) == vowels.charAt(i)) {
numVowels += 1;
}
}
}
System.out.println("The string has " + numVowels + " vowels in it.");
}
private void removeAllEs() {
String str3 = str.replace('e', ' ');
System.out.print(str3);
str = str3;
}
private void changeTToPlus() {
String str2 = str.replace('t', '+');
System.out.println(str2);
str = str2;
}
private void find() {
str = oString;
getTheText();
if(str.indexOf(menuChoice) != -1)
{
System.out.println("The word " +menuChoice+ " is at index " +str.indexOf(menuChoice));
}
else
{
System.out.println("The word " +menuChoice+ " is not in the string.");
}
}
private void listWords() {
int pos = 0;
int i = 0;
while(i > -1)
{
i = str.indexOf(' ', pos);
if (i > -1)
{
System.out.println(str.substring(pos, i));
pos = i + 1;
}
}
}
private void reset() {
str = oString;
System.out.println();
System.out.println("String reset.");
System.out.println();
}
private void makeArray() {
int n = 1;
String[] words = new String[n];
int pos = 0;
int i = 0;
int j = 0;
while(j > -1)
{
for (i = 0; i < 1000; i++)
{
n += 1;
j = str.indexOf(' ', pos);
if (j > -1)
{
words[i] = str.substring(pos, j);
pos = j + 1;
}
}
}
//printArray();
}
//***FIX***
private void printArray() {
for (int k = 0; k < words.length -1; k++){
System.out.println(words[k]);
}
}
//***FIX***
private void reverse() {
int i = 0;
int j = words.length - 1;
String temp;
while (i < j){
temp = words[i];
words[i] = words[j];
words[j] = temp;
i++;
j--;
}
}
private void sort() {
String temp = "";
for (int i = 1; i < words.length - 1; i++) {
for (int j = i + 1; j < words.length; j++) {
int x = words[i].compareTo(words[j]);
if (x > 0) {
temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
for (int p = 0; p < words.length -1; p++) {
System.out.println(words[p]);
}
}
}
You Error is here:
private void makeArray() {
int n = 1;
String[] words = new String[n];//At This line you are creating local array words.The instance variable words is still null.
int pos = 0;
int i = 0;
int j = 0;
while(j > -1)
{
for (i = 0; i < 1000; i++)
{
n += 1;
j = str.indexOf(' ', pos);
if (j > -1)
{
words[i] = str.substring(pos, j);
pos = j + 1;
}
}
}
use:
words = new String[n]; instead of String[] words = new String[n];
As mentioned by Luiggi Mendoza in the comment section, the local variable words defined within makeArray method is shadowing the instance variable words defined within HUTPanel class.
As side note I want to point out the unnecessary creation of new BufferedReader objects in method grabText() each time you are calling it in getTheText(). It would be much efficient if your make inputReader an instance variable in your class , and instantiate it once within the constructor using inputReader = new BufferedReader(new InputStreamReader(System.in));. This way your grabText method becomes like this :
private Boolean grabText()
{
try {
//No more new object creation for BufferedReader for each call of this method.
menuChoice = inputReader.readLine();
return true;
}
catch(IOException e)
{
System.out.println("Error reading input. Please try again.");
}
return false;
}
Make sure you always you always start with option 7, so your words array gets initialized. This is in fact not something that the user should do. The application should handle it so that the user either can't select other options, or does it automatically.
Update: Vishal K is correct, but this is still a weak point in your application.

Categories