I've searched around and can't find a solution to my problem. For one of my courses I'm tasked with writing a simple console email system. When the user is prompted for a message body, the string variable that holds the input only takes one word, not the whole message. I read that I should use readLine(), but when the program prompts the user to enter a message body, it completely skips input for that segment. To remedy this, I read that I should place a skip("\n") before I read the line. Now, however, the program doesn't end after the user presses Enter. It just keeps taking input and won't let me do anything.
Here is a bit of the code to help:
Scanner in = new Scanner(System.in);
//Declare variables
String subject, reciepent, message = "";
//Get subject
System.out.println("> Enter subject: ");
subject = in.next();
//Get reciepent
System.out.println("> Enter reciepent: ");
reciepent = in.next();
//Get message
System.out.println("> Enter message: ");
in.skip("\n");
message = in.nextLine();
//Print out message to verify user input
System.out.println("> " + message);
I don't understand how nextLine() works for all the threads I searched, but not for me.
The solution to this problem is not to use the .skip() method, but use .nextLine() instead, which removes the trailing '\n' character from the input stream as you desire.
So change the line: in.skip("\n"); to in.nextLine();
Try using nextLine() which waits for user input and then returns the input. Your code should be like this:
Scanner in = new Scanner(System.in);
//Declare variables
String subject, recipient, message;
//Get subject
System.out.println("> Enter subject: ");
subject = in.nextLine();
//Get recipient
System.out.println("> Enter reciepent: ");
recipient = in.nextLine();
//Get message
System.out.println("> Enter message: ");
message = in.nextLine();
//Print out message to verify user input
System.out.println("> " + message);
How about
Scanner s = new Scanner(System.in);
String line = "";
while((line = s.nextLine()) != null) {
System.out.println("> Enter subject: ");
subject = in.nextLine();
//Get recipient
System.out.println("> Enter reciepent: ");
recipient = in.nextLine();
//Get message
System.out.println("> Enter message: ");
message = in.nextLine();
//Print out message to verify user input
System.out.println("> " + message);
}
Related
Hey guys any help would be appreciated.
I've created some code that allows me to take user input from terminal, and saves it into a txt file in the same directory. The issue is that only 1 name and surname is stored each time. when i open a new client and type a different name, it will just overwrite the original one. not sure what is the cause as i was under the impression that the out.newline would solve this issue.
public void userinput()
{
try
{
out = new BufferedWriter(new FileWriter("TESTING.txt"/*,true*/));
//
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//ask for first name
System.out.println("Please enter your first name: ");
Name = input.nextLine();
//ask for surname
System.out.println("Please enter your last name: ");
Surname = input.nextLine();
//write names into txt file
out.write(Name + " - " + Surname);
//print welcome message with names into console for user
System.out.println("Welcome " + Name + Surname);
out.newLine();
out.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
}
thanks for the help!
This is happening simply because you didn't open your FileWriter in the append mode, so it doesn't overwrite the file every time. To do this, you have to call the constructor as new FileWriter("TESTING.txt", true). Just uncomment the true and it'll work. I'm guessing at some point you accidentally commented that out.
My objective is to create a method in which a user inputs their first name and last name, and with this information a .txt file will be created and named using the first initial of the first name and the last name. For example if user enter Marcus Simmon, the text file created should be named "MSimmon.txt" and how would I be able to return this file name. Thank you in advance. This is my code so far...
public static String GetUserInfo() {
// complete with your code of the method GetUserInfo
Scanner input = new Scanner(System.in);
System.out.println("Please enter your first name: ");
char initial = input.next().charAt(0);
System.out.println("Please enter your last name: ");
String lastName = input.nextLine();
try{
FileWriter x = new FileWriter(initial + lastName + ".txt");
}
catch(IOException e){
System.out.println("ERROR");
}
}
I know this might seem like a simple/silly question, but I am trying to keep my code as organized and simple as possible. The problem that I am having is with a while loop for validation. I am validating a string input. I am using the validation simply to make sure that something is entered. The only time I would like the while loop to run is when no information is entered at all, so I would like to include every character and symbol. The question that I have, is that I am wondering if there is a shorter way to include every character possible except for simply hitting enter of course. Here is the simple code snippet.
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");
System.out.print("Please enter your name: ");
String email = input.nextLine();
while(!email.matches("[a-zA-Z]+"));
{
System.out.println("\nPlease enter a valid E-Mail.");
email = input.nextLine();
}
out.println("E-Mail: " + email);
What about restructuring it as a do-while and only having one print/scan?
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");
String email;
String prompt = "Please enter your name: ";
do {
System.out.print(prompt);
email = input.nextLine();
prompt = "\nPlease enter a valid E-Mail.\n"
} while (!email.matches("[a-zA-Z]+"));
out.println("E-Mail: " + email);
I am getting user input for the string variable street and trying to check whether it contains only strings and no special characters. And then I am assigning it to a string variable "street". But when the user types, for example "La Jolla" it considers only "La" and ignores "Jolla". How should I modify the code so that it checks for valid input string and also considers space and assigns street variable with "La Jolla" and also if the street name is just "Montclair" without any more words
System.out.println("Please enter the street name>> " );
while(!sc.hasNext("[a-zA-Z]+")){
System.out.println("Please enter a valid street name>> " );
sc.next();
}
String street = sc.nextLine();
hasNext("[a-zA-Z]+") only checks if there is a token matching your expression, not if an entire line is available.
next() gets the next token from the scanner, not next line.
No real use for Scanner in this scenario.
This will work:
BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); // Optionally add a charset as 2nd parameter.
String street;
while (true) {
System.out.println("Please enter a valid street name>> " );
try {
String line = r.readLine();
// Accept a line with alphabetic characters delimited with space.
if (line.matches("[A-Za-z ]+$")) {
street = line;
break;
}
} catch (IOException e) {
// Handle broken input stream here.
street = "";
e.printStackTrace();
break;
}
}
System.out.println(street);
sc.next() finds and returns the next complete token from the current scanner 'sc'.
Scanner has a method nextLine() which advances the scanner past the current line and returns the input that was skipped.
You need to use nextLine() in your case , so you can get past the interval.
You can do that with simple code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the street name>> ");
String street = sc.nextLine();
while (!isAlphabet(street)) {
System.out.println("Please enter a valid street name>> ");
street = sc.nextLine();
}
System.out.println(street);
sc.close();
}
public static boolean isAlphabet(String s) {
return s.matches("[a-z A-Z]+");
}
Output
> Please enter the street name>>
> La Jolla%
> Please enter a valid street name>>
> La Jolla
> La Jolla
To briefly explain, I'm supposed to get the user to enter the name of the
recipient of a message, and then get them to enter the message body, which can
have multiple lines. If they enter a blank line, then the message body ends and
they can select another case in the switch.
case 'S':
case 's':
if(user.equals(" ")) {
System.out.println("No user logged in.");
} else {
System.out.println("Recipient: ");
recip = menuScan.next();
m = new Message(user,recip);
System.out.println("Enter message. Blank line to quit.");
mbody = menuScan.nextLine();
while(!mbody.equals("")) {
mbody = menuScan.next();
m.append(mbody);
}
ms.deliver(m);
System.out.println("Messgae sent.");
}
break;
But as it is now, the while loop is skipped completely. I've tried changing recip to menuScan.nextLine(), and mbody to menuScan.next() and .nextLine(), but the only other thing that happens is the message body goes on forever.
I've also tried using two different Scanner objects for recip and mbody, but no luck there, either.
You should replace your next by nextLine. next, as the documentation states, returns the next token if it matches the pattern constructed from the specified string, which is not what you want.
Try the following:
System.out.println("Recipient: ");
recip = menuScan.nextLine();
m = new Message(user,recip);
System.out.println("Enter message. Blank line to quit.");
mbody = menuScan.nextLine();
while(!mbody.equals("")) {
m.append(mbody);
mbody = menuScan.nextLine();
}
ms.deliver(m);
System.out.println("Messgae sent.");
I've tried this piece of your code
System.out.println("Enter message. Blank line to quit.");
mbody = menuScan.nextLine();
while (!mbody.equals("")) {
mbody = menuScan.next();
m.append(mbody);
}
changing it a bit
System.out.println("Enter message. Blank line to quit.");
mbody = menuScan.nextLine();
while (!mbody.equals("")) {
m.append(mbody);
mbody = menuScan.nextLine();
}
This way the loop is executed and exited as expected.
I have used java.util.Scanner