This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I have a rudimentary piece of code that's meant to update a properties file. However, it seems that of the two possible keywords to update, only the second is updated by the user's input, as opposed to one after the other.
Here is the full code:
import java.io.*;
import java.util.Properties;
import java.util.Scanner;
public class UpdateProperty{
private static int choice;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws Exception
{
FileInputStream in = new FileInputStream("Stats.properties");
Properties props = new Properties(); //creates a Properties object named prop
props.load(in); //loads in as value of prop
in.close(); //no idea
System.out.println("1- BlackBerryIzzie: " + props.getProperty("BlackBerryIzzie"));
System.out.println("2- GrapeFruitIzzie: " + props.getProperty("GrapeFruitIzzie"));
System.out.println("");
String blackAmount = props.getProperty("BlackBerryIzzie");
String grapeAmount = props.getProperty("GrapeFruitIzzie");
//System.out.println("Selling BlackBerry Izzie");
//blackAmount = itemSold(blackAmount);
System.out.println("Do you wish to update inventory? Type 2");
choice = sc.nextInt();
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
}
public static String itemSold(String s){
int i=Integer.parseInt(s);
i -= 1;
String ret=Integer.toString(i);
return ret;
}
}
The bit that seems to be malfunctioning:
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
This is meant to ask the user for blackberry amount, then update the BlackBerryIzzie keyword to that amount. Then, it is meant to do the same for grapefruit after blackberry is done. However, it skips blackberry and only asks for one scanner input and sets grapefruit to that.
Thanks for your time!
Don't mix nextLine and nextAnythingElse.
The solution is to set your scanner's delimiter to what you want. You want 'user presses enter' to be the delimiter, surely. So, tell scanner that. Run scanner.useDelimiter("\\R") immediately after making it. Then, to get 'an entire line', call .next(), if you want that line to be read as e.g. an int, call .nextInt(), etc. Don't call nextLine() for anything.
Explaining why mixing nextLine and nextAnythingElse is bad is a bit of a story - this SO answer explains part of it. Unfortunately the 1000-vote accepted answer is not the right solution (.useDelimiter("\\R") and then .next() to read a line is the right solution).
Related
I need to do the following exercise:
a) Make a new text file
b) Put the user's input into that text file
c) we must save all user's input while user keeps typing but as soon as user pressing Enter in a new line (When an empty string is sent) the user must get out of the program.
For coding this issue I have write the following codes, but when
I try it by myself so I am stuck at while loop, cant get out when I sending empty string.
So could anyone help with a solution for this issue?
Thanks
I have tried some of the solutions I have found on youtube like making if statement inside the while loop or adding the code that takes the input of the user inside the loop's condition.
So I do not know what to do at the next stage.
I tried to see the console window via the Eclipse output.
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
while (true) {
Scanner input = new Scanner(System.in);
str = input.next();
pw.println();
if (str.equals(null)) {
break;
}
}
pw.close();
System.out.println("Done");
}
}
The user must get out of the loop when he/she sends an empty string. and the writing to the file must be finished.
First the code, then the explanation...
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lesson {
public static void main(String[] args) {
File file = new File("mytext.txt");
try (Scanner input = new Scanner(System.in);
PrintWriter pw = new PrintWriter(file)) {
System.out.println("Enter a text here: ");
String str = input.nextLine();
while (str.length() > 0) {
pw.println(str);
pw.flush();
str = input.nextLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
System.out.println("Done");
}
}
The above code requires at least Java 7 since it uses try-with-resources. Scanner should be closed, just like PrintWriter should be closed. The try-with-resources ensures that they are closed. Note that if file mytext.txt doesn't exist, creating a new PrintWriter will also create the file and if the file already exists, its contents will be removed and replaced with the text that you enter.
After that the prompt is displayed, i.e. Enter a text here, and the user enters a line of text. Method nextLine() will get all the text entered until the user presses Enter. I read your question again and the program should exit when the user presses Enter without typing any text. When the user does this, str is an empty string, i.e. it has zero length. That means I need to assign a value to str before the while loop, hence the first call to method nextLine() before the while loop.
Inside the while loop I write the value entered by the user to the file mytext.txt and then wait for the user to enter another line of text. If the user presses Enter without typing any text, str will have zero length and the while loop will exit.
Written and tested using JDK 12 on Windows 10 using Eclipse for Java Developers, version 2019-03.
To achieve this, we check is length of input is >0:
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
Scanner input = new Scanner(System.in);
while ((str = input.nextLine()).length() > 0) {
//str = input.next();
pw.println(str);
}
pw.close();
System.out.println("Done");
}
}
I'm doing a small project and I have everything done, just one small error. the error shows "symbol not found" and shows the red squiggly line under my scan.
package pkgif.elsestatements.java;
import java.util.Scanner;
public class IfElseStatementsJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String your_name;
System.out.print("What is your name?");
your_name = user_input.next();
System.out.println("Hi " + your_name);
String user_input2;
System.out.print(".");
user_input2 = user_input.next();
System.out.println("Do you like Gospel Music Paul?"); //Asks question
String input = scan.nextLine(); //Waits for input
if (input.equalsIgnoreCase("Yes")) { //If the input is Yes)
System.out.println("Here are some songs; Amazing Grace, I'll Fly Away, A Little Talk With Jesus ");
}
else { //If the input is anything else
System.out.println("Ok! Have a nice day!");
}
}
this line is the one giving me trouble ---- String input = scan.nextLine(); //Waits for input
I was feeling really great about finish this with no errors beforehand, then this. Any help is appreciated.
According to the code above. You've defined Scanner user_input = new Scanner(System.in); i.e. user_input as the oject ref.
So, changing String input = scan.nextLine(); to String input = user_input.nextLine(); should do.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I am just learning HashMaps, and have just written my first program using them. For some reason, my check to determine if the inputs I've entered match up with the key and it's corresponding value always returns false. Can anyone tell me why that is?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) throws FileNotFoundException {
HashMap<String, String> userPass = new HashMap<String,String>();
HashMap<String, String> userFull = new HashMap<String, String>();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename to read from: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String fullname=inputFile.next()+" "+inputFile.next();
String username=inputFile.next();
String pass=inputFile.nextLine();
userPass.put(username, pass);
userFull.put(username, fullname);
}
inputFile.close();
//initialize variable for use after loop
String inputUsr = null;
//checks if key/value is found
boolean b=false;
int tries=1;
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.next();
System.out.print("\nPassword: ");
String inputPass=keyboard.next();
//if inputted password equals the password of the inputted username
if(inputPass.equals(userPass.get(inputUsr)))
b=true;
System.out.println("Either the username or password is incorrect. You have "+(3-tries)+" more attempts.");
tries++;
//program quits afte 3 tries
if(tries>3){
System.exit(0);
}
}
System.out.println("Welcome "+userFull.get(inputUsr));
}
}
There are two problems in the code inside your while loop as explained below:
(1) keyboard.next() is reading the console output text i.e., reading the printed text 'Password', so replace keyboard.next() with keyboard.nextLine();
(2) You did not handle the else condition for the tries count
You can refer at the below code with inline comments:
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.nextLine();
System.out.print("\nPassword: ");
String inputPass=keyboard.nextLine();
if(inputPass.equals(userPass.get(inputUsr))) {
b=true;
} else {
System.out.println("Either the username
or password is incorrect.
You have "+(3-tries)+" more attempts.");
tries++;
}
if(tries>3){
System.exit(0);
}
}
My task is to create a program which asks the user to enter a year, a first name and a last name. It then takes the last 2 numbers of the year, the whole last name, and the first letter of the first name and formats them into an email like this: 16SmithJ#mymail.co.uk. It places this email in a text file, which doesn't need to be printed. At the end, it asks if the user wishes to repeat the process again to make a new email.
This is my program, and it isn't fully complete yet. I have it working, but when I go to implement the part which repeats it if wanted, the email is no longer made in the file:
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter (new FileWriter("7D_mail.txt"));
boolean done = false;
while (done==false){
Scanner kb = new Scanner (System.in);
System.out.print ("Enter the year (e.g 2016) > ");
String year = kb.nextLine();
System.out.print ("Enter your first name > ");
String fname = kb.nextLine();
System.out.print ("Enter your last name > ");
String lname = kb.nextLine();
pw.write (year.substring(2)+lname+fname.charAt(0)+"#mymail.co.uk");
System.out.print ("*** Email created - another one? (Y/N)");
pw.close();
}
}
This program above works, but if I then add one line after the last one (String answer = kb.nextLine();), to make a new string for the answer, it no longer works.
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter (new FileWriter("7D_mail.txt"));
boolean done = false;
while (done==false){
Scanner kb = new Scanner (System.in);
System.out.print ("Enter the year (e.g 2016) > ");
String year = kb.nextLine();
System.out.print ("Enter your first name > ");
String fname = kb.nextLine();
System.out.print ("Enter your last name > ");
String lname = kb.nextLine();
pw.write (year.substring(2)+lname+fname.charAt(0)+"#mymail.co.uk");
System.out.print ("*** Email created - another one? (Y/N)");
String answer = kb.nextLine();
pw.close();
}
}
Any idea why this doesn't work? Thanks
I don't think it stopped working. You are unconditionally setting "done" to true after you take the user's repsonse, so it exits. Wrap "done = true" in a condition that checks for the value of "answer" to be "Y".
This is because the value 'done' is set to true after the first iteration of the loop and the loop never gets a chance to run again.
Besides, you close the PrintWriter after one iteration as well.
What I would suggest is this change:
if(answer.equals("N")){
done = true;
pw.close();
}
Try using System.out.println (); after printing the question to avoid exceptions (you can read the api here https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()).
I have a basic User Input and System Output program using strings, and at the start of the program it asks for the user's name, which it saves as a string variable inside the program.
Scanner input = new Scanner(System.in);
System.out.println("Hello there! What's your name?");
String name = input.nextLine();
What I want is for the program to save all new names it receives in an external file (like a
text file), and whenever a name is input it checks to see if it has encountered that name before. I want to use an if / else statement to have it display a different output depending on whether or not it has seen that name before. How do I go about accomplishing this?
~
My apologies if this is a basic problem (or if it has been answered before), but I am relatively new to java and I wasn't able to find a solution. Thank you for your help! ^-^
I think this program may accomplished your requirement
public static void main(String as[]) throws Exception{
int i=0;
File f1=new File("D:\\Name.txt");
FileWriter fw=new FileWriter(f1,true);
Scanner input = new Scanner(System.in);
Scanner output=new Scanner(f1);
System.out.println("Hello there! What's your name?");
String name = input.nextLine();
if(!f1.exists()){
f1.createNewFile();
}
else{
while(output.hasNext()){
String na=output.next();
if(na.equals(name)){
++i;
break;
}
}
if(i==0)
fw.write(name+" ");
else{
System.out.println("Please enter some different name");
}
}
fw.close();
input.close();
output.close();
}