public static void main (String[] args)
{
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();
System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();
int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}
System.out.println(letter + " appears " + amount + " times in " + sentence);
System.out.print("Continue? ");
String decide = keyboard.nextLine();
} while (decide.equals("yes"));
}
}
I want the user to input either "yes" or "no" at the end of the loop, then I want that input to determine whether or not the program will loop again. As it stands right now, the the last line of my code isn't working. I've looked around and I'm not sure what I should do to fix this.
You need to declare your variable decide outside the loop and initialize inside:
String decide;
do {
//do something ...
decide = keyboard.nextLine();
} while (decide.equals("yes"));
You should use keyboard.next() to read a String instead of keyboard.nextLine()
next() only reads a word, nextLine() reads the whole line including Enter so it will never be equal to "yes"
You must declare declare the string describe outside of the do/while loop, otherwise it is a local variable of the do/while loop, and cannot be accessed by the do testing portion. Simply using
public static void main(String[] args) {
String decide;
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();
System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();
int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}
System.out.println(letter + " appears " + amount + " times in "
+ sentence);
System.out.print("Continue? ");
decide = keyboard.nextLine();
} while (decide.equals("yes"));
}
will solve your problem.
You has to define your variable decide outside of the loop:
String decide = null
do {
....
decide = keyboard.nextLine();
} while (decide.equals("yes"));
Related
So the problem that I am currently running into is that the statement "Enter your command (reverse, replace first, replace last, remove all, remove)" is printing twice after I go through all the steps.
What I believe is happening is the loop is executing twice but I don't know why. Any help would be appreciated in solving this problem. Sorry in advance if my code formatting is bad still learning how to properly format.
import java.util.Scanner;
public class StringChangerenter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
// While loop
while (!command.equalsIgnoreCase("quit")) {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
// Bracket for while loop
}
}
}
The reason you are getting two entries after you've processed a character, is that you have not fully read the line containing the character.
Specifically, you use keyboard.nextInt(); in the upper branch, and keyboard.next(); in the lower branch. While these read the next integer and character, respectively, they do not process the end of line marker.
Then when you reach the top of the loop, you call keyboard.nextLine() which processes whatever characters occurred after the int (or character, in the remove all case) until the end of line marker. With the expected user input, that's just an empty string.
To fix this, you need to ensure you read all the way through the keyboard.nextLine() in the cases where you are reading only integers, or a single character.
what is happening is, the condition for you while loop is
while (!command.equalsIgnoreCase("quit"))
which in english mean, as long as command is not equal to "quit" then run this loop.
Inside the loop, command is never actually set to "quit". ex if I give input string as "abcde" and ask to remove "c" at position 1.
Then your logic sets command to "remove" here
command = keyboard.nextLine();
and then prints the final value as "abde". Now when the loop ends, command is still "remove" and hence the loop executes again.
A possible solution is to explicitly ask the user if he wants to retry using a do while loop. Also just a tip, i see you have used nextInt. It is advisable to use a nextLine immediately after next int. see this for the reason why: Java Scanner doesn't wait for user input
this is what you code would be if you explicitly took user consent if you want to run any more commands:
public static void main (String[] args) throws java.lang.Exception
{
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
String retry = "";
// While loop
do {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
keyboard.nextLine();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
System.out.println("Do you want to go again?");
retry = keyboard.nextLine();
// Bracket for while loop
}while("yes".equalsIgnoreCase(retry));
}
Below is the code that I wrote in order to have a user input a few different strings, check if each is a palindrome, and only return the palindrome. Currently, all of the entered in strings will be returned. It seems that the IF statement if not working correctly. Any suggestions on how to have the correct strings returned?
import java.util.Scanner;
public class hh {
static void checkPalin () {
// creates a scanner
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";
// asks the user for the number of strings
System.out.print("Enter the number of strings: ");
StringBuilder sentence = new StringBuilder(userInput);
StringBuilder palindrome = new StringBuilder();
// stores the number of strings user will enters
int stringNumber = input.nextInt();
// prompts the user to enter in their sentences
System.out.println("Enter the strings:");
// this loop will go until the number of strings entered are entered
while(i <= stringNumber){
userInput = input.nextLine();
if(sentence.reverse().equals(sentence)){
palindrome.insert(0, " " + userInput);
}
i ++;
}
// if( sentence == sentence.reverse()){
System.out.println("The palindromes are: " + palindrome);
}
public static void main(String[] args) {
checkPalin();
}
}
You need to create the String from the StringBuilder using the toString method before calling equals:
if(new StringBuilder(userInput).reverse().toString().equals(userInput)) { ... }
When you declare
StringBuilder sentence = new StringBuilder(userInput);
The "sentence" variable will not change if userInput changes. You need to recreate the StringBuilder each time you need it.
Here is the fixed code :
static void checkPalin() {
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";
System.out.print("Enter the number of strings: ");
StringBuilder palindrome = new StringBuilder();
int stringNumber = input.nextInt();
System.out.println("Enter the strings:");
while (i <= stringNumber) {
userInput = input.nextLine();
String reversed = new StringBuilder(userInput).reverse().toString();
if (reversed.equals(userInput)) {
palindrome.insert(0, " " + userInput);
}
i++;
}
System.out.println("The palindromes are: " + palindrome);
}
You have to write something like
new StringBuilder(sentence.toString()).reverse().equals(sentence)
in your if
The code works the first time through. But after that, the output doesnt work.
The main goal of this is to create an infinite loop, of asking a user for a phrase, then a letter. Then, to output the number of occurences of the letter in the phrase.
Also - - how would i go about breaking this loop by entering a word?
Scanner in = new Scanner(System.in);
for (;;) {
System.out.println("Enter a word/phrase");
String sentence = in.nextLine();
int times = 0;
System.out.println("Enter a character.");
String letter = in.next();
for (int i = 0; i < sentence.length(); i++) {
char lc = letter.charAt(0);
char sc = sentence.charAt(i);
if (lc == sc) {
times++;
}
}
System.out.print("The character appeared:" + times + " times.");
}
Remove the for loop and replace it with a while.
The while loop should check for a phrase and it will drop out automatically when the phrase is met.
So something like
while (!phraseToCheckFor){
// your code
}
This sounds like homework so I won't post all the code but this should be enough to get you started.
If you need an infinite loop, just do this:
for(;;) { //or while(true) {
//insert code here
}
You can break the loop by using the break statement, for example like this:
for(;;) {
String s = in.nextLine();
if(s.isEmpty()) {
break; //loop terminates here
}
System.out.println(s + " isn't empty.");
}
In order for your program to run correctly, you need to consume the last new line character. You can do this by adding a call to nextLine.
Working example,
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (;;) {
System.out.println("Enter a word/phrase");
String sentence = in.nextLine();
if (sentence.trim().equals("quit")) {
break;
}
int times = 0;
System.out.println("Enter a character.");
String letter = in.next();
for (int i = 0; i < sentence.length(); i++) {
char lc = letter.charAt(0);
char sc = sentence.charAt(i);
if (lc == sc) {
times++;
}
}
System.out.println("The character appeared:" + times + " times.");
in.nextLine();//consume the last new line
}
}
I am trying to make some kind of 'Evil Hangman game' (nifty Stanford CS exercises). The purpose of the game is to 'cheat' by removing as many possible word solutions as possible so the user cannot guess before the very end.
I have made a loop (below) which seems to remove many of the words possible words but for some reason it does not remove all of them. The input is a dictionary.txt file which contains about 120K words.
When I 'guess' the letter "a" it will take away roughly 60-70% of the words with "a" in them (estimate based on comparisons between the output with the first couple of words in the txt file)
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
I am aware that my code is a bit messy at this point, I am trying to improve everything about my programming so all feedback is greatly appreciated! I have the feeling that I am including stuff that does not have to be there and so on.
I will post the whole code below in case that helps:
import java.util.*;
import java.lang.*;
import java.io.*;
public class EvilHangman
{
public static void main(String[] args) throws IOException
{
// declaring variables
int wordLength;
int guessNumber;
// initiate the scanner
Scanner keyboard = new Scanner( System.in );
// introduction and prompting the user for word length
System.out.println("Welcome to Hangman. Let's play! ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
// prompt the user for number of guesses
System.out.println("How many guesses do you want to have? ");
guessNumber = keyboard.nextInt();
while(guessNumber < 0)
{
System.out.println("Number of guesses has to be a postive integer. ");
System.out.println("Please enter the desired number of guesses: ");
guessNumber = keyboard.nextInt();
}
// count the number of words with the specified length
/* int wordCount = 0;
String word = null;
while ( textScan.hasNext() )
{
word = textScan.next();
if (word.length() == wordLength)
{
wordCount++;
}
}
*/
// prompts the user whether he/she wants a running count of word length - using next() instead of nextLine() to clear buffer
/* System.out.println("Do you want a running total of number of words remaining? ");
String runningTotal = keyboard.next();
if (runningTotal.equalsIgnoreCase("yes"))
System.out.println("Words with that length: " + wordCount);
*/
// create a list (array) of all the words that matches the input length
String word = null;
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
System.out.println(wordList);
Finally figured out it had to do with the scanner. It had to be initiated inside the loop
for(int i = 1; i <= guessNumber; i++)
{
Scanner textScan2 = new Scanner(file1);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
//System.out.print(guess);
while ( textScan2.hasNext() )
{
String word1 = textScan2.next();
if (wordLength != word1.length() || (word1.contains(guess)))
{
wordList.remove(word1);
}
}
}
Hi I have a question regarding the use of .nextLine and why it skips user input the second time around during the infinite loop. The .next function (letter input) still asks for user input everytime but the .nextLine function (phrase input) does not. Thanks.
import java.util.Scanner;
public class Lab6 {
public static void main (String [] args) {
Scanner in = new Scanner(System.in);
String phrase, l;
char letter;
while (true) {
System.out.println("Enter a phrase. Enter 'quit' to quit.");
phrase = in.nextLine();
if (phrase.startsWith("quit")) {
break;
}
System.out.println("Enter a letter");
l = in.next();
letter = l.charAt(0);
System.out.println("Phrase entered is: " + phrase);
System.out.println("Letter entered is: " + letter);
int i = 0;
int count = 0;
while (i < phrase.length()) {
if (phrase.charAt(i) == letter) {
count++;
}
i++;
}
System.out.println(count);
}
}
}
The reason is that Scanner.next() does not consume newline characters from the system input, so the input will be passed through to the statement:
phrase = in.nextLine();
which will now not block having received the input.