Java - Method to loop until a Y or N is entered - java

I have looked around and haven't found any questions that has been directly answered for my problem, if i'm wrong, sorry. I'm writing a program that is supposed to take in your birth information, year, month, day, hour, minute and then ask if they would like to do it again but using a method and loop until a Y/N is entered.
My problem is im not able to get the method to take in the Y/N and end the program, as well as end when a N is entered.
I think there is supposed a while or some sort of loop that needs to be in the method but im having a hard time figuring that out.
All my other methods work except for this one, any help would be appreciated, thanks.
This is the code I have for my method now:
public static boolean getYNConfirm(Scanner pipe, String prompt)
{
String choice="";
System.out.println(prompt);
choice = pipe.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
return true;
}
else
{
return false;
}
}
And this is the code for my main program:
public static void main(String[] args)
{
int year, month, day, hour, minutes;
String msg="";
boolean done = false;
Scanner in = new Scanner(System.in);
while(!done)
{
year = SafeInput.getIntInRange(in, "Enter the year you were born: ", 1965, 2000);
month = SafeInput.getIntInRange(in, "Enter your month of birth: ", 1, 12);
switch (month)
{
case 1:
msg = "January";
break;
case 2:
msg = "February";
break;
case 3:
msg = "March";
break;
case 4:
msg = "April";
break;
case 5:
msg = "May";
break;
case 6:
msg = "June";
break;
case 7:
msg = "July";
break;
case 8:
msg = "August";
break;
case 9:
msg = "Septemeber";
break;
case 10:
msg = "October";
break;
case 11:
msg = "November";
break;
case 12:
msg = "December";
break;
}
hour = SafeInput.getIntInRange(in, "Enter the hour you were born in: ", 1, 24);
minutes = SafeInput.getIntInRange(in, "Enter the minutes you were born: ", 1, 59);
System.out.println("You were born: " + year + " , " + msg + " , " + hour + " hr. " + minutes + " mins. ");
SafeInput.getYNConfirm(in, "Would you like to play again?");
}
}
}
Thanks for any help.

Value of done is always false. Change on last line:
done = SafeInput.getYNConfirm(in, "Would you like to play again?");
EDIT:
Your logic does not fit if you return true Change here too:
if(choice.equalsIgnoreCase("Y"))
{
return false;
}
else
{
return true;
}

you need to change the value of done base on the return of the getYNConfirm method. So the last line should be
done = SafeInput.getYNConfirm(in, "Would you like to play again?");

Related

How to fix inputting the user's info twice?

The program ask for a month and it could be a string or int. In the isDigitsOrSpecial method, it works and it has the same format in my method isString. The difference is that when I want to enter the month in a string way (ex.january), it will ask me twice. So, I don't know what to do. I tried a lot of ways but it doesn't work. Do you have any suggestions?
Here's my full code. You can try to run it, and see the problem where you have to input twice the name of the month in a string way.
I would really appreciate any of your suggestions.
package Electronic_payment_process;
import java.util.InputMismatchException;
import java.util.Scanner;
public class practice {
static String s;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float current = 0, recent = 0, difference, multiply;
String month, recents, currents = null;
System.out.println("The month could be a number or a name.");
System.out.println("Example: (01-12) or (JAN – dec)");
// for the validation of due month user’s input
do {
System.out.print("\nEnter a month: ");
month = scan.next();
if (isDigitsOrSpecial(month)) {
System.out.print("proceed");
break;
} else if (isString(month)) {
System.out.print("proceed");
break;
}
} while (true);
// for the validation of current meter reading
do {
System.out.print("\nEnter current reading: ");
try {
current = scan.nextFloat();
System.out.println("proceed");
currents = String.format("%.2f", current);
if (current <= 0) {
System.out.println("Invalid input");
}
} catch (InputMismatchException a) {
System.out.println("Must enter a number");
scan.next();
}
} while (current <= 0);
// for the validation of recent meter reading
do {
System.out.print("Enter recent reading: ");
try {
recent = scan.nextFloat();
if (recent < current) {
System.out.println("proceed");
recents = String.format("%.2f", recent);
break;
} else {
System.out.println("recent must be less than current");
}
} catch (InputMismatchException a) {
System.out.println("Must enter a number");
scan.next();
}
} while (true);
difference = current - recent;
multiply = difference * 50;
System.out.println("====================================================================================");
System.out.println("MONTH " + " RECENT " + "CURRENT " + "TOTAL USAGE " + "Price per unit " + "TOTAL AMOUNT ");
System.out.println((s + (" ") + recents + (" kW") + (" ") + currents + (" kW") + (" ") + difference + (" ") + ("50php") + (" ") + multiply));
}
public static boolean isDigitsOrSpecial(String month) {
Scanner scan = new Scanner(System.in);
if (month != null) {
for (char ch : month.toCharArray()) {
if (Character.isLetter(ch)) {
return false;
}
}
}
int we = Integer.parseInt(month);
s = Integer.toString(we);
if (null == month) {
s = scan.nextLine();
} else switch (we) {
case 01:
s = "January";
break;
case 02:
s = "February";
break;
case 03:
s = "March";
break;
case 04:
s = "April";
break;
case 05:
s = "May";
break;
case 06:
s = "June";
break;
case 07:
s = "July";
break;
case 8:
s = "August";
break;
case 9:
s = "September";
break;
case 10:
s = "October";
break;
case 11:
s = "November";
break;
case 12:
s = "December";
break;
default:
System.out.println("You have entered an invalid number of month");
}
return true;
}
public static boolean isString(String month) {
Scanner scan = new Scanner(System.in);
if (null != month) {
char[] chars = month.toCharArray();
s = scan.nextLine();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
}
if (!(month.length() >= 3)) {
System.out.println("Name of month must be at least 3 letters.Please try again");
return false;
} else if (month.startsWith("jan") || month.startsWith("JAN") || month.startsWith("Jan")) {
s = "January";
}
return true;
}
}
I see we have added additional scanner statements inside isDigit or isString methods. I have removed them and it looks good to me.
public static boolean isDigitsOrSpecial(String month) {
if (month != null) {
for (char ch : month.toCharArray()) {
if (Character.isLetter(ch)) {
return false;
}
}
}
int we = Integer.parseInt(month);
switch (we) {
case 01:
s = "January";
break;
case 02:
s = "February";
break;
case 03:
s = "March";
break;
case 04:
s = "April";
break;
case 05:
s = "May";
break;
case 06:
s = "June";
break;
case 07:
s = "July";
break;
case 8:
s = "August";
break;
case 9:
s = "September";
break;
case 10:
s = "October";
break;
case 11:
s = "November";
break;
case 12:
s = "December";
break;
default:
System.out.println("You have entered an invalid number of month");
return false;
}
return true;
}
public static boolean isString(String month)
{
if (null != month) {
char[] chars = month.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
}
if (!(month.length() >= 3)) {
System.out.println("Name of month must be at least 3 letters.Please try again");
return false;
}
return true;
}

JAVA - How can I make sure program only continues with a scanned int? [duplicate]

This question already has answers here:
How to loop user input until an integer is inputted?
(5 answers)
Closed 4 years ago.
I'm learning to program in Java and I'm working on a pizza-ordering console program.
I've gotten the entire program to work, but I want to fool-proof it. Three places I ask for an int input, but when I type a char or a string, the program crashes.
What I hoped to achieve:
When the user enters a valid number, the program continues - Done
When the user enters a char or a string they get an error message and the loop starts over.
Here's an example from my code:
do {
correctInput = true;
System.out.println("Step 1: Look through the menu below and type in the NUMBER of the pizza you want.\n");
pizzaMenu();
System.out.print("\nType in your pizza number here: ");
pizzaNumber = pizza.nextInt();
pizza.nextLine();
switch (pizzaNumber) {
case 1:
pizzaChoice = "Napoli";
pizzaPrice = 50;
break;
case 2:
pizzaChoice = "Hawaii";
pizzaPrice = 50;
break;
case 3:
pizzaChoice = "Quattro Stagioni";
pizzaPrice = 60;
break;
case 4:
pizzaChoice = "Sicillia";
pizzaPrice = 75;
break;
case 5:
pizzaChoice = "Turbo";
pizzaPrice = 60;
break;
case 6:
pizzaChoice = "Jamaica";
pizzaPrice = 75;
break;
case 7:
pizzaChoice = "Romano";
pizzaPrice = 60;
break;
case 8:
pizzaChoice = "Vulcano";
pizzaPrice = 75;
break;
case 9:
pizzaChoice = "Vegetariana";
pizzaPrice = 60;
break;
case 10:
pizzaChoice = "Salame";
pizzaPrice = 60;
break;
default:
System.out.println("You've entered a wrong number. Try again");
correctInput = false;
break;
}
} while (!correctInput);
Could you please help pointing me towards a possible solution?
You can read a string from the scanner and then manually try to convert it to required number (either Integer or Double):
String str = scan.next();
if (isNumeric(str))
System.out.println("Numeric value: " + Double.parseDouble(str));
else
System.out.println("Not a numeric");
And method that checks if given string a numeric or not:
private static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e) {
return false;
}
}

Do while loop is not repeating

I want it to ask the user for an input again if he misspells "im sad" and go through the whole switch process.
When I type "imsed" it says "I don't understand" as it's supposed to and asks for another input but when I type in the other input, it just ends.
I can't use arrays yet.
do {
if (a.contains("sad")) {
System.out.println("bot: " + "Hey there! Dont be sad, Here is a pun to cheer you up");
System.out.println();
i = 1 + dice.nextInt(3);
switch (i) { // start of switch
case 1:
System.out.println("Why did the traffic light felt embarrased?\n"
+ "Because everyone saw it changing");
a = input.nextLine();
break;
case 2:
System.out.println("Why was Cinderella thrown off the basketball team?"
+ "\nShe ran away from the ball.");
a = input.nextLine();
break;
case 3:
System.out.println("Why is Peter Pan always flying?\n"
+ "He neverlands.");
a = input.nextLine();
break;
} //end of switch
} else if (a.contains("again")) {
e = 1 + dice.nextInt(3);
switch (e) { // start of switch
case 1:
System.out.println("How do you know it's an emotional wedding?\n" + "When the cake is in tiers");
a = input.nextLine();
break;
case 2:
System.out.println("What does a house wear?" + "\nA Dress.");
a = input.nextLine();
break;
case 3:
System.out.println("How do you know a frenchmen plays video games?\n" + "He says wii when you ask him.");
a = input.nextLine();
break;
} //end of switch
}
} while (a.equals("again")
if (a.contains("im happy")) {
System.out.println("bot: " + "Have a great day ahead!");
}
if (!a.equals("im sad")
|| !a.equals("im happy"
|| !a.equals("again")) {
System.out.println("bot: " + "I don't understand");
a = input.nextLine();
}

What my system.out.println coming out vertical

everything works perfect and I know more or less java sout formatting, but I ve been following this book and its been explaining how the logic works. One thing I can not seem to figure out is why my output is coming out vertical and in the book its perfectly horizontal? I have it formatted exactly the same way
this is my java code
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package b.elsestatements;
import java.util.*;
/**
*
* #author willc86
*/
public class Clock {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minuite = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);
if (hour > 17){
System.out.println("Good evening");
} else if (hour < 12) {
System.out.println("Goodmorning");
} else {
System.out.println("Good afternoon");
}
System.out.println("It is ");
if (minuite != 0) {
System.out.println("" + minuite + " ");
// if (minuite != 1) {
// System.out.println("minuites");
// } else {
// System.out.println("minuite");
// }
System.out.println((minuite != 1) ? "minuites" : "minuite ");
System.out.println("Past");
System.out.println((hour > 12) ? (hour - 12) : hour);
System.out.println("O clock on ");
//month case
switch (month) {
case 1:
System.out.println("Jan");
break;
case 2:
System.out.println("Feb");
break;
case 3:
System.out.println("Mar");
break;
case 4:
System.out.println("Apr");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("Jun");
break;
case 7:
System.out.println("Jul");
break;
case 8:
System.out.println("Aug");
break;
case 9:
System.out.println("Sept");
break;
case 10:
System.out.println("Oct");
break;
case 11:
System.out.println("Nov");
break;
case 12:
System.out.println("Dec");
}
System.out.println("On " + year + " day " + day);
}
}
}
Maybe on your book it doesn't say: System.out.println maybe it says: System.out.print
System.out.print("" + minuite + " ");
System.out.print((minuite != 1) ? "minuites" : "minuite ");
System.out.print("Past");
System.out.print((hour > 12) ? (hour - 12) : hour);
System.out.print("O clock on ");
Maybe that should solve your problem.
I mean change System.out.println to System.out.print
And your output should look like this:
Good afternoon
It is 52 minuitesPast2O clock on Apr
On 2014 day 28
System.out.println will create a new line (ln on the end stands for line) so if you take it out, it should print horizontal without creating new lines.
Another way to create new lines on a System.out.print is by using escape characters such as "\n" that will do the same as System.out.println
This case:
System.out.println("Hello"); //Will create a new line
System.out.println("World"); //Will create a new line
System.out.print("Hello"); //Won't create a new line
System.out.print("World"); //Won't create a new line
System.out.print("Hello \n"); //Will create a new line
System.out.print("World"); //Won't create a new line
The output for the 3 cases above will be:
Hello
World
Hello World
Hello
World

Looping Quiz, Java

Alrighty so, I'm supposed to make a quiz that consists of 5 questions with 4 possible answers. The user then will answer the questions via keyboard input. At the end if they have 5 out of 5 the program should outprint, "excellent" at 4 it should output "Very Good" and at 3 or less is should outprint "Time to brush up on your knowledge of global warming" along with a link to the site with information used to create the questions. included in the coding must be, "Do-While", and "Switch" Statements. I think its almost there but I keep getting errors and I'm really having a hard time figuring out what to do next! Help a lady out?
Edit Here are my received errors:
"Multiple markers at this line
- chosenAnswer1 cannot be resolved
- chosenAnswer1 cannot be resolved to a
variable
- answer1string cannot be resolved to a
variable"**
(My code is below)
import java.io.* ;
public class globalwarming {
public static void main(String[] args) {
InputStreamReader keyInput = new InputStreamReader(System.in) ;
BufferedReader read = new BufferedReader(keyInput) ;
try {
System.out.println("1. Carbon Dioxide (CO2)_____________;");
System.out.println("A. Is colorless, odorless, non-toxic, and non-combustible.");
System.out.println("B. Is produced when Carbon sources are burned (i.e. oil, coal, gas, wood…)");
System.out.println("C. Atmospheric concentration has increased by over 34% since 1960.");
System.out.println("D. All of the above");
String chosenAnswer1 = read.readLine();
int answer1 = 4;
String answer1string = "" + answer1;
String Question1answers;
switch (answer1) {
case 1: Question1answers = "A. Is colorless, odorless, non-toxic, and non-combustible.";
break;
case 2: Question1answers = "B. Is produced when Carbon sources are burned (i.e. oil, coal, gas, wood…)";
break;
case 3: Question1answers = "C. Atmospheric concentration has increased by over 34% since 1960.";
break;
case 4: Question1answers = "D. All of the above";
break;
default: Question1answers = "No response selected";
break;
}
System.out.println("2. Greenhouse gases are; ");
System.out.println("A. A myth created by popular media.");
System.out.println("B. Keep heat close to earth sustaining life, however is rapidly increasing heat levels, which is detrimental to the environment.");
System.out.println("C. Green colored gases that poison and kill plant life.");
System.out.println("D. Nothing to be concerned about, continue buying and consuming products that release CO2 emissions… Nothing to see here.");
String chosenAnswer2 = read.readLine();
int answer2 = 2;
String answer2string = "" + answer2;
String Question2answers;
switch (answer2) {
case 1: Question2answers = "A. A myth created by popular media.";
break;
case 2: Question2answers = "B. Keep heat close to earth sustaining life, however is rapidly increasing heat levels, which is detrimental to the environment.";
break;
case 3: Question2answers = "C. Green colored gases that poison and kill plant life.";
break;
case 4: Question2answers = "D. Nothing to be concerned about, continue buying and consuming products that release CO2 emissions… Nothing to see here.";
break;
default: Question2answers = "No response selected";
break;
}
System.out.println("3. Smart Cars help combat global warming by,");
System.out.println("A. Reducing CO2 emissions slowing the rapid warming of the planets atmosphere.");
System.out.println("B. Consuming more energy thereby eliminating oil supplies.");
System.out.println("C. Require fewer resources to manufacture.");
System.out.println("D. None of the above.");
String chosenAnswer3 = read.readLine();
int answer3 = 1;
String answer3string = "" + answer3;
String Question3answers;
switch (answer3) {
case 1: Question3answers = "A. Reducing CO2 emissions slowing the rapid warming of the planets atmosphere.";
break;
case 2: Question3answers = "B. Consuming more energy thereby eliminating oil supplies.";
break;
case 3: Question3answers = "C. Require fewer resources to manufacture.";
break;
case 4: Question3answers = "D. None of the above.";
break;
default: Question3answers = "No response selected";
break;
}
System.out.println("4. There is more carbon dioxide in the air today than;");
System.out.println("A. There ever has been before.");
System.out.println("B. Than at any other time in the last 800,000 years.");
System.out.println("C. Than there will be in 20 years.");
System.out.println("D. Both A and B.");
String chosenAnswer4 = read.readLine();
int answer4 = 2;
String answer4string = "" + answer4;
String Question4answers;
switch (answer4) {
case 1: Question4answers = "A. There ever has been before.";
break;
case 2: Question4answers = "B. Than at any other time in the last 800,000 years.";
break;
case 3: Question4answers = "C. Than there will be in 20 years.";
break;
case 4: Question4answers = "D. Both A and B.";
break;
default: Question4answers = "No response selected";
break;
}
System.out.println("5. In the last century sea levels have risen how many inches?");
System.out.println("A. 5 Inches");
System.out.println("B. 0 Inches");
System.out.println("C. 7 Inches");
System.out.println("D. 22 Inches");
String chosenAnswer5 = read.readLine();
int answer5 = 3;
String answer5string = "" + answer5;
String Question5answers;
switch (answer5) {
case 1: Question5answers = "A. 5 Inches";
break;
case 2: Question5answers = "B. 0 Inches";
break;
case 3: Question5answers = "C. 7 Inches";
break;
case 4: Question5answers = "D. 22 Inches";
break;
default: Question5answers = "No response selected";
break;
}
}
int i = 5;
String strI = "" + i;
int count = 0;
do {
if (chosenAnswer1 == answer1string) {
count++;
}
if (chosenAnswer2 == answer2) {
count++;
}
if (chosenAnswer3 == answer3) {
count++;
}
if (chosenAnswer4 == answer4) {
count++;
}
if (chosenAnswer5 == answer5) {
count++;
}
} while (count <= 5);
if (count == 5) {
System.out.println("Excellent!");
} else if (count == 4) {
System.out.println("Very good!");
} else if (count > 3) {
System.out.println("Time to brush up on your knowledge of global warming.");
System.out.println("http://www.dosomething.org/actnow/tipsandtools/11-facts-about-global-warming");
}
/*
System.out.println(Question1answers);
System.out.println(Question2answers);
System.out.println(Question3answers);
System.out.println(Question4answers);
System.out.println(Question5answers);
*/
}
}
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Cases does not mean order in your menu, they are like "IF the given variable equals THIS case value"
switch (STRING) {
case STRING_A: do something.. break;
case STRING_B: do something.. break;
}
switch (INTEGER) {
case 1: do something.. break;
case 2: do something.. break;
}
This variable is defined in a try context. It cannot be used outside the try.
String chosenAnswer1 = read.readLine();
You will have to do something like:
String chosenAnswer1 = null;
try {
...
chosenAnswer1 = read.readLine();
The same for all other chosenAnswers and answer1strings
Your try is missing the catch/finally, otherwise why would you use a try?
http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
read.readLine(); These lines need to be wrapped by try catch OR the method should allow the exception throw.
Strings are immutable, therefore stringA==stringB does not evaluate if the strings are the same, it will evaluate if the two strings are the same Object....
String a = "hello";
String b = "hello";
//a==b is false.
//a.equals(b) is true
String a = "hello";
String b = a;
//a==b is true.
//a.equals(b) is true
your use of == for strings incorrect. Strings should be checked for equality using .equals() For example, this line, and all others below it:
if (chosenAnswer1 == answer1string) {
This should be
if (chosenAnswer1.equals(answer1string)) {

Categories