I'm fairly new at java and have a current assignment to take a given word, put the first word at the end, rebuild the word from reverse, and see if it's the same word as the original, such as: grammar, potato, uneven, dresser, banana etc. So far I have this:
Scanner input = new Scanner(System.in);
String original, reverse = "";
String exit = "quit";
int index;
System.out.println("Please enter a word (enter quit to exit the program): ");
original = input.next();
while (!original.equalsIgnoreCase(exit))
{
String endingChar = original.substring(0, 1);
String addingPhrase = original.substring(1);
reverse += endingChar;
for (index = addingPhrase.length() - 1; index >= 0; --index)
{
char ch = addingPhrase.charAt(index);
reverse += ch;
}
if (original.equals(reverse))
{
System.out.println("Success! The word you entered does have the gramatic property.");
}
else
{
System.out.println("The word you entered does not have the gramatic property."
+ " Please try again with another word (enter quit to exit the program): ");
}
original = input.next();
}
input.close();
When I run it and enter the word "banana," it properly recognizes that it is indeed the same backwards when the b is moved to the end, and does the same with the other words listed above, but when I enter a second word on the loop, it never recognizes it properly, and always responds with the print statement from the else block:
Please enter a word (enter quit to exit the program):
banana
Success! The word you entered does have the gramatic property.
banana
The word you entered does not have the gramatic property. Please try again
with another word (enter quit to exit the program):
I'm guessing it's something to do with either the way I made my for loop, or the way I asked for input at the end of the while loop, but like I said I'm fairly new and awful at debugging. Any help would be much appreciated, thanks a lot in advance.
You are changing string reverse in every iteration, but you are not clearing it. So before the end of the loop or at the beginning clear the string for example like so: reverse = "", and then it should be fine.
Just add reverse = ""; in the end of the while loop in order to set the variable reverse to its original state, i.e. empty string
Related
This is an implementation of the Hangman game. Once the user has uncovered the word, the program should exit, but it continues to prompt the user for input although all letters of the word have been correctly guessed.
How can I make the program exit properly once the word has been guessed?
The word to seach is for example no : Here is an illustration:
Enter your lettre:
n
The letter is OK !
n_
Enter your lettre:
o
The letter is OK !
no
Enter your lettre:
I don't understand why the loop continues ? Because I found the word...
Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Random r = new Random();
String[] arr = {"one", "no"};
String word = arr[r.nextInt(arr.length)];
char[] dash = word.toCharArray();
char[] charArr = word.toCharArray();
for(int i=0;i<dash.length;i++){
dash[i] = '-';
System.out.print(dash[i] + " ");
}
System.out.println("");
for(int i=0;i<3;i++){
System.out.print("Enter your letter : ");
char letter = input.next().charAt(0);
for(int j=0;j<charArr.length;j++){
if(letter == charArr[j]){
dash[j] = letter;
System.out.println("Ok ! ");
System.out.println(dash);
i--;
}
}
}
}
}
I share you the code here => https://repl.it/repls/BonyRevolvingOs
Thank you for your help.
Look at the block of code defining your inner loop:
for(int j=0;j<charArr.length;j++){
if(letter == charArr[j]){
dash[j] = letter;
System.out.println("Ok ! ");
System.out.println(dash);
i--; // What is this doing here?
}
}
At the bottom of that block is the line that's blowing up your program. Get rid of it. Your program never exits the loop because you keep resetting the value of the counter for your outer loop i to 0. Every time the loop increments itself normally to 1, you decrement it, so it's always going from 0 to 1 and back to 0.
Because 0 is less than 3, the loop keeps running. If a break statement depended on the value of that counter, it would not have changed the way your program operated at all. If you called break on some other basis, you could have exited, but you would still have had a fundamentally broken program.
This said, you still have a long way to go to get a working implementation of Hangman because as it stands, your user only has as many guesses as the word has letters If you guess wrong, even a single time, you can never complete the word.
You need to find a way to account for incorrect guesses (drawing the parts of the hanged man) and a way to detect and announce victory or failure (right now, your program just exits after two or three guesses whether or not the puzzle is solved). Work on those things, and if you need more help, post separate questions for each problem.
So, I posted this nearly identical code yesterday, asking about how to leave the punctuation at the end of a reversed sentence after using .split. I'm still struggling with it, but I'm also having another issue with the same code: And here is my screen shot http://i.stack.imgur.com/peiEA.png
import java.util.Scanner;
import java.util.StringTokenizer; // for splitting
public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";
}
System.out.println(backward); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case
} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
} // end class MyTokenTester][1]][1]
As you guys can probably see my from screen shot, when the user is prompted to add another sentence in, the previous sentence is read back again.
My questions are:
How do I use charAt to identify a character at an undefined index (user input with varying lengths)
How do I stop my sentence from reading back after the user decides to continue.
Again, as I said, I'd posted this code yesterday, but the thread died and I had additional issues which weren't mentioned in the original post.
To address part 2, if you want to stop the sentence from reading back previous input, then reset backward to an empty string, because as it stands now, you're constantly adding new words to the variable. So to fix this, add this line of code right before the end of your do-while loop,
backward = "";
To address part 1, if you want to check the last character in a string, then first you have to know what is the last index of this string. Well, a string has indexes from 0 to str.length()-1. So if you want to access the very last character in the user input, simply access the last word in your words array (indexed from 0 to words.length - 1) by doing the following,
words[count].charAt(words[count].length() - 1);
Note that count is simply words.length - 1 so this can be changed to your liking.
1) So you have this array of strings words. Before adding each word to the backward string, you can use something like: words[count].chartAt(words[count].length() - 1). It will return you the charater at the last position of this word. Now you are able to do you checking to know wether it is a letter or any special char.
2) The problem is not that it is reading the previous line again, the problem is that the backward string still has the previous result. As you are using a + operator to set the values of the string, it will keep adding it together with the previous result. You should clean it before processing the other input to have the result that you want.
here is your code:
import java.util.*;
public class main{
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String[] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
List<String> items = Arrays.asList(words);
Collections.reverse(items);
System.out.println(generateBackWardResult(items)); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
// i use quals ignore case, makes the code more readable
} while (!sentinel.equalsIgnoreCase("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
static String generateBackWardResult(List<String> input){
String result="";
for (String word:input){
result =result +" "+word;
}
return result;
}
} // end class MyTokenTester][1]][1]
there are also some thing to mention:
* never invent the wheel again! (for reverting an array there are lots of approaches in java util packages, use them.)
*write clean code, do each functionality, i a separate method. in your case you are doing the reverting and showing the result in a single method.
I am making a program that will read user input and determine with an if/else condition what to do. If the user hits just enter and doesn't type anything else in, I want to loop something through the if. If anything else is typed as an input, the program should exit back to a different menu.
Here is what I have so far:
Scanner scnr = new Scanner(System.in);
String choice = scnr.next();
if (choice.equals("")) {
...
}
else {
...
}
When I run through it, just pressing enter does not affect anything, it just makes the cursor advance to the next line in the console. However, when I type something in, the error part that sends it to the menu when anything else is typed in works just fine. I'm thinking I have to use something besides scnr.next(); but I don't know what that would be.
This is for an entry level class, and it requires that we use the scanner utility and not something more advanced. Thanks in advance.
do
{
//string variable used to take scanner input when
//looping generations
String choice = "";
printWorld( patternName, world, generationCounter);
System.out.println("Options");
System.out.println("(Enter): show next generation");
System.out.println("end(Enter): end this simulation");
System.out.print("Choice:");
choice = scnr.nextLine();
if (choice.length() == 0) {
//used as a filler array when the method
//next generation is called
boolean newWorld[][] = new boolean [world.length][world[0].length];
nextGeneration(world, newWorld);
for (int i=0; i<newWorld.length;i++){
for (int j = 0; j<newWorld[0].length; j++){
world [i][j] = newWorld[i][j];
}
}
generationCounter++;
System.out.println("went through");
} else {
generationKill = 1;
generationCounter = 1;
}
} while (generationKill !=1);
Try using scnr.nextLine(); instead of scnr.next();
The reason for this is because of tokens. next()'s documentation says:
public String next()
Finds and returns the next complete token from this scanner.
Token generally is separated by whitespaces ("\n", "\t", " ") and therefore will not recognize your "enter" or "\n" character as a token. Which is why it'll keep reading, thinking that you haven't entered any tokens.
nextLine() on the other hand will read until it finds a "\n" character. That means when you enter, it's reading in a "\n" character, thereby setting your choice to be "".
I am having a little problem with my code. Compiling and running works well, however, when I attempt to break out of the inner loop,
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
The code above is printing twice to the terminal when I only want it to print once.
I have a feeling that is a simple mistake with the way my brackets are aligned but I am having difficulty with figuring out how to do it. Any help would be greatly appreciated!
import java.util.Scanner;
public class GetGrade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 15;
int[] homework = new int[MAX];
int[] classwork = new int[MAX];
int[] lab = new int[MAX];
int[] test = new int[MAX];
int[] quizzes = new int[MAX];
int[] midterm = new int[MAX];
int[] fin = new int[MAX];
int hwCount, clCount, labCount, testCount, quizCount, midCount, finCount;
double hwTotal, clTotal, labTotal, testTotal, quizTotal, midTotal, finTotal;
double grade = 0;
String selection = "";
System.out.println();
System.out.println("Welcome to GetGrade!");
System.out.println();
while (true) {
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
selection = input.nextLine();
if (selection.equals("homework")) {
System.out.print("What percentange of your grade is homework? > ");
double hwPercent = input.nextDouble();
System.out.println("Now begin typing your grades. When you are finished, type -1.");
for (int i = 0; i < homework.length; i++) {
homework[i] = input.nextInt();
hwTotal = homework[i] * hwPercent;
grade += hwTotal;
if (homework[i] == -1) break;
}
}
}
}
}
It's just as trivial as it seems:
The call to input.nextInt(); in your inner loop does not include the newline.
So you are breaking of the innerloop, receiving the next line which only contains the newline - character in input.nextLine(); which is the remaining input of your "-1\n" line and proceed with the main loop again as it does not match "homework".
Try setting the conditional variable in your while loop to an actual boolean rather than true.
Also, when you invoke "break", you are only breaking out of the for loop. If you reassign a boolean variable to false at this point, you would exit the while loop completely.
Just before while loop ends, add a "Do you want to continue? (Y/N)" functionality.
If user enters "N" or anything else, execute another break. And that break will make you get out of the while loop.
The simple way to get your code working is to change
selection = input.nextLine();
to
selection = input.next();
next() only reads in a string value (which is what you are actually doing in your code) instead of the newline character as Peter has suggested.
So the an extra iteration of the while does not take place when you read the newline character.
When you use a scanner to read a line from the keyboard, it reads everything up to and including the newline character the user types to submit their input. So for example:
Type which category you want to add to.
Homework, Classwork, Labs, Test, Quizzes, Midterm, Final
>
If you type "homework" and then ENTER, the actual input becomes "homework\n". input.nextLine() will scan the input until it encounters the first newline character, '\n', which it will consume and then it returns everything up to that point (i.e. "homework").
Your problem here is that input.nextInt() does NOT consume a newline character, and so there is still a newline character in the input buffer by the time your while loop starts another round.
Now begin typing your grades. When you are finished, type -1.
> ...
> -1
=> User input is "-1\n"
-------------------------------
// Meanwhile, back in the code...
for (int i=0;i<homework.length;i++) {
homework[i] = input.nextInt(); // <--- This call consumes "-1" but leaves '\n'
hwTotal = homework[i] * hwPercent;
grade += hwTotal;
if (homework[i] == -1) break;
}
That newline is consumed by the next call to input.nextLine(), leaving the input buffer empty.
while (true) {
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
selection = input.nextLine(); // <--- This call consumes the leftover '\n' and returns the empty string
...
And because "" is not equal to "homework", the while loop goes around one more time, but this time the input buffer is empty, and so the call to input.nextLine() behaves as you would expect.
// selection is empty, so this condition fails and the program loops back around
if (selection.equals("homework")) {
...
There are two easy solutions to this problem. You can
Use Integer.parseInt(input.nextLine()) instead of input.nextInt()
Add an extra call to input.nextLine() at the end of your while loop to consume the final newline character
The first option is probably the most robust, and you get the added benefit of a run-time error being thrown if they do not give you a valid integer as input.
I want to write a program, which is checks an entered String of the user for a given char limits (10 chars for instance). If entered String is more than 10 chars, then the system should re-prompt again and again the user to enter the valid String (a word of 10 chars) until the user enter a valid string.
I have already some piece of code for it, but its not works yet, because I've no idea how to move process up to start (to the line 1) for re-prompt the user or there is other simple way?
System.out.print("Input: ");
String inputChars = Input.readString();
while (inputChars.length() > 10){
System.out.print("Input: ");
String inputChars = Input.readString(); // here is mistake now
}
System.out.print("Output: ");
System.out.print("The enter has 10 chars");
I just want to check the entered word, if is more than 10 chars, then just skip it and prompt the user again for entering a word which is not more than 10 chars. I'm not yet good in java, so if this question is stupid just explain me how to solve it. Thanks in advance
Look at your loop:
while (inputChars.length() > 10){
System.out.print("Input: ");
String inputChars = Input.readString();
}
The second line of the loop body redeclares the inputChars variable. You can't do that, as it's already in scope. You want to just replace the previous value:
inputChars = Input.readString();
You should also consider restructuring your code to avoid the duplication though:
String inputChars;
do {
System.out.print("Input: ");
inputChars = input.readString();
} while (inputChars.length() > 10);
Note how I've also renamed the Input variable to input to follow normal Java naming conventions. I'd actually probably change both input and inputChars to be more descriptive - in particular, there's no indication of what the input data is meant to mean at the moment.
Just remove the String in beginning:
while (inputChars.length() > 10){
System.out.print("Input: ");
inputChars = Input.readString(); // here is mistake now
}
By having String in beginning, you are attempting the redefine the same name variable again.
Change to:
String inputChars = ""
do {
System.out.print("Input: ");
inputChars = Input.readString();
} while (inputChars.length() > 10)
System.out.print("Output: ");
System.out.print("The enter has 10 chars");
Before, inputChars had already been declared before the loop, so you didn't need to redeclare the variable.
A do-while loop is a better construct here because it makes your intentions more clear and makes your code more clean.