Taking user input until <<EOF>> is entered - java

I'm going to start off by saying I already looked at the thread called "I have to make a loop taking users input until "done" is entered" I had no luck with the code answers that were given there.
The description I've been given for my edit command is this:
"Edits a text file if exists. Otherwise, creates new text file. The command waits for the user to type in text(must support multiple lines of text). The user ends the input by typing <<EOF>> and hitting enter."
Right now the code I have is this:
else if (spaceSplit[0].equals("edit")) {
String name = spaceSplit[1];
boolean endOfFile = false;
String content = "";
while(endOfFile == false){
String userInput = s.next();
content += userInput;
if(content.contains("<<EOF>>")){
endOfFile = true;
}
}
FileSystem.edit(name, content);
}
Nothing errors-out, but my else statement prints. My else statement code is this:
else {
System.out.println("That is not a command. Please try again.");
}
What is also funky is that the program goes through the whole do while loop then prints the else. I know this because what is exactly printed is: $That is not a commond. Please try again.
Here is the beginning of my do while loop:
do {
System.out.print("$");
String input = s.nextLine();
input = input.toLowerCase();
spaceSplit = input.split(" ");
Quite confusing. Also my edit(String name, String content) function is as follows:
public static void edit(String name, String content){
for(int i = 0; i < texts.size(); i++){
if(texts.get(i).getName().equals(name)){
texts.get(i).setContent(content);
} else {
texts.add(new TextFile(name,content));
for(int j = 0; j < directories.size(); j++){
if(directories.get(j).getName().equals(wDir.getName())){
texts.get(texts.size() - 1).setParent(directories.get(j));
System.out.println("The parent of " + name + " is " + directories.get(j).getName());
}
}
}
}
}
As you can see I've done a check at the end of my edit(name,content) method to check if the file is correctly created by printing out the parent directory of the text file.
This is how my program should function once I call the edit command:
$mkdir d
$cd d
$edit stuff.txt
Hello everyone, this is just an example!<<EOF>>
The parent of stuff.txt is d
$exit
Good Bye!
Any help provided would be greatly appreciated.
Here is the whole do while loop:
do {
System.out.print("$");
String input = s.nextLine();
input = input.toLowerCase();
spaceSplit = input.split(" ");
if (spaceSplit[0].equals("mkdir")) {
if (spaceSplit[1].equals("-p")) {
for (int i = 3; i < spaceSplit.length; i++) {
}
} else if (spaceSplit[1].contains("/")){
//This method will create a directory farther down the tree like creating c in a/b/c
String[] dirSplit = spaceSplit[1].split("/");
int length = dirSplit.length;
FileSystem.mkdir(dirSplit[length-1]);
int directoriesLength = FileSystem.directories.size();
for(int i = 0; i < FileSystem.directories.size(); i++){
if(dirSplit[length-2].equals(FileSystem.directories.get(i))){
FileSystem.directories.get(i).addChild(FileSystem.directories.get(directoriesLength-1));
//Checking if this works
System.out.println("The child was created succesfully");
}
}
} else {
for (int i = 1; i < spaceSplit.length; i++) {
FileSystem.mkdir(spaceSplit[i]);
}
}
} else if (spaceSplit[0].equals("cd")) {
FileSystem.cd(spaceSplit[1]);
} else if (spaceSplit[0].equals("pwd")) {
FileSystem.pwd();
} else if (spaceSplit[0].equals("ls")) {
} else if (spaceSplit[0].equals("edit")) {
String name = spaceSplit[1];
boolean endOfFile = false;
String content = "";
while(endOfFile == false){
String userInput = s.next();
content += userInput;
if(content.contains("<<EOF>>")){
endOfFile = true;
}
}
FileSystem.edit(name, content);
} else if (spaceSplit[0].equals("cat")) {
for(int i = 1; i < spaceSplit.length; i++){
FileSystem.cat(spaceSplit[i]);
}
} else if (spaceSplit[0].equals("updatedb")) {
} else if (spaceSplit[0].equals("locate")) {
} else if (spaceSplit[0].equals("exit")) {
exitProg = true;
System.out.println("Good bye!");
} else {
System.out.println("That is not a command. Please try again.");
}
} while (exitProg == false);

Alright, well I guess I'll answer my own question here. Everything works perfectly now.
else if (spaceSplit[0].equals("edit")) {
if(spaceSplit.length > 1) {
String name = spaceSplit[1];
boolean endOfFile = false;
String content = "";
while (!(content.contains("<<EOF>>"))) {
String userInput = s.nextLine();
content += userInput + " ";
}
String end = "<<EOF>>";
content = content.replace(end, "");
int size = tree.getTexts().size();
if (size != 0) {
for (int i = 0; i < size; i++) {
if (tree.getTexts().get(i).getName().equals(name)) {
tree.getTexts().get(i).setContent(content);
}
}
tree.edit(name, content);
} else {
tree.edit(name, content);
}
}
}

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.

How do I prevent a array resetting in tomcat?

I am working on a hangman project for school that is due tomorrow and I am using embedded tomcat in java. My program is currently able to accept an input from the servlet and and generate random word from a list that can remain constant while the page reloads. However every time I compare the letter input to the string (it is supposed to add the letter to a char array at the correct index location) it refreshes every time the page reloads so the word in the char array will never be complete- if that makes any sense :(
Here is the code:
private static String currentWord = gameWord();
private static final char[] untilEmpty = new char[currentWord.length()];
String temp = req.getParameter("Word");
if (temp == null) {
currentWord = gameWord();
} else {
currentWord = temp;
}
for (int i=0; i< currentWord.length();i++){
untilEmpty[i] = '_';
}
System.out.println(currentWord);
out.write("<form method=\"get\" action=\"game\" >".getBytes());
out.write("<p> Guess a letter:</p>".getBytes());
out.write("<input type=\"text\" name=\"Guess\">".getBytes());
out.write("<input type=\"submit\" value=\"enter here\">".getBytes());
out.write(String.format("<input type=\"text\" name=\"Word\" value=\"%s\">", currentWord).getBytes());
out.write("</form>".getBytes());
String letter = "";
boolean integer = false;
try {
letter = req.getParameter("Guess");
integer = validateString(letter, 0);
} catch (Exception e) {
}
//String untilEmpty = currentWord;
String subStr = "";
String Empty = currentWord;
if (integer == false) {
out.write("invalid input".getBytes());
} else {
//while (untilEmpty != "") {
char letterChar = letter.charAt(0);
if (currentWord.indexOf(letterChar) >= 0) {
int count = currentWord.length()- currentWord.replaceAll(letter,"").length();
System.out.println(count);
Empty = Empty.replaceAll(letter,"");
System.out.println(Empty);
for (int i =0; i<currentWord.length(); i++){
if (currentWord.charAt(i) == letter.charAt(0)){
untilEmpty[i]= letterChar;
//untilEmpty.indexOf(letter);
//untilEmpty[i] = untilEmpty+letter;
//untilEmpty = untilEmpty.substring(i)+letter.charAt(0);
}
}
System.out.println(untilEmpty);
} else {
System.out.println("incorrect guess");
}
}
System.out.println(letter);
if (Empty == "") {
System.out.println("guessed whole word :)");
I've never used embedded Tomcat but you could try to save state in the Session

How to handle: java.lang.ArrayIndexOutOfBoundsException: 1

I have a program that takes in a file of unindented code and comments the program takes the specified file and will output an indented version of the code.
I keep on getting the java.lang.ArrayIndexOutOfBoundsException: 1 error. This seems to occur when I have only one comment on a line as for when it splits the string the index only takes up 0. I have got an if statement in place to handle a comment on a line on its own but it still throws the exception.
Would I need to implement an if statement to check whether or not the split string has more than 1 part to it?
import java.io.*;
import java.util.*;
class Program
{
public static int spaces = 0;
public static int longestLine = 0;
public static int commentSpaces;
public static String beforeComment;
public static String afterComment;
public static void main(String args[]) throws FileNotFoundException
{
Scanner input2 = new Scanner(new File("C:\\Users\\James\\Music\\code.java")); //get text from file
while (input2.hasNextLine() == true) { //get the longest line
String text = input2.nextLine();
if (text.contains("//")) {
if (text.contains("\"//")) {
printLine(text);
}
String[] parts = text.split("//");
String codeOnly = parts[0];
if (codeOnly.length() > longestLine) {
longestLine = codeOnly.length();
}
}
else {
if (text.length() > longestLine) {
longestLine = text.length();
}
}
if (input2.hasNextLine() == false) {
break;
}
}
Scanner input3 = new Scanner(new File("C:\\Users\\James\\Music\\code.java"));
while (input3.hasNextLine()) { //indent comments
String text = input3.nextLine();
if (text.contains("}")) {
spaces -=2;
}
for (int i = 0; i < spaces; i++) {
System.out.print(" ");
}
if (text.startsWith("//")){
String justComment = text;
commentSpaces = longestLine - spaces + 6;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(justComment);
System.out.println(" ");
}
if (text.contains("\"//")) {
printLine(text);
}
if (text.contains("//")) {
String[] parts = text.split("(?=//)");
beforeComment = parts[0].trim(); // trim() to get rid of any spaces that are already present within the code
afterComment = parts[1];
printLine(beforeComment);
commentSpaces = longestLine - beforeComment.length() - spaces + 5;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(afterComment);
System.out.println();
}
else {
printLine(text);
System.out.println();
}
if (text.contains("{")) {
spaces +=2;
}
}
}
public static void printLine(String text) {
Scanner data = new Scanner(text);
while (data.hasNext()) {
System.out.print(" " + data.next());
}
}
public static void yesItContains() {
System.out.print("It contains a string");
System.exit(0);
}
}
I think that if text is "something//" meaning it is ending in a empty comment your parts will only have length 1. So yes, you need to check it, e.g. via afterComment = parts.length > 1 ? parts[1] : "";. Note that lines like "something // something else // blabla" might break that logic as well.

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