I just started to code in Java and I have a question. After my "else" statement, I want to repeat my code again. How do I do that? Is there a keyword or something?
import java.util.Scanner;
public class UserInputStory {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println(
"Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
}
else {
System.out.println("Let's try again then!");
}
}
}
Place the body of your code that you want repeating inside a while loop and break when your end-condition is true:
public static void main(String[] args) {
while(true) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println("Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
break;
}
else {
System.out.println("Let's try again then!");
}
}
}
You can envelop our whole code by:
while(1)
ut its not a good approach and there must be some condition applied (depending upon the xontext of your program) which can take you out of the loop
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
can i ask whats the problem in my code? its done but the part of the yes or no which is this System.out.println("A refrigerator costs $2.50 extra each day would you like that? (Y/N)"); will be skipped and insted the System.out.println("Number of Days Staying :" + dys); will be printed.
import java.util.Scanner;
public class Test
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String rt;
String a = new String ("G");
String b = new String ("P");
String c = new String ("L");
System.out.println(" Welcome to Easy Living Resort Hotel");
System.out.println("------------------------------------------");
System.out.println(" Room Type Daily Rate ");
System.out.println(" ~~~~~~~~~ ~~~~~~~~~~ ");
System.out.println(" G- Garden Pool View $125.00 ");
System.out.println(" P- Pool View $145.00 ");
System.out.println(" L- Lake View $180.00 ");
System.out.println("Please select your room type");
rt = scan.nextLine();
if(rt.equalsIgnoreCase("G")) {
System.out.println("Garden Pool View");
} else if(rt.equalsIgnoreCase("P")) {
System.out.println("Pool View");
} else {
System.out.println("Lake view");
}
int dys;
System.out.println("------------------------------------------");
System.out.println("Number of Days you are staying in: ");
dys = scan.nextInt();
String r;
String d = new String ("Y");
String e = new String ("N");
System.out.println("A refrigerator costs $2.50 extra each day would you like that? (Y/N)");
r = scan.nextLine();
if(r.equalsIgnoreCase("Y")) {
System.out.println("Y");
}else if (r.equals("N")) {
System.out.println("N");
}
System.out.println("Number of Days Staying :" + dys);
//System.out.println("
}
}
I would suggest you to go through this for detailed explanation.
https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/#:~:text=Why%20is%20Scanner%20skipping%20nextLine()%20after%20use%20of%20other%20next%20functions%3F,-Difficulty%20Level%20%3A%20Easy&text=The%20nextLine()%20method%20of%20java.&text=Scanner%20class%20advances%20this%20scanner,line%20separator%20at%20the%20end.
Here is a working example:
The problem was a missing scan.nextLine(). Otherwise it will take the \n of your previous input and skip the input. I also cleaned up your code. It is better to split up your code in methods.
import java.util.Scanner;
public class Reservation
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String rt;
String a = "G";
String b = "P";
String c = "L";
showRoomPrices();
rt = scan.nextLine();
evaluateEnteredRoomType(rt);
int dys;
System.out.println("------------------------------------------");
System.out.println("Number of Days you are staying in: ");
dys = scan.nextInt();
String r;
String d = "Y";
String e = "N";
scan.nextLine();
System.out.println("A refrigerator costs $2.50 extra each day would you like that? (Y/N)");
r = scan.nextLine();
if(r.equalsIgnoreCase("Y")) {
System.out.println("Y");
}else if (r.equals("N")) {
System.out.println("N");
}
System.out.println("Number of Days Staying :" + dys);
//System.out.println("
}
private static void evaluateEnteredRoomType(final String rt) {
if(rt.equalsIgnoreCase("G")) {
System.out.println("Garden Pool View");
} else if(rt.equalsIgnoreCase("P")) {
System.out.println("Pool View");
} else {
System.out.println("Lake view");
}
}
private static void showRoomPrices() {
System.out.println(" Welcome to Easy Living Resort Hotel");
System.out.println("------------------------------------------");
System.out.println(" Room Type Daily Rate ");
System.out.println(" ~~~~~~~~~ ~~~~~~~~~~ ");
System.out.println(" G- Garden Pool View $125.00 ");
System.out.println(" P- Pool View $145.00 ");
System.out.println(" L- Lake View $180.00 ");
System.out.println("Please select your room type");
}
}
This is my code, the while loop does not have an input and the rep variable does not accept an input:
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "";
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} // This does not accept input
while (rep.equals("y"));
}
}
Either just add one more keyboard.nextLine() before rep = keyboard.nextLine(); (in order to clear the newline character), or read your double gpa value with:
double gpa = Double.parseDouble(keyboard.nextLine());
Important point to understand here (especially if you're a novice Java developer), about why your code doesn't work, is, that you invoke nextDouble() as a last method on your Scanner instance, and it doesn't move the cursor to the next line.
A bit more details:
All the methods patterned nextX() (like nextDouble(), nextInt(), etc.), except nextLine(), read next token you enter, but if the token isn't a new line character, then the cursor isn't moved to the next line. When you enter double value and hit Enter, you actually give to the input stream two tokens: a double value, and a new line character, the double value is initialized into the variable, and the new line character stays into input stream. The next time you invoke nextLine(), that very new line character is read, and that's what gives you an empty string.
Here's the same code using a while loop instead of do-while. It works the way you want it to.
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "y";
while (!rep.equals("n")) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ",GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
}
}
}
You need to skip blank lines.
public static void main(String[] args) {
String rep;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
keyboard.skip("\r\n"); // to skip blank lines
}
while (rep.equalsIgnoreCase("y"));
keyboard.close();
}
Use nextLine instead of nextDouble:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String rep = "";
do {
System.out.println("Enter your full name:");
String name = keyboard.nextLine();
System.out.println("Enter your GPA:");
// double gpa = keyboard.nextDouble();
double gpa = Double.parseDouble(keyboard.nextLine());
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} while (rep.equals("y"));
keyboard.close();
}
I am writing a program to print out the name of a student and their grade. It works if I only enter their first name and I get an Error when I enter their last. I am wondering if I have overlooked something with the String name.
package project_2;
import java.util.Scanner;
public class Project_2 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.next();
System.out.print("Enter Grade: \t");
double Grade = input.nextDouble();
if(Grade>=88)
System.out.println(name + "You have an A!");
else if (Grade<=87 && Grade>=80)
System.out.println(name + "You have a B!");
else if (Grade<=79 && Grade>=67)
System.out.println(name + "You have a C!");
else if (Grade<=66 && Grade>=60)
System.out.println(name + "You have a D!");
else
System.out.println(name + "You have a F!");
}
}
Just do this:
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.print("Enter Grade: \t");
Then you can take the full name.
Output:
Enter your name: Jack Davidson
Enter Grade: 88
Please note that, Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.
I'm creating a program which prints a summary of the situation after interactive input has ended (ctrl - d). So it prints a summary of the average age and percentage of children who have received vaccines after interactive input.
However, I'm always receiving the No Line Found error whenever I press ctrl-d at Name:. My compiler tells me the error is at name = sc.nextLine(); within the while loop but I don't know what is causing the error exactly.
public static void main(String[] args) {
String name = new String();
int age, num = 0, i, totalAge = 0;
boolean vaccinated;
int numVaccinated = 0;
double average = 0, percent = 0, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
while(sc.hasNextLine())
{
sc.nextLine();
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
}
average = (double) totalAge/num;
percent = (double) count/num * 100;
System.out.printf("Average age is %.2f\n", average);
System.out.printf("Percentage of children vaccinated is %.2f%%\n", percent);
}
}
You do not correctly implement an exit condition for your loop if you ask me.
Try something like this:
String input = "";
do {
System.out.print("Name: ");
name = sc.nextLine();
[... all your input parameters ...]
sc.nextLine();
System.out.print("Do you want to enter another child (y/n)? ");
input = sc.nextLine();
} while (!input.equals("n"));
This way you can quit entering new persons without having to enter a strange command that might lead to an error. Furthermore, a do-while loop helps you to reduce your code, because you don't have to use the same code twice, i.e., everything between Scanner sc = new Scanner(System.in); and while(sc.hasNextLine()) in your example.
I have to write a program that asks the user for his name, address and phone number. When the data is entered the program shall print the data and ask the user to verify the data by entering yes or no. This process shall be repeated until the user is satisfied and answers yes to the question.
Now, at this moment I am able to pop-up a single prompt (in my case asking only the user's name). But what if I want to add multiple question (i.e. asking address and telephone number) and happen the same thing? How could I do that?
My code:
package userinfo;
import java.util.Scanner;
import sun.security.krb5.SCDynamicStoreConfig;
public class UserInfo {
public static void main(String[] args) {
String varify;
String yes = "yes";
String no = "no";
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = input.next();
System.out.println("Your input was: "+name);
System.out.println("Varify by yes or no: ");
while (true) {
varify = input.next();
if (varify.equalsIgnoreCase(yes)) {
System.out.println("Varified! Your name is: " + name);
} else if (varify.equalsIgnoreCase(no)) {
System.out.println("Type your name again: ");
}
}
}
}
You can extract this code to a method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName = readFieldAndVerify(input, "Enter your name: ");
String userAddress = readFieldAndVerify(input, "Enter your address: ");
String userPhoneNumber = readFieldAndVerify(input, "Enter your phone number: ");
}
private static String readFieldAndVerify(Scanner input, String prompt) {
while (true) {
System.out.print(prompt);
String field = input.next();
System.out.println("Are you sure (yes / no)?");
String verify = input.next();
if (verify.equalsIgnoreCase("yes")) {
System.out.println("Verified!");
return field;
} else {
System.out.println("Canceled");
}
}
}
EDIT Added logic for more questions... Expand it in similar fashion for everything you need. You could expand this code into a single method as well so you avoid code replication. Check answer from user alaster for an example.
Try this. It will store the name variable in case you want to use it further.
We use a boolean to keep asking the user to input his name until he validates it.
Of course, you can still use while(true) and then break if the name is valid, but I prefer this method since the code is more clear and easier to understand.
private static boolean isVerified(String verify) {
if (verify.equalsIgnoreCase("yes")) {
return true;
} else if (verify.equalsIgnoreCase("no")) {
return false;
} else
return false;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validName = false;
boolean validTelephoneNo = false;
boolean validAddress = false;
String name="";
String telephoneNo="";
String address="";
while (!validName) {
System.out.print("Enter your name: ");
name = input.next();
System.out.println("Are you sure your name is " + name + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your name is: " + name);
validName = true;
} else {
System.out.println("Not verified! Please type your name again.");
}
}
while (!validTelephoneNo) {
System.out.print("Enter your telephone nummber: ");
telephoneNo = input.next();
System.out.println("Are you sure your telephone number is " + telephoneNo + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your telephone number is: " + telephoneNo);
validTelephoneNo = true;
}
else {
System.out.println("Not verified! Please type your telephone number again.");
}
}
while (!validAddress) {
System.out.print("Enter your address: ");
address = input.next();
System.out.println("Are you sure your address is " + address + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your address is: " + address);
validAddress = true;
}
else {
System.out.println("Not verified! Please type your address again.");
}
}
System.out.println("Done, here is your info:");
System.out.println("Name: " + name);
System.out.println("Telephone Number: "+telephoneNo);
System.out.println("Address: "+address);
}