How to implement an input in a loop - java

I wanted to create a loop where I can input my name using a Scanner, but the system keeps spamming "Gimme your name" and doesn't leave me the chance to input my name. I want the system to output "Gimme your name" and wait for my input.
Scanner sc = new Scanner(System.in);
char reponse = 'O';
name = sc.nextLine();
while (reponse=='O')
System.out.println("Gimme your name! ");
name = sc.nextLine();
System.out.println("Hello "+name+"How are you doing ? \n Wanna retry ? (O/N)" );
reponse = sc.nextLine().charAt(0);

Try putting open close brackets around the while statement:
char reponse = 'O';
name = sc.nextLine();
while (reponse=='O') {
System.out.println("Gimme your name! ");
name = sc.nextLine();
System.out.println("Hello "+name+"How are you doing ? \n Wanna retry ? (O/N)" );
reponse = sc.nextLine().charAt(0); ```
}

Because there is not a open and close bracket, the way the code was written may be read from the compiler like:
while (respose == 'O') System.out.println("Gimme your name! ");
The ending semicolon would "combine" the two lines into one, per se.
Include the open and closed bracket after the while loop and at the end of the looping statements to fix.

Related

How to make do while loop after validating email address?

// My Scanner
Scanner input = new Scanner(System.in);
//using Do While Loop
do {
//Asking user to enter email
System.out.println("enter your email:");
//Read and safe input in to Var userEmail
String userEmail = input.next();
//Check for contains '#' and '.com' simbols
Pattern pattern = Pattern.compile("\\S+?#\\S+?\\.com");
//And it checking in users entered email
Matcher matcher = pattern.matcher(userEmail);
//if userEmail contain '#'and '.com' print next line
if (matcher.matches()) {
System.out.println("Matches"); // Prints this for this email
}
//if user put email with out '#'and'.com' print next line
else {
System.out.println("your email should
looks like this sample bob.Dillon#gmail.com");
}
// And here I have a problem don't know what to type in
// so that it starts looping until user input will be 100% correct.
} while(!matcher.matches());
Can someone help what needs to be done here while(here); to make it looping?
You want to see if the user entered anything in those fields. So, check like this:
if (INPUTVALUE.length > 0) { //THEY ENTERED SOMETHING
// do something
}
Then, put this in your while statement. Like so:
// My Scanner
Scanner input = new Scanner(System.in);
//using Do While Loop
do{
//Asking user to enter email
System.out.println("enter your email:");
//Read and safe input in to Var userEmail
String userEmail = input.next();
//Check for contains '#' and '.com' simbols
Pattern pattern = Pattern.compile("\\S+?#\\S+?\\.com");
//And it checking in users entered email
Matcher matcher = pattern.matcher(userEmail);
//if userEmail contain '#'and '.com' print next line
if (matcher.matches()) {
System.out.println("Matches"); // Prints this for this email
}
//if user put email with out '#'and'.com' print next line
else{
System.out.println("your email should
looks like this sample bob.Dillon#gmail.com");
}
//And here I have a problem don't know what to type in so that it starts looping until user input will be 100% correct
}while(INPUTVALUE.length > 0);
You need:
}while(INPUTVALUE.length > 0);
To break the loop:
Just erase all of the values that the user has entered at the end of the do. That way, INPUTVALUE.length < 0. That will break the loop ! Good luck !

I need help on the Java Scanner Code

So I need help on this code. This code is all in one so ignore the spaces but I need to write another scanner in the way bottom of the code and if I do add
String feeling = in.nextLine(); at the very end it does not work. I need a it so that I can write my feelings so that I can make jarvis answer but the string does not work and java ignores the string and goes right on to the next part. It starts from the middle.
Scanner in = new Scanner(System.in);
System.out.println("Type User Name:");
String userName = in.nextLine();
System.out.println("PASSWORD:");
int passcodeFromUser=in.nextInt();
int passcode = 2015;
if (passcodeFromUser == passcode) {
System.out.println("Welcome Mr." + userName + "!");
Random random = new Random(userName.hashCode());
System.out.println("Mr." + userName + ", You are now recognized and you are now able to command me.");
System.out.println("I was created by John Choi");
System.out.println("JARVIS stands for Just A Rather Very Intelligent System");
System.out.println("How are you today Mr." + userName + "?");
}
So if I add this code at the back it does not work. It ignores and says Oh. Mr is feeling.
String feeling = in.nextLine();
System.out.println("Oh. Mr." + userName + "is feeling" + feeling + ".")
That is because your nextInt invocation does not actually parse a line feed.
Quoting the API, Scanner#nextInt:
Scans the next token of the input as an int.
(focus on the token part here)
Here's one (but not the only) way to fix it:
Integer passcodeFromUser = null;
try {
passcodeFromUser= Integer.parseInt(in.nextLine());
}
catch (NumberFormatException nfe) {
// TODO handle non-numeric password
}
... instead of int passcodeFromUser=in.nextInt();.
You can also loop the parsing of the Integer so that you print an error message when catching the NumberFormatException and don't break the loop until you have a valid numeric passcode.
You can consume the \n character:
in.nextLine();
String feeling = in.nextLine();
So just putting in.nextLine() before the code you were going to add will easily fix your problem.

Java How to search a word from text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
edit: Write a program to read in 100 words from a file. Then, have the user search for a word until they enter 'quit'.
The program will read in up to 100 words from a file. The file may or may not contain 100 words but the array should hold up to 100 (if the list does not contain enough words, fill the rest of the array with empty strings).
After the file is read in, the program will prompt the user for a search string. The program will then search for the string and tell the user if the word was found or not. The program will continue to get search strings from the user until the user enters 'quit'
Hello I need help write a program to find a word from text file
the result should look like:
Enter a word to search for: taco
Word 'taco' was found.
Enter a word to search for: asd
Word 'asd' was NOT found.
and when user enter the word "quit" the program will quit
below is what I have so far and need help to complete
import java.io.*;
import java.util.Scanner;
public class project2 {
public static void main( String[] args ) throws IOException {
String[] list;
String search;
list = load_list( "words.txt" );
search = prompt_user( "\nEnter a word to search for: " );
while ( ! search.equals( "quit" ) ) {
System.out.println( "Word '" + search + "' was" +
( ( find_word( search, list ) ) ? "" : " NOT" ) +
" found." );
search = prompt_user( "\nEnter a word to search for: " );
}
System.out.println();
}
for(String s: list){
if(s.equals(search)){
//do whatever
}
}
Use this:
Scanner txtscan = new Scanner(new File("filename.txt"));
while(txtscan.hasNextLine()){
String str = txtscan.nextLine();
if(str.indexOf("word") != -1){
System.out.println("EXISTS");
}
}
The below code answers this question perfectly:
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("newFile.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
System.out.println("Word EXISTS in the file");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Word does not exist");
}
System.out.println("-------continue or quit--- enter continue or quit");
word = input.next();
}

Make an email list, by entering only recipient names

I want to make a simple code, that prompts you to enter names, separated by comma or just a space, and when you click enter, to take every one word you entered, and put a #gmail.com at the end of it, how can I do it?
That's what I have for now
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
String names;
System.out.println("Enter names: ");
names = input.next();
System.out.println(names + mail);
This should be everything you asked for, if you put a list of names separated by commas it will loop through them, otherwise it will just print a single name.
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
System.out.println("Enter names: ");
String names = input.next();
if(names.contains(",")) {
for(String name : names.split(",")) {
System.out.println(name + mail);
}
} else {
System.out.println(names + mail);
}
Hope that helps.
Not knowing what language this is, here's the pseudo-code:
names = input.next();
namesArray = names.split(" ") -- replace with your preferred delimiter
foreach name in namesArray
print name + mail

Why does the compiler complain "while expected" when I try to add more code?

Write a program with a word containing # character as an input. If the word doesn't contain #, it should prompt the user for a word with #. Once a word with # is read, it should output the word then terminate.
This is what I have done so far:
public class find {
public static void main(String[] args) {
System.out.println(" Please enter a word with # ");
Scanner scan = new Scanner(System.in);
String bad = "#";
String word = scan.next();
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
}
}
I can get it to terminate after a word containing "#" is given as input, but if I try to add a Scanner to the line after "please try again", it says while expected.
I think issue is you are missing surrounding braces for do/while:
do
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
while ( !word.contains( bad ));
should be:
do
{
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
}while ( !word.contains( bad ));
Some people may not like this, but my suggestion is always use open/close braces. In this case, for the code if/else also. It avoids lot of confusion.
This is where your problem lies:
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
You need to put braces from where the loop starts until it ends. |So this thing should like:
do {
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
} while(!word.contains(bad));
For Better Practice You should Check do...while loops here.
The problem with your code is it is not re-reading the word in your loop.
Modify your loop like this (minimum change to your code).
do {
word = scan.next();
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
}
while (!word.contains(bad));
And yes as others have pointed out try to use braces especially with nested constructs.
There are two issues.
Your code is not using the braces properly
you are not attempting to read the new word if right word is not entered.
Also I prefer while loop better in the case as opposed to do-while loop as below.
Scanner scan = new Scanner ( System.in );
String required= "#";
System.out.println( " Please enter a word with # " );
String word = scan.next() ;
//check if the right word(containing #) is entered,
//if not then loop until it is enteres
while((!word.contains(required)){
System.out.println( " Please try again " );
//read the new word as input from the user
word = scan.next() ;
}
//right word is entered, display it
System.out.println(word);
Also please note that when you use scan.next(), it reads each word separately if entered in the same line.

Categories