infinite while loop, .nextLine() user input - java

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.

Related

Palindrome Checker with nested loops thats checks the input and then flips its to compare

Im stuck on this, I need a code that use 2 nested loops for this assignment (there are other solutions, but I need to demonstrate my understanding of nested loops). But I just dont get it. The outer loop repeats the entire algorithm and the inner loop iterates half-way (or less) through the string. I am not sure on what I need to put inside the for loops. This is what I have so far. Any Assistance would be pleasured.
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String x = 0;
String y = input.length-1;
for (String i = 0; i < line.length-1; i ++){
for (String j = 0; j < line.length-1; j ++){
if (input.charAt(x) == input.charAt(y))
{
x++;
y--;
}
}
}
}
Example Output:
Enter a string: 1331
1331 is a palindrome.
Enter a string: racecar
racecar is a palindrome.
Enter a string: blue
blue is NOT a palindrome.
Enter a string:
Empty line read - Goodbye!
Your algorithm is flawed, your nested loop should be to prompt for input - not to check if the input is a palindrome (that requires one loop itself). Also, x and y appear to be used as int(s) - but you've declared them as String (and you don't actually need them). First, a palindrome check should compare characters offset from the index at the beginning and end of an input up to half way (since the offsets then cross). Next, an infinite loop is easy to read, and easy to terminate given empty input. Something like,
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string: ");
System.out.flush();
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
boolean isPalindrome = true;
for (int i = 0; i * 2 < line.length(); i++) {
if (line.charAt(i) != line.charAt(line.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.printf("%s is a palindrome.%n", line);
} else {
System.out.printf("%s is NOT a palindrome.%n", line);
}
}
System.out.println("Empty line read - Goodbye!");
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String reversedText ="";
for(int i=line.length()-1/* takes index into account */;i>=0;i++) {
reversedText+=line.split("")[i]; //adds the character to reversedText
}
if(reversedText ==line){
//is a palidrome
}
}
Your code had lot of errors. I have corrected them and used a while loop to check if its a palindrome or not. Please refer below code,
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
String line;
boolean isPalindrome = true;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
int x = 0;
int y = line.length() - 1;
while (y > x) {
if (line.charAt(x++) != line.charAt(y--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(line + " is a palindrome");
} else {
System.out.println(line + "is NOT a palindrome");
}
System.out.println();
}
}
}

Java string to array and replace a certain word from user to uppercase

Here is the full Question:
...
My Code
import java.util.Scanner;
import java.lang.StringBuilder;
public class javaAPIString {
public static void main(String[]args)
{
String SentenceFromUser = "";
String IndiWordFromUser = "";
/// String upper = IndiWordFromUser.toUpperCase();
//String[] words = SentenceFromUser.split("\\s+");
char ans;
Scanner keyboard = new Scanner(System.in);
do
{
final StringBuilder result = new StringBuilder(SentenceFromUser.length());
String[] words = SentenceFromUser.split("\\s");
System.out.println("Enter a sentence :");
SentenceFromUser = keyboard.nextLine();
System.out.println("Enter a word : ");
IndiWordFromUser = keyboard.next();
/// IndiWordFromUser = upper;
for(int i =0; i > words.length; i++ )
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
// System.out.println("The Output is : " + SentenceFromUser);
System.out.println("Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.");
ans = keyboard.next().charAt(0);
}
while ((ans == 'Y') || (ans == 'Y'));
}
}
My Output/ problem of my code :
Enter a sentence :
i like cookies
Enter a word :
cookies
The Output is : i like cookies
Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.
it returns the same original sentence without changing to Uppercase of the second input to replace to all CAPS.
I hope my solution will help you out! :)
import java.util.Scanner;
public class Solution {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
getTextFromUser();
}
private static void getTextFromUser() {
print("Enter Sentence Here: ");
String text = in.nextLine();
print("\nDo you want to capitalize words in sentence? Y/N: ");
while (in.nextLine().equalsIgnoreCase("y")) {
print("Enter Word: ");
print("Modified Text: " + changeWord(text, in.nextLine()));
print("\n\nDo you want to capitalize words in sentence? Y/N");
}
}
private static String changeWord(String text, String word) {
return text.replaceAll("\\b" + word + "\\b" /* \\b Means word
boundary */, word.toUpperCase()); // No validations done.
}
private static void print(String message) {
System.out.print(message);
}
}
Just some things:
please use java naming conventions for variables name
when you execute your code this instruction will overwrite the user input with an empty string.
IndiWordFromUser = upper;
String[] words = SentenceFromUser.split("\\s");... you are splitting an empty string the first time and the old sentence the other runs
The variable IndiWordFromUser is never read

How to end a do while loop with a user inputted string?

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"));

i'm trying to solve an algorithm with java and i find some issue

i'm taring convert this to a Java program :
$ java SpaceTravel
Welcome to the SpaceTravel agency
What do you want do? [h for help]
a
Unknown command. Type h for help
What do you want do? [h for help]
h
h: print this help screen
q: quit the program
What do you want do? [h for help]
q
Bye bye!
Now the problem that my program seem's do an infinite loop at the 2nd do while loop whatever is my choice i tried many algorithm's and steel wont work for me . here is my code :
package gesitionEleve;
import java.util.Scanner;
public class SpaceTravel {
public static void main(String[] args) {
System.out.print("Welcom to the SpaceTravel Agency\n");
int lafin = 0;
while (lafin != 1) {
int taill;
do {
System.out.print("What do you want to do [h for help] : ");
Scanner sc = new Scanner(System.in);
String test = sc.nextLine();
taill = test.length();
} while(taill == 0);
char choix = 0;
String test;
if (choix != 'h') {
do {
System.out.print("\nUknown command. Type h for help ");
System.out.print("\nWhat do you want to do : ");
Scanner sc1 = new Scanner(System.in);
test = sc1.nextLine();
choix = test.charAt(0);
} while(choix == 'h');
}
System.out.print("\nh : print this help page ");
System.out.print("\nq : quite the program ");
do {
Scanner sc1 = new Scanner(System.in);
test = sc1.nextLine();
choix = test.charAt(0);
switch(choix) {
case 'h' :
System.out.print("\nh : print this help page ");
System.out.print("\nq : quite the program ");
case 'q' :
System.out.print("Bye bye");
lafin++;
}
} while (choix == 'q' || choix == 'h');
}
}
}
The below program suits your needs:
import java.util.Scanner;
public class SpaceTravel
{
public static void main(String[] args) {
System.out.print("Welcome to the SpaceTravel Agency\n");
String str; //To avoid exception when user enters just an enter
while (true) { //infinite loop
char choix; //for getting a character
System.out.print("What do you want to do [h for help] : ");
Scanner sc = new Scanner(System.in);
str=sc.nextLine(); //get input
if(str.length()!=1) //If no characters or more than one character is entered,
{
System.out.println("Invalid Choice");
continue;
}
choix=str.charAt(0); //get char from str
if(choix=='q') //if char is q,break out of the while loop
break;
if (choix != 'h') { //if char is not h,print invalid input and continue the loop
System.out.println("\nUnknown command. Type h for help ");
continue;
}
System.out.print("\nh : print this help page ");
System.out.print("\nq : quit the program ");
}
}
}
You got the condition of that loop backwards.
If you want to leave the loop when 'h' is entered, it should be :
do {
System.out.print("\nUknown command. Type h for help ");
System.out.print("\nWhat do you want to do : ");
Scanner sc1 = new Scanner(System.in);
test = sc1.nextLine();
choix = test.charAt(0);
} while(choix != 'h');
Currently you are staying in the loop as long as 'h' is entered.
You should also note that test.charAt(0) would throw an exception if the user presses enter without typing any characters.

Infinite Loop not working

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
}
}

Categories