Make one extra variable, program doesn't work - java

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()).

Related

Java Properties: How to update two keywords consecutively? [duplicate]

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).

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

Console returning first thing Scanner captured without moving onto other blocks of code

I am trying to write a very simple program which captures a few key pieces of info about a prospective job and inserts those into a prepared cover letter. I have imported Java's scanner utility as you can see in my code. When I run it via the "Java" command in windows' cmd prompt, the first System.out.println command appears and I (the user) input as prompted. But then, the console simply outputs exactly what I input and does not move on to other parts of the code. Also, as you can see, the console only outputs the first word of whatever I input.
I am very new at programming, can anyone spot what I must be missing?
I will include an image of the console here (code below):
Link to picture - Lack to reputation needed to edit in photos
find code below
import java.util.Scanner;
public class CoverLetter {
public static void main(String[] args) {
System.out.println("Welcome to tera_byteme's Simple Cover Letter Generator.");
// defines scanner "reader", prompts user to enter business name, stores that in a string var "bizName", closes reader
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the business name.");
String bizName = reader.next();
reader.close();
//same as above block but asks for position title, stores in string var "posTitle"
System.out.println("Please enter position title.");
String posTitle = reader.next();
reader.close();
//"" but asks for user's name, stores in string var "userName"
System.out.println("Please enter your name.");
String userName = reader.next();
reader.close();
String seg1 = new String();
seg1 = "My name is " + userName + " and I am very interested in working for ";
String seg2 = new String();
seg2 = bizName + "as a " + posTitle;
String finalCut = new String();
finalCut = seg1 + seg2;
System.out.println("Here is your cover letter!");
System.out.println(finalCut);
}
}![enter image description here](https://i.stack.imgur.com/EqheW.jpg)
You have two problems you close your scanner too soon and you use next() instead of nextLine(). Don't forget to recompile! I tested those fixes and it works for me. This code:
import java.util.Scanner;
public class CoverLetter {
public static void main(String[] args) {
System.out.println("Welcome to tera_byteme's Simple Cover Letter Generator.");
// defines scanner "reader", prompts user to enter business name, stores that in a string var "bizName", closes reader
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the business name.");
String bizName = reader.nextLine();
//same as above block but asks for position title, stores in string var "posTitle"
System.out.println("Please enter position title.");
String posTitle = reader.nextLine();
//"" but asks for user's name, stores in string var "userName"
System.out.println("Please enter your name.");
String userName = reader.nextLine();
reader.close();
String seg1 = new String();
seg1 = "My name is " + userName + " and I am very interested in working for ";
String seg2 = new String();
seg2 = bizName + " as a " + posTitle;
String finalCut = new String();
finalCut = seg1 + seg2;
System.out.println("Here is your cover letter!");
System.out.println(finalCut);
}
}
Gives this output:
Welcome to tera_byteme's Simple Cover Letter Generator.
Please enter the business name.
Biz Inc.
Please enter position title.
Senior Manager
Please enter your name.
Jeff
Here is your cover letter!
My name is Jeff and I am very interested in working for Biz Inc. as a Senior Manager

Why does Java just skip over the if statement? [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
import java.util.Scanner;
public class Box
{
public static void main(String[] args)
{
String empty = "";
String yes = "yes";
String no = "no";
String response;
String name;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
name = input.nextLine();
if(name.equals(empty))
{
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
System.out.println("Would you like the profanity filter turned on?");
response = input.nextLine();
response = response.toLowerCase();
if(response.equals(yes) || response.equals(no))
{
if(response.equals(yes))
System.out.print("Profanity filter will be turned on.");
else
System.out.print("Profanity filter will not be turned on.");
}
else
System.out.print("Invalid response, please try again.");
}
}
This displays "Please enter your name >>", but no matter what I enter there, even if it's empty, it always asks if you'd like the profanity filter turned on.
It just skips over the if that's supposed to loop forever until you actually enter a name, and I can't figure out why.
Also, I know I didn't ask this in the title, but I also can't figure out a way for the final statement to loop back to the "response = input.nextLine();" when someone doesn't enter either "yes" or "no".
If you want it to loop forever then you need to use while loop and not if, e.g.:
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
String name = input.nextLine();
while(name.isEmpty()){
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
This will keep asking the user to enter the name until he enters a non empty String.

How to accept different data types from the user in java

I'm a beginner in Java and I just wrote a program to get the user's name, phone number and address. The problem is after reading the phone number the program will not proceed to read the address, it's like if it's skipping it. Here is my code:
public static void main(String [] arge){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name, phone number and address");
String name = sc.nextLine();
long phone = sc.nextLong();
String address = sc.nextLine();
System.out.println("\n *** Here is your info ***");
System.out.println("Name: "+name+"\nPhone number: "+phone+"\n Address: "+address);
}
long phone = sc.nextLong();
change this to
long phone = Long.parseLong(sc.nextLine());
Because after giving the phone number, the enter you hit is being consumed as the nextLine which is set to your address. Thus, the blank address(in the sense, the program doesn't prompt to you enter the address).
Another way to make your code work(without changing anything, YES without any changes!) is to provide your phone number and address in the same line as input. Scanner will take the space as the default delimiter and do the job for you. This is because nextLong() will only scan for a long value.
Your program will read all the three inputs. But i believe you are hitting enter key after doing the input for phone number. Try doing the input as mentioned here:
myName
100000 myAddress
sc.nextLong() method will accept the long value and then sc.nextLine() will wait for input on the same line. And if you press enter after entering the long value, sc.nextLine() will simply read empty.
Try this:
String name = sc.nextLine();
long phone = Long.parseLong(sc.nextLine());
String address = sc.nextLine();
try to read values one by one
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
String name = sc.nextLine();
System.out.println("Enter your phone number");
long phone = sc.nextLong();
sc.nextLine();//to catch the buffer"ENTER KEY" value
System.out.println("Enter your address");
String address = sc.nextLine();
System.out.println("\n *** Here is your info ***");
System.out.println("Name: "+name+"\nPhone number: "+phone+"\n Address: "+address);
Try this.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
}

Categories

Resources