While loop not terminating even when condition is met-Java - java

I am not sure what is wrong and my Professor is stumped as well. The while loop condition only terminates if the condition is met right away. Once the loop is running, the met condition no longer stops it and it just keeps going. Its like the look isnt checking the condition anymore? Below is my code. Thank you for any help.
import java.io.*;
import java.util.*;
public class createPhoneList {
public static void main(String[] args) {
DataOutputStream ostream;//creates output stream
Scanner input = new Scanner(System.in);//creates scanner in object
final String DONE = "DONE";//will be used to end data entry loop
String firstName;
String lastName;
long phoneNumber;
try{
ostream = new DataOutputStream(new FileOutputStream("javaContactsUnit4Assignment.txt"));
System.out.print("Enter First Name or type 'DONE' to quit: ");
firstName = input.nextLine();
while(!firstName.equalsIgnoreCase(DONE)){
/*
* Error occuring at runtime where while loop terminates only if
* "done" is typed first, but once the loop is running "done" no longer
* stops it. Not sure what is wrong...
*/
input.nextLine();
System.out.print("Please enter Last Name: ");
lastName = input.nextLine();
System.out.print("Please enter the Phone Number(with NO DASHES, as they will cause a fatal error): ");
phoneNumber = input.nextLong();
ostream.writeUTF(firstName);
ostream.writeUTF(lastName);
ostream.writeLong(phoneNumber);
System.out.print("Enter First Name or type 'DONE' to quit: ");
firstName = input.nextLine();
}
}
catch(IOException e){
System.err.println("Error opening file.");
}
catch(InputMismatchException e){
System.err.println("Invalid data was entered. Please try again.");
}
catch(Exception e){
System.err.println("You encountered a fatal error. Please try again.");
}
}
}

You should add another input.nextLine(); after phoneNumber = input.nextLong();.
That's because input.nextLong() command reads only the long value (and skips the \n which is the enter key you press right after).
So when you continue reading with input.nextLine() you receive the \n and not "done", that's why your loop never terminates. So adding another input.nextLine() will "swallow" the \n and the next one will read the actual String.

Related

trouble getting rid of small error (symbol not found) in a little project java

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.

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.

If user presses enter (without anything else) how can I print out the line ("please give a valid command")?

I have a program in java where the user have to give command. However if he presses enter without anything else the program stops and he gets this:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at UserInterface.main(UserInterface.java:43)
How is it possible that I can detect with the program that no line is found, and I print out the following ("please give a valid command").
I have tried this:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command == "") {
System.out.println("please give a valid command");
}
1) You can use the method isEmpty() from the Scanner itself to find out if an input is "nothing".
Try this:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command.isEmpty())
{
System.out.println("Please give a valid command.");
}
2) You can't compare two Strings like you did either. If you want to compare them you need to use the equals(Object anObject) method.
Here is an example:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command.equals("A String"))
{
System.out.print("Success");
}
Surround the statement with try/catch
...
String command = "";
try {
keyboard.nextLine();
} catch (Exceptionn e) {}
...
This will catch the exception.
Try this:
if(command.equals("")){
System.out.println("please give a valid command");
}

Make one extra variable, program doesn't work

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

How to have my code run until I enter a number

I'm sorry if this is a silly question but I am fairly new to coding and so for my assignment I was given this code:
package webservice;
import webservice.Weather;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the zip code : ");
java.lang.String zipCode = scan.nextLine();
try{
webservice.Weather service = new webservice.Weather();
webservice.WeatherSoap port = service.getWeatherSoap();
webservice.WeatherReturn result = port.getCityWeatherByZIP(zipCode);
System.out.print(result.getCity()+ " ");
System.out.println (result.getState());
System.out.println("Zip code " + zipCode);
System.out.println ("Current Temperature is " + result.getTemperature());
}
catch (Exception ex){
System.out.println("Error");
}
}//end main
}//end class
The code runs perfectly fine but I have to have it loop until i enter "0" for the zip code.
I'm fairly new to coding and I tried to review my previous works to try to incorporate a loop but I was never successful. Which loop would be the most efficient to have the code loop until the user enters "0" as the zip code?
Simply try this:
Scanner scan = new Scanner (System.in);
int zipCode;
while(scan.nextInt()!=0){
System.out.print ("Enter the zip code : ");
zipCode = scan.nextInt();
}
Use a while loop to verify your condition and use .nextInt() to get an int from the scanner.
Also there's a typo:
If you use :
import webservice.Weather;
You don't have to do this:
webservice.Weather service = new webservice.Weather();
It's simply:
Weather service = new Weather();
Take a look at Using Package Members for further information.
How about while loop?
String zipCode;
while(!"0".equals(zipCode = scan.nextLine())) {
//to do rest
}
Sample code:
import java.util.Scanner;
class Ideone
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String zipCode;
while(!"0".equals(zipCode = sc.nextLine())) {
System.out.printf("zip code: %s\n", zipCode);
}
System.out.printf("last zip code: %s\n", zipCode);
}
}
I/P:
123
456
789
0
O/P:
zip code: 123
zip code: 456
zip code: 789
last zip code: 0
while loop would do your trick.
This is because while loop checks the condition first and then iterates over if the condition is found to be true. And in your case we need to check if the user has entered the correct value or not. If he has entered 0 we do not need to proceed further.

Categories

Resources