Boolean and if/else statement help in Java - java

I'm trying to have a user enter an input (their name and age, obviously) and if they're younger than 10 or older than 100, I want it to return back to the start and ask them for their age again, until the condition has been met, and then go on to ask the users name. I know how to do that, a boolean. What I don't know how to do is to implement that into my if/else statements. Could anyone help me?
public class Person {
public static void main(final String[] args) {
int age;
String name;
Scanner scan = new Scanner(System.in);
System.out.println("Enter in your age.");
age = scan.nextInt();
if ((age >= 10) && (age < 18)) {
System.out.println("So you're a kid, huh?");
} else if (age < 10) {
System.out.println("How old are you really?");
} else if ((age >= 18) && (age <= 100)) {
System.out.println("So you're an adult, huh?");
} else if (age > 100) {
System.out.println("How old are you really?");
}
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter in your name");
name = in.nextLine();
System.out.println("So you're " + age + " years old and your name is " + name + "?");
}
}

Use a while loop while the condition is not met:
boolean conditionMet = false;
while(!conditionMet) {
// ...
else if (age >= 18 && age <= 100) {
System.out.println("So you're an adult, huh?");
conditionMet = true; // the condition is met => exit the loop
}
// ...
}

Just put a while loop around your first scan and if statements.
boolean validAge = false;
while (!validAge) {
System.out.println("Enter in your age.");
age = scan.nextInt();
if ((age >= 10) && (age < 18)) {
System.out.println("So you're a kid, huh?");
} else if (age < 10) {
System.out.println("How old are you really?");
} else if ((age >= 18) && (age <= 100)) {
System.out.println("So you're an adult, huh?");
validAge = true;
} else if (age > 100) {
System.out.println("How old are you really?");
}
}

You need a loop:
boolean ageIsCorrect = false;
while (!ageIsCorrect) {
// ask age, if the age is correct, set ageIsCorrect to true
}

Put it inside a while loop
while(age is between your specified critiera)

Roughly something like this:
private static int readAndCheck() {
// read age and validate, upon failure return -1
}
public static void main(final String[] args) {
int age = -1;
while (age == -1) {
age = readAndCheck();
}
System.out.println("So you're " + age + " years old and your name is " + name + "?");
}

You should do that in a while loop. I think it's easier and better than other answers:
int age = 0;
while (age<10 || age>100){
age = scan.nextInt();
}
string username = scan.next();
...

Since you are looping, put the prompting code in a loop. Use a boolean to exit the loop
boolean goodAnswer = false;
do
{
System.out.println("Enter in your age.");
...
if ((age >= 10) && (age 100)
{
... // do not set goodAnswer, because the answer was not good
}
} while (!goodAnswer);

Your code actually needs to be better encapsulated to check the age.
Use a method called isValidAge(age) to return a true or false result and then you can write:
int age = 0;
while(!isValidAge(age)){
System.out.println("Please try again! Not a valid age (for an adult)");
... read in the age using scanner...
}
Generally speaking if else () statements are messy and don't extend well - maintenance wise they are not always the best option.

Related

do while loop is not breaking properly java

public class DoWhile1 {
private static int grade, total, sum, average;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please enter a grade b/w 0-100:");
grade = sc.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum = sum + grade;
System.out.println("Please enter another grade or 999 to break:");
} else {
System.out.println("Incorrect value, please reenter grade:");
}
} while (grade != 999);
average = sum/total;
}
}
This loop is suppose to break when 999 is entered, but when entered before breaking it output error message from the else inside the loop. It's not suppose to output anything before breaking.
we tried moving the while part of the loop, but it did not affect anything. We can't see any other problems with it.
Your do-while is working correctly - the course of action is the following:
In a do-while, the statements are always executed at least once. So you enter the do { }, and fall into the else condition, since 999 is greater than 0 and not smaller than 100.
You then evaluate the expression grade != 999 -> this is false, since grade == 999.
You don't do the do { } again and come out of the do-while.
To achieve the behavior that you want, you will need to add an additional statement inside the do { }, e.g:
...
if (grade == 999) {
break; //or print statement
}
else if (grade >= 0 && grade <= 100) {
...
You could wrapp the message by another if that checks if the number is not 999.
else
{
if (grade != 999) {
System.out.println("Incorrect value, please reenter grade:");
}
}
Change else to else if (grade != 999) when you are displaying the error.
Do it as follows:
import java.util.Scanner;
public class Main {
private static int grade, total, sum, average;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please enter a grade b/w 0-100:");
grade = sc.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum = sum + grade;
System.out.println("Please enter another grade or 999 to break:");
} else if (grade != 999) {
System.out.println("Incorrect value, please reenter grade:");
}
} while (grade != 999);
average = sum / total;
}
}
A sample run:
Please enter a grade b/w 0-100:
24
Please enter another grade or 999 to break:
Please enter a grade b/w 0-100:
999
You could check input value for grade == 999 and exist in case it equals to:
public static double getAverage() {
try (Scanner scan = new Scanner(System.in)) {
int total = 0;
int sum = 0;
int average = 0;
while (true) {
System.out.print("Please enter a grade b/w 0-100 (or 999 to exit): ");
int grade = scan.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum += grade;
} else if (grade == 999)
break;
else
System.out.println("Incorrect value\n");
}
return (double)sum / total;
}
}

Java guess game. How do I use data validation to check if a number is within a certain range?

I need help coding a set of statements of data validation that checks if a user entry is within a range of 0 and 100, and anything the user types that ISNT a non-decimal integer between 1 and 100 should display an error message. Also I need a way to code how I can get a "goodbye" output to only display if the user enters "n" not "n" and "y." N meaning no and y meaning yes.
Heres my code.
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max + " " + "let's see if you guess what it is!");
System.out.println(" ");
}
public static int calculateRandomValue(int max) {
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void validateTheData(int count) {
if( count < 3) {
System.out.println("Good job!");
} else if (count < 7) {
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}
public static void main(String[] args) {
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if ( (unit - userEntry) > 10 ) {
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
validateTheData(counter);
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
}
Instead of using .nextInt() rather use .nextLine(), which returns a String and then parse it to an int and catch the NumberFormatException
So basically you'll have this structure:
try {
int userEntry = Integer.parseInt(sc.nextLine());
...
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
Oh, just a comment on the rest of your code. You don't really need two while loops, one will be more than sufficient.

Java guess game. How do I input data validation(range checking) and how do I input guesses?

I have a project Im working on for class. Its a guessing game that gets a random number and the user guesses what it is. Ive got a working version of the project, but according to my instructions, it needs data validation(range checking would be best) and it also needs to display a certain message depending on how many tries it takes the user to guess correctly. If its less than 3, it should say something like "Good job!" If its more than 3 but less than 7, it should say something like "Need more practice." If its more than 7 it should say something like "Need way more practice." I dont want to have to de-construct my whole project, I would like to just add into it, and tweak accordingly. Can someone give me a way of coding these things?
Heres my code:
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max);
System.out.println(" ");
}
public static int calculateRandomValue(int max){
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void main(String[] args){
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
System.out.println("Too low! Guess higher!");
}else if (userEntry > unit) {
System.out.println("Too high! Guess lower!");
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
public static void validateTheData() { }
}
Seems all you need to do is passing counter variable to validateTheData method and output your message, like this:
...
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if( (unit - userEntry) > 10 ){
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
validateTheData(counter);
break;
}
counter++;
}
...
public static void validateTheData(int count) {
if( count < 3){
System.out.println("Good job!");
} else if( count < 7 ){
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}

Making sure input is not null [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
So below i have an issue that i cant wrap my head around as to why its not working.
The first block of java code works exactly how i wanted it to (e.g. set salary amounts to whatever, and if its not in range give an error and repeat the initial question.)
My problem is this in the second block of code I assumed making a boolean again and emulating the above code to check whether or not my inputs were == "", and if not rinse and repeat like before but it doesnt? i wrote it out exactly the same (of course changing the values) but i simply cant get t to function.
If anyone can help or point me toward the right path id appreciate it :)
//First Block.....
boolean salaryState = false;
while (salaryState == false){
System.out.print("Salary: ");
salary = (input.nextDouble());
if(salary >= 45000 && salary <= 49999) { //if salary amount in this range
this.coachCategory = "Junior"; //then set coaches category to this
salaryState = true;
}
else if(salary >= 50000 && salary <= 59999) { //if salary amount in this range
this.coachCategory = "Youth"; //then set coaches category to this
salaryState = true;
}
else if(salary >= 60000 && salary <= 70000) { //if salary amount in this range
this.coachCategory = "Senior"; //then set coaches category to this
salaryState = true;
}
else { //if invalid salary amount then print error
if (salary <= 45000 && salary >= 70000);
System.out.println("ERROR: Salary range needs to be within 45 000 - 70 000.");
//Second Block...
boolean isName = false;
while (isName == false) {
System.out.print("Name: ");
name = (input.nextLine());
if(name != "") {
this.name = name;
isName = true;
}
else {
if(name == "");
System.out.println("ERROR: Please enter a name.");
}
Replace
name != "" with "name.length()>0"
Your solution will work.
Here is the full solution:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
String heroname;
Scanner input = new Scanner(System.in);
System.out.println("Hello World");
String name;
boolean isName = false;
while(isName==false){
System.out.println("Name: ");
name = (input.nextLine());
if(name.length()>0){
heroname = name;
isName = true;
}else{
System.out.println("Try Again");
}
}
}
}

How can I prevent the user from entering the same text twice

This program basically calculates the gpa, by letting the user enter the number of courses and course code, with the relevant credit and marks. If the course code is entered twice, a message will show (the course is already registered), and it will keep looping until the user has entered all courses with a different course code
I have created two methods. One to check if the code is already registered and the other for calculating the gpa, the first method that checks the user input, I'm not sure about it. Because if I entered the course code twice it will only show the message and would allow me to calculate the rest
public static boolean checkCourse(String[] courseList, String code){
boolean check = false;
for(int i=0 ; i < courseList.length; i++){
if(code.equals(courseList[i]))
check = true;
else
check = false;
}
return check;
}
public static double gradeValue(double marks){
double grade = 1.0;
if(marks >=95){ grade = 5.0;}
else if (marks >= 90) { grade = 4.75;}
else if (marks>=85) { grade = 4.5;}
else if (marks >= 80) { grade = 4.0;}
else if (marks >= 75) { grade = 3.5; }
else if (marks >= 70) { grade = 3.0;}
else if (marks >= 65) {grade = 2.5 ;}
else if (marks >= 60) { grade = 2;}
else if (marks < 60) { grade =1 ;}
return grade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of courses: ");
int n = input.nextInt();
String[] Courses = new String[n];
int sumOfcreadit=0;
int sumOfmarks =0;
for(int i =0; i<Courses.length;i++){
System.out.print("Enter a course code: ");
Courses[i] = input.next();
if(checkCourse(Courses,Courses[i])){
System.out.println("the course already registered");
i--;
}
System.out.print("Enter a credit: ");
int credit = input.nextInt();
System.out.print(" Enter a marks: ");
int marks = input.nextInt();
sumOfcreadit += credit;
sumOfmarks +=marks * credit;
}
double TotalMarks;
TotalMarks = sumOfmarks /sumOfcreadit;
System.out.println("The GPA is: "+gradeValue(TotalMarks));
}
I made some changes in your code and now it works. Changes are described in below code. There was 3 important changes.
I tried to make as less changes as possible to make your code work as expected
public static boolean checkCourse(String[] courseList, String code) {
boolean check = false;
for (int i = 0; i < courseList.length; i++) {
if (code.equals(courseList[i])) { // equals instead of == to compare strings
check = true;
break; // you have to break loop if it is true because else statement before returned false even if there was the same course code due to null values in next array elements which was not filled yet
}
}
return check;
}
public static double gradeValue(double marks) {
double grade = 1.0;
if (marks >= 95) {
grade = 5.0;
} else if (marks >= 90) {
grade = 4.75;
} else if (marks >= 85) {
grade = 4.5;
} else if (marks >= 80) {
grade = 4.0;
} else if (marks >= 75) {
grade = 3.5;
} else if (marks >= 70) {
grade = 3.0;
} else if (marks >= 65) {
grade = 2.5;
} else if (marks >= 60) {
grade = 2;
} else if (marks < 60) {
grade = 1;
}
return grade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of courses: ");
int n = input.nextInt();
String[] Courses = new String[n];
int sumOfcreadit = 0;
int sumOfmarks = 0;
for (int i = 0; i < Courses.length; i++) {
System.out.print("Enter a course code: ");
String code = input.next();
if (checkCourse(Courses, code)){
System.out.println("the course already regestered ");
i--;
continue; // continue is neccessary to let user write value again if it already exists
}
Courses[i] = code;
System.out.print("Enter a credit: ");
int credit = input.nextInt();
System.out.print(" Enter a marks: ");
int marks = input.nextInt();
sumOfcreadit += credit;
sumOfmarks += marks * credit;
}
double TotalMarks;
TotalMarks = sumOfmarks / sumOfcreadit;
System.out.println("The GPA is: " + gradeValue(TotalMarks));
}
Use a set kind of structure to store all the course code visited, It will avoid unnecessary iteration on your course array
this method can be enhanced to
public static boolean checkCourse(HashSet<String> courses, String code){
boolean check = false;
if(courses.contains(code)){
check = true;
else
check = false;
}
return check;
}
Initialise the hashset courses and if the checkCourses method returns false add the course code in courses.
Initialize before loop like this
HashSet<String> courseSet = new HashSet<String>();
your if condition inside loop
if(checkCourse(courseSet,courses[i])){ // check for variable name , name should always start with lower case letter
System.out.println("the course already regestered ");
i--;
// You can use continue if you don't want processing for it
// it will skip the loop iteration and it will go next iteration
}else{
courseSet.add(courses[i]);
}

Categories

Resources