How to keep a string input within a loop - java

I'm making a program that takes a string from the user and separates it word by word with a delimiter, and it's almost complete. However, after the first full loop, the next input from the user doesn't pass through the last while loop.
Here's the segment of code I'm talking about:
do
{
System.out.println ("\nEntered String: " + s1 + "\n");
while (input.hasNext())
{
word++;
System.out.println ("Word #" + word + ": \t" + input.next());
}
System.out.print ("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while (!s1.equals("q"));
I'm thinking that I need another while loop around the word increment and print line and have the continue sequence within the input.hasNext() loop, because that's how I got a similar program using int to work, but I'm not sure how that would work with strings.
Any advice?
EDIT: to clarify, right now the output of my code looks like this:
Enter a sentence: this is a sentence
Entered String: this is a sentence
Word #1: this
Word #2: is
Word #3: a
Word #4: sentence
Enter 'q' to quit, enter string to continue: another sentence
Entered String: another sentence
Enter 'q' to quit, enter string to continue:
I need 'another sentence' to print out like 'this is a sentence'

I do not understand exactly what's the problem since your code does not compile. But there is no need for another loop. Here is a bit of code that works:
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter a sentence:");
String s1 = scan.nextLine();
do
{
System.out.println("\nEntered String: " + s1 + "\n");
Scanner input = new Scanner(s1);
int word = 0;
while (input.hasNext())
{
word++;
System.out.println("Word #" + word + ": \t" + input.next());
}
System.out.print("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while(!s1.equals("q"));
scan.close();

You can try this if it works. It has the same results with the one you need.
Scanner scan = new Scanner(System.in);
String s1 = scan.nextLine();
do {
String input[] = s1.split(" ");
System.out.println ("\nEntered String: " + s1 + "\n");
for(int i = 0; i < input.length; i++) {
System.out.println ("Word #" + i+1 + ": \t" + input[i]);
}
System.out.print ("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while (!s1.equals("q"));

You are using
while (input.hasNext())
I suppose input is a Scanner object, so you should do something like this before using it (but before entering the loop):
Scanner input = new Scanner(System.in);

Instead of using scanner.next() in while loop, I would recommend doing the following API:
String.split
Scanner.nextLine
Something like this:
while(input.hasNextLine()) {
String line = input.nextLine();
String[] words = line.split("delimeter");
if(words.length < 1 || words[words.length - 1].equals("q")) {
break;
}
}

Related

Scanner loop breaks + Regex issue

This task is whether a word is a palindrome, and I use java 11.
After entering of the word with spaces the code gives me an answer, but while loop breaks and the code "finishes with exit code 0" If I choose word = sc.next(). But If I write word = sc.nextLine() - It executes well and begins loop again.
I can't understand why, cause I can't debug this part of code, It's just skipped. And I don't understand why this happens. So can somebody explain to me what am I doing wrong?
Maybe there's a way to avoid this spaces?
P.S. I'm new to programming. Thanks to everyone.
try {
Pattern pattern = Pattern.compile("[Y|y][E|e][S|s]");
while (true) {
String word = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter the word without spaces");
if (sc.hasNext("(?>\\p{Alpha})+")) {
word = sc.next();
System.out.println(word);
System.out.println("The word is correct");
String text2;
StringBuilder sb = new StringBuilder();
text2 = sb.append(word).reverse().toString();
if (word.equalsIgnoreCase(text2)) {
System.out.println("Yes, it's a palindrome." + " " + "Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
else {
System.out.println("No, it's not a palindrome." + " " + "Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
}
else {
word = sc.next();
System.out.println("It's not a word");
System.out.println("Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
}
}
catch (NoSuchElementException ex) {
System.out.println(ex.getMessage());
}
}
What can you improve in your regex, [Y|y][E|e][S|s]?
Use [Yy][Ee][Ss] instead. The [] specifies a character class and all the characters inside it mean one of them i.e. by default they come with an implicit OR. Check this to learn more about it.
How can you determine if the input contains space?
Pass " " to the function, String#contains to determine it.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a word without spaces: ");
String word = sc.nextLine();
if (word.contains(" ")) {
System.out.println("It's not a word");
} else {
System.out.println("The word is correct");
StringBuilder reverse = new StringBuilder(word).reverse();
System.out.println(word.equalsIgnoreCase(reverse.toString()) ? "Palindrome" : "Not a palindrome");
}
System.out.println("Want to try another one?");
System.out.print("Enter yes if you want to continue or any other symbol otherwise: ");
if (!sc.nextLine().matches("[Yy][Ee][Ss]")) {
break;
}
}
}
}
A sample run:
Enter a word without spaces: Hello World
It's not a word
Want to try another one?
Enter yes if you want to continue or any other symbol otherwise: yes
Enter a word without spaces: HELLO
The word is correct
Not a palindrome
Want to try another one?
Enter yes if you want to continue or any other symbol otherwise: YES
Enter a word without spaces: Malayalam
The word is correct
Palindrome
Want to try another one?
Enter yes if you want to continue or any other symbol otherwise: Yes
Enter a word without spaces: papa
The word is correct
Not a palindrome
Want to try another one?
Enter yes if you want to continue or any other symbol otherwise: n

java prompt + get number before get a string contain any space (one or more)

I need get a number from prompt, and juste after I need get a String list from prompt. I have a problem. Is it OK if the 1st question ask a string with nextLine() see this post.
Java code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();
System.out.println("Enter a name list:");
String nameList = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
input.close();
System.out.println(num + " * " + nameList + " ** " + lastName);
}
console result:
Enter a number:
2
Enter a name list:
Enter last name:
1st response is 2 + enter
but juste after 2 + enter, the program display Enter a name list:
Enter last name:
I would use input.next() instead of input.nextLine() as next blocks for user input while nextLine moves the scanner past the current line and it buffers all the inputs until it finds a line separator.
or use nextLine() after nextInt to consume the linefeed which is left by nextInt
Solution add input.nextLine(); juste after int num = input.nextInt();.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();
input.nextLine();
System.out.println("Enter a name list:");
String nameList = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
input.close();
System.out.println(num + " * " + nameList + " ** " + lastName);
}
console:
Enter a number:
2
Enter a name list:
aa bb cc
Enter last name:
dd
2 * aa bb cc ** dd

Ask user for numerical input and return character at that index?

I am stumped on how to go about completing this. The script needs to Ask the user for a sentence, tell them the length, return the character at that index, than ask them for a character and give the first location it appears. I just cant figure out how to use the numerical input to find return the character at that index. (I know its probably a simple answer).Everything else works.
public class Sentence
{
Scanner scan = new Scanner (System.in);
int sentlength;
int letterenter;
int lowerinput;
int letterloc;
String enterletter;
public void sentence()
{
System.out.print("Please enter a sentence");
String originalsent = scan.nextLine();
sentlength=originalsent.length();
System.out.println("The sentence is "+sentlength+" charecters long");
System.out.println("Please enter a number less than the length of the sentence");
lowerinput = scan.nextInt();
System.out.println("Please enter a charecter");
enterletter = scan.next();
letterloc = originalsent.indexOf(""+enterletter+"");
System.out.println(""+letterloc+"");
}
public static void main(String[] args)
{
Sentence worksheet= new Sentence();
worksheet.sentence();
}
}
I believe you are looking for something like this from your question
System.out.print("Please enter a sentence: ");
String originalsent = scan.nextLine();
sentlength=originalsent.length();
System.out.println("The sentence is "+ sentlength +" characters long");
System.out.println("Please enter a number less than the length of the sentence: ");
lowerinput = scan.nextInt();
System.out.println("The character at index " + lowerinput + " is " + originalsent.charAt(lowerinput));
System.out.println("Please enter a character: ");
enterletter = scan.next();
System.out.println("The first index " + enterletter + " shows up is at " + originalsent.indexOf(enterletter));
When run outputs the following
Please enter a sentence: the cow flew over the moon
The sentence is 26 charecters long
Please enter a number less than the length of the sentence:
5
The character at index 5 is o
Please enter a charecter:
o
The first indext o shows up is at 5
It's very easy :
System.out.println(originalsent.charAt(lowerinput));

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

Output line numbers parallel to output

thank you all for looking.
I am a beginner to Java and have been for a few years.
I am not looking for the answer but would like some to tips to finish my query.
I want to output line numbers with my out put of code in netbeans.
I am guessing a while loop would be sufficient.
I would like my output to look like the below example:
I am looking to add line numbers to my output like they are in bold below.
1: Enter a line
Some input
2: Enter another line
More input
3: Enter the last line
The end
The end,More input,Some input
HERE IS my code i would like to add to:
Scanner in = new Scanner(System.in);
String msg1, msg2, msg3;
System.out.println("Enter a line");
msg1 = in.nextLine();
System.out.println("Enter another line");
msg2 = in.nextLine();
System.out.println("Enter the last line");
msg3 = in.nextLine();
System.out.println(msg3 + "," + msg2 + "," + msg1);
This is what I am guessing i should add, however I may be totally wrong
int count = 0;
while (count ??????) {
count++;
System.out.println(count + "" + ?????????????());
}
Thank you in advance for any advice,
regards
Seems like your homework, but I would answer it anyway
Scanner in = new Scanner(System.in);
String msg1, msg2, msg3;
int count = 0;
System.out.println(++count + ": Enter a line");
msg1 = in.nextLine();
System.out.println(++count + ": Enter another line");
msg2 = in.nextLine();
System.out.println(++count + ": Enter the last line");
msg3 = in.nextLine();
System.out.println(msg3 + "," + msg2 + "," + msg1);

Categories