Java leapyear check program. No response to edge values - java

I'm working on a program for school to take a year input from the user and check to see if it is a leap year or not. It should also check to see if the year is prior to 1582 and return an error if it is. I'm having an issue that if the user enters a year between [1582, 1599] that the program halts and doesn't print anything. If I change the value to 1600 it doesn't return anything between [1600, 1639]. Not sure why this behavior is happening. Any help would be appreciated.
import java.util.Scanner;
public class Leapyear {
public static void main(String[] args) {
Scanner Jeff = new Scanner(System.in);
//System.out.print("Run Leapyear progra? Enter true or false: ");
//boolean RunLoop$ = Jeff.nextBoolean();
System.out.print("\nPlease enter a year: ");
int Year = Jeff.nextInt();
//while(RunLoop$ = true)
if (Year <= 1582)
System.out.println("The entered year is prior to the Gregorian Callandar");
else
if (Year % 4 == 0)
if (Year % 400 + Year % 100 == 0)
System.out.println("The entered year is a leapyear");
else
System.out.println("The Entered year is not a leapyear");
}
}

Your if statements are incorrect. I second David's comment and strongly advise to use brackets for every if statement (which is also recommended in the - albeit ancient, but mostly still valid - Code Conventions for the Java Programming Language).
Furthermore, switching to a decent IDE and/or making use of its source code formatting support will greatly help you with these kinds of issues.
A simple (automatic) cleanup leads to the following snippet for your if statements, which is fully equivalent in terms of application logic:
if (Year <= 1582) {
System.out.println("The entered year is prior to the Gregorian Callandar");
} else if ((Year % 4) == 0) {
if (((Year % 400) + (Year % 100)) == 0) {
System.out.println("The entered year is a leapyear");
} else {
System.out.println("The Entered year is not a leapyear");
}
} // else?
You can now clearly see that there won't be any output if Year is greater than 1582 but not divisible by 4.

if you don't use the {} curly brackets for every if and else statement then it will only consider the first line after the condition so in
else
[empty line]
if (Year %4 ==0)
[empty line]
means after else it will do nothing the same after the if because only the first line under it is considered which is empty.
Another problem you'll be having is that your while loop will go forever :) since the boolean value will always remain true. If you want to make user insert a new value each time then just insert at the end of the while loop.
System.out.print("add another year ? ");
RunLoop$ = Jeff.nextBoolean();
Year = Jeff.nextInt();`
or add Jeff.hasnextInt()in the while loop condition instead removing the Boolean entirely so when user enters anything other than an int value the loop breaks.while(Jeff.hasnextInt()) and at the end of the loop.
System.out.print("add another year ? ");
Year = Jeff.nextInt();`

Related

Validate integer

This is a program that allows the user to build a high school schedule.
I would like to validate an integer as a high school class number in my String method. Here's the name of my method with the parameters.
public static String addClass(String name, String day, String momentOfDay, int group){
The user has to put an integer as the value of a school class number. The number has to start with a specific number according to the day of class. Here's a table that explains the validation wanted
Day of Class | Valid Group
Monday | The first number of the group must start with 1 ( example 10, 14...)
Tuesday | The first number of the group must start with 2 ( example 20, 22...) ______________________________________________________________________________
Wednesday | The first number of the group must start with 3 ( example 30, 31...) ______________________________________________________________________________
Thursday | The first number of the group must start with 4 ( example 40, 31...) ______________________________________________________________________________
Friday | The first number of the group must start with 5 ( example 50, 56...)
Here's what the output should look like ( the terms in bold are the entered values by the user ) :
**********************
ADD CLASS TO SCHEDULE
**********************
Name of class : **INF1120**
Day of class : **Monday**
Moment of the day of the class : **PM**
Group of class : **12**
I'm using the scanner to allow the user to enter the wanted integer.
I completed the name of class, day and moment of the day part.
However, I'm having a hard time to validate the first number of the group integer according to the days in the table. Here's my code :
import java.util.Scanner;
public class schedule {
public static String addClass(String name, String day, String momentOfDay, int group) {
Scanner keyboard = new Scanner(System.in);
System.out.print("day of class: ");
day = keyboard.nextLine();
if( day != "monday" || day != "tuesday" || day != "wednesday"
|| day != "thursday" || day != "friday" ) {
System.out.print("Error, the day has to be either : monday, tuesday, wednesday, thursday, or friday...");
}
else if(day = "monday" || day = "tuesday" || day = "wednesday"
|| day = "thursday" || day = "friday" ) {
return day;
}
System.out.print("Moment of day: ");
momentOfDay = keyboard.nextLine();
if(momentOfDay != "am" || momentOfDay != "pm" || momentOfDay != "night") {
System.out.print("Error, the moment of the day has to be : am, pm, or evening...");
}
else if(momentOfDay == "am" || momentOfDay == "pm" || momentOfDay == "evening") {
return momentOfDay;
}
System.out.print("Class group");
group = keyboard.nextInt();
while(day == "monday" || day == "tuesday" || day == "wednesday"
|| day == "thursday" || day == "friday"){
if (String.valueOf(Math.abs(int(group)).charAt(0) == 1){
return group;
}
else {
System.out.print("Error, group number is invalid");
}
}
}
}
However, it is not compiling because the return value cannot be an int which is required. Here's the error.
Type mismatch: cannot convert from int to String
It is asking me to either change the return type to int or change the type of group to String.
Should I change the type of group in the parameter ? What did I do wrong ?
I tried to research the methods in this link but can't seem to figure it out.
When I copied the code of class schedule that you posted, I got a compilation error for this line:
if (String.valueOf(Math.abs(int(group)).charAt(0) == 1){
The int should be removed. group is a parameter of method addClass() and it is an int. So the line of code should be:
if (String.valueOf(Math.abs(group)).charAt(0) == 1){
After correcting that line, the line following it causes a compilation error. That line is:
return group;
Method addClass() is declared to return a String but group is an int. So that line should be changed to:
return String.valueOf(group);
After correcting that line of code, I got yet another compilation error, namely that the method does not return a value. This is the while loop in method addClass():
while (day == "monday" || day == "tuesday" || day == "wednesday" || day == "thursday"
|| day == "friday") {
If day is "sunday", the loop is terminated. There needs to be a return statement after that while loop.
But even after fixing all the compilation errors, your code will not work due to logic errors. I just showed you one of those errors in the while loop. Similarly this if statement will not do what you want.
if (day != "monday" || day != "tuesday" || day != "wednesday" || day != "thursday"
|| day != "friday")
Besides that fact that you need to use method equals() to check if two strings are equal, if day is "tuesday", then the first condition, namely day != "monday" is true. If you want to ensure that the user enters a valid day, then you need the following:
if ("monday".equals(day) ||
"tuesday".equals(day) ||
"wednesday".equals(day) ||
"thursday".equals(day) ||
"friday".equals(day)) {
return day;
}
else {
System.out.print(
"Error, the day has to be either : monday, tuesday, wednesday, thursday, or friday...");
}
If day and momentOfDay and group are all parameters of method addClass(), why do you ask the user to enter these values inside method addClass() ? Also the other method parameter, name, is never used in the method.
I think you need to create three, separate methods. One to get the day from the user, another to get the momentOfDay and yet another to get the group.
I suggest you read the book Java by Comparison by Simon Harrer, Jörg Lenhard, Linus Dietz

Finding day of week given date (no libs or package imports allowed)

I want to create a Java Program that takes a date as input (27,2,2019) and print out what day it was. I am just assuming the usage of Gregorian Calender only. The reference is 1,1,1 which is a Monday. I am unable to complete this. Can someone help me out please. I also took leap years to account. Also, in this project, I am not allowed to import any packages so I should do it normally.
public class sortday
{
public static void main (String [] args)
{
sortdayoftheyear(1,1,2019);
}
public static void sortdayoftheyear(int day, int month, int year)
{
final int [] months = {31,28,31,30,31,30,31,31,30,31,30,31};
{
final int monthnum = 12;
int totaldays=0;
int newmon = month-1; //find which month it is
int monthdays = months[newmon]; // find days of the month
for (int i = 1; i < year; i++)
{
if (i%100 != 0 && i%4 == 0 && i%400 == 0) //check for leap year
{
totaldays = i*366;
}
else
totaldays = i*365;
}
totaldays += (day) + (newmon*monthdays);
if (totaldays%7 == 4)
System.out.println("Sunday");
if (totaldays%7 == 5)
System.out.println("Monday");
if (totaldays%7 == 6)
System.out.println("Tuesday");
if (totaldays%7 == 0)
System.out.println("Wednesday");
if (totaldays%7 == 1)
System.out.println("Thursday");
if (totaldays%7 == 2)
System.out.println("Friday");
if (totaldays%7 == 3)
System.out.println("Saturday");
System.out.println("It had been " + totaldays + " since January 1,AD");
}
}
}
There seems to be more than one bug in your code. I have spotted:
Each time through your for loop you are assigning a new value to totaldays. In this way only the last time through the loop has any effect in the end. I believe you intended every iteration to contribute.
As yole said in a comment, newmon*monthdays is incorrect for the total number of days in the first newmon months of the year. I even think that for February 13 your are counting 13 + 1 * 28, which can’t be right. One suggestion is you loop through the months and add up their lengths.
If the entered year is a leap year, you are always counting 28 days in February. You want to count 29 sometimes. An auxiliary method to determine whether a year is a leap year would come in handy.
If your reference date of January 1, 1 is a Monday, I think you want to print this when the modulo operation in the end yields 1. You are printing Thursday in this case.
I can’t tell if there may be more.
Issues without functional consequences that you should nevertheless want to fix include:
You are not using the constant monthnum, so delete it.
You have a superfluous set of braces around the code piece from the mentioned constant down to System.out.println. Delete those too.
Get your indentation right so you and I can read your code.
When writing code for others to read (including Stack Overflow users), respect the naming conventions. Call the class SortDay or FindDayOfWeek. The method sortDayOfTheYear or printDayOfWeek.

Java, I dont understand why this is happening, variable changes

public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
String enteredDate = in.nextLine();
//This array will hold the 3 elements of which the date is made up of, day, month and year, and this method returns it.
String[] dateEnteredSplit = enteredDate.split("/");
//I am using the split method to seperate each number, which returns an array, so I am assigning that array to the dateEnteredSplit array.
//dateEnteredSplit = enteredDate.split("/");
//So now the first element holds the day, second the month, and the third element holds the year.
//System.out.println(Arrays.toString(dateEnteredSplit));
//Assigning each element and converting them to integers.
int day = Integer.parseInt(dateEnteredSplit[0]);
int month = Integer.parseInt(dateEnteredSplit[1]);
int year = Integer.parseInt(dateEnteredSplit[2]);
**System.out.println("day: " + day + " month: " + month + " year: " + year);**
//The loop will be entered if any of the values are wrong. which will use recursion to call this method again for a chance to enter the date again.
while (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000)) {
**System.out.println("day: " + day + " month: " + month + " year: " + year);**
//Im calling these methods to inform which one specifially was wrong so they know what they need to change.
this.setDay(day);
this.setMonth(month);
this.setYear(year);
dateEnteredSplit[0] = "0";
askForDate(in);
}
//I then assign any correct value into the object attribute because the while loop is either finished or not entered at all.
//No need to use setDay etc. here because the checks have been done above in the while loop.
this.day = day;
this.month = month;
this.year = year;
}
Ok that is a method in a class. It asks for input in the format dd/mm/yyyy
If the first time I input 12/1/1996 it works, but if I enter a wrong date for example like this first, 123/123/123 and the enter a correct date for example 12/1/1996, it still enters the loop.
After debugging, the first line that is bold, the values are different from the second line that is bold, its like the values are changing by their own.
What is the problem here? I have been trying to find out in the past 1 hour.
Thanks in advance!
The problem very likely is in the way you are trying to combine recursive and iterative approach to update values (there is a while loop, that call the function recursively, which may also trigger while loop in next level of call and the previous one will continue calling itself recursively and you will end up with just mess)
There is no real reason to do that recursively, I would do iterative only approach, something like this:
public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
int day, month, year;
do { // We use do-while to get the first read without condition, although setting date to invalid value (like day = 0) and then running standard while loop will work just as fine
String[] dateEnteredSplit = in.nextLine().split("/");
//Assigning each element and converting them to integers.
day = Integer.parseInt(dateEnteredSplit[0]);
month = Integer.parseInt(dateEnteredSplit[1]);
year = Integer.parseInt(dateEnteredSplit[2]);
} while (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000));
// Now day month and year variables are set correctly and we can do stuff with it
}
If you insist or recursive approach, the correct way would be to call the function just once:
public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
int day, month, year;
String[] dateEnteredSplit = in.nextLine().split("/");
//Assigning each element and converting them to integers.
day = Integer.parseInt(dateEnteredSplit[0]);
month = Integer.parseInt(dateEnteredSplit[1]);
year = Integer.parseInt(dateEnteredSplit[2]);
if (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000)) askForDate(in);
// You need to save day/month/year variables to other than local scope (like this.day = day)
// Otherwise it would just somewhere in recursion stack and you wouldn't be able to use it
}
Just to be complete, keep in mind that date string could be wrong in other way that just number out of range. What if user types 1. 2. 3456 or a/b/c or not even something very different like Hello
At your snippet of code would crash (either throw NumberFormatException when trying to parse non-integer or ArrayIndexOutOfBoundsException when accessing dateEnteredSplit array at element that doesnt exists (there are no '/' in 'Hello'))
Here is what happens. Wrong values on a first while loop iteration make a call to askForDate possible. You receive a second prompt and provide correct input. The second call of askForDate ends as expected. The execution returns again to a while loop, where you still have the first wrongly set values and the process starts again.
If you really do want to use recursion here, you should return a value from your function (dates or boolean flag) and check it in a while loop condition.

How can I prevent null from showing up?

Sorry I'm a beginner so the answer may be obvious but I'm trying to make a code where it will tell you your horoscope based on your dob and based off that tell you your daily, monthly, and yearly horoscope.
import java.io.*;
public class MysticLady {
static String zodiacSign = "";
static String dailyDescript = "";
private static java.util.Scanner myScanner;
public static void main(String[] args) throws Exception
{
BufferedReader keyIn = new BufferedReader (new InputStreamReader(System.in));
Thread.sleep(1000);
System.out.println("Welcome user to the world of the mystic truths!");
Thread.sleep(3000);
System.out.println("My name is Mirela and will be telling you all about you...");
Thread.sleep(3000);
System.out.println("But first, what is your name?");
myScanner = new java.util.Scanner(System.in);
String name = myScanner.nextLine();
Thread.sleep(1000);
System.out.println( name + ", what a lovely name");
Thread.sleep(3000);
System.out.println("Well " + name + ", I need to first know your date of birth");
Thread.sleep(3000);
System.out.println("Keep in mind that by knowing this I will be able to tell you certain things");
Thread.sleep(3000);
System.out.println("We currently have daily, monthly, and yearly horoscopes available");
Thread.sleep(3000);
System.out.println("Now first tell me what month were you born (1-12)");
int month = Integer.parseInt(keyIn.readLine());
System.out.println("Now what day were you born?");
int day = Integer.parseInt(keyIn.readLine());
Thread.sleep(1000);
System.out.println(name + ", the galaxy is telling me that your zodiac sign is " + MysticHoroscope1.getZodiacSign());
System.out.println("Now that we know your sign, would you like to know your daily, monthyly, or yearly horoscope?");
String horotype = myScanner.nextLine();
{
if (horotype.equalsIgnoreCase("daily"))
{
Thread.sleep(1000);
System.out.println("Today is May 11, 2017");
System.out.println("Your horoscope for today is...");
System.out.println("" + MysticHoroscope1.getDailyDescript());
if (horotype.equalsIgnoreCase("monthly"))
{System.out.println("");
if (horotype.equalsIgnoreCase("yearly"))
{System.out.println("");
}
}}}}}
public class MysticHoroscope1 {
private static String zodiacSign;
int month;
int day;
public MysticHoroscope1(int m, int d)
{
int month = m;
int day = d;
switch (month)
{
case 1 :
if (day > 0 && day <= 20)
setZodiacSign("Capricorn");
else if (day > 20 && day < 32)
setZodiacSign("Aquarius");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 2 :
if (day > 0 && day <= 19)
setZodiacSign("Aquarius");
else if (day > 19 && day < 30)
setZodiacSign("Pisces");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 3 :
if (day > 0 && day <= 20)
setZodiacSign("Pisces");
else if (day > 20 && day < 32)
setZodiacSign("Aries");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 4 :
if (day > 0 && day <= 20)
setZodiacSign("Aries");
else if (day > 20 && day < 31)
setZodiacSign("Taurus");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 5 :
if (day > 0 && day <= 21)
setZodiacSign("Taurus");
else if (day > 21 && day < 32)
setZodiacSign("Gemini");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 6 :
if (day > 0 && day <= 21)
setZodiacSign("Gemini");
else if (day > 21 && day < 31)
setZodiacSign("cancer");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 7 :
if (day > 0 && day <= 22)
setZodiacSign("Cancer");
else if (day > 22 && day < 32)
setZodiacSign("Leo");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 8 :
if (day > 0 && day <= 21)
setZodiacSign("Leo");
else if (day > 21 && day < 32)
setZodiacSign("Virgo");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 9 :
if (day > 0 && day <= 23)
setZodiacSign("Virgo");
else if (day > 23 && day < 31)
setZodiacSign("Libra");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 10 :
if (day > 0 && day <= 23)
setZodiacSign("Libra");
else if (day > 23 && day < 32)
setZodiacSign("Scorpio");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 11 :
if (day > 0 && day <= 22)
setZodiacSign("Scorpio");
else if (day > 22 && day < 31)
setZodiacSign("Sagittarius");
else
setZodiacSign("Sorry, that's not a valid date");
break;
case 12 :
if (day > 0 && day <= 22)
setZodiacSign("Sagittarius");
else if (day > 22 && day < 32)
setZodiacSign("Capricorn");
else
setZodiacSign("Sorry, that's not a valid date");
break;
default :
setZodiacSign("Sorry, that's not a valid date");
}
}
public void MysticHoroscope(int month2, int day2) {
}
public static String getZodiacSign() {
return zodiacSign;
}
public static void setZodiacSign(String zodiacSign) {
MysticHoroscope1.zodiacSign = zodiacSign;
}
public static String dailyDescript;
{
if (zodiacSign.equals("Capricorn"))
setDailyDescript("There are many ways to journey through life,\nbut you will only know the path you choose to travel.\nThis is a wonderful day to expose yourself to new art,\nespecially if it's from a different culture.\nTurn the dial on your radio or television to a foreign-language broadcast.\nLeave it there for a few minutes. You'll be surprised how intriguing you find it.\nEvery now and then, it's wise to travel down an unfamiliar side street.");
if (zodiacSign.equals("Aquarius"));
setDailyDescript("Stand up for yourself and watch how quickly people back down.\nToday, you will be able to talk to absolutely anyone--even the folks who usually intimidate you.\nIt's a great day to ask for a raise, try to get some face time with the big boss, or ask someone out on a date.\nYou'll give off an unmistakable air of confidence, which might be a bit stronger than what you actually feel.\nThis level of boldness could open up some very important doors for you.");
if (zodiacSign.equals("Pisces"));
setDailyDescript("Finding a balance between what you want and what is best for everyone involved is important today.\nBefore making any decisions, you have to factor in other people's feelings and goals.\nThis could be difficult, because you can't exactly read minds.\nLuckily, your intuition is strong, and you can sense what people want.\nDon't bend too far backward to accommodate them, though.\nJust let them know you considered their feelings -- that's plenty of incentive.");
}
public static String getDailyDescript() {
return dailyDescript;
}
private static void setDailyDescript(String dailyDescript) {
MysticHoroscope1.dailyDescript = dailyDescript;
}
}
Everything "works" except for the actual answer.
name, the galaxy is telling me that your zodiac sign is null
Now that we know your sign, would you like to know your daily, monthyly, or yearly horoscope?
daily
Today is May 11, 2017
Your horoscope for today is...
null
Issues include:
You're setting the class variable dailyDescript in an instance initializer. You want an instance member. Remove static from the declaration.
That initializer gets called before setZodiacSign() is called, and then never again. You'll want to either move that code so that it can be called after setZodiacSign(), or initialize the zodiac sign and description in the constructor.
When you move that code to allow calling it from setZodiacSign(), you'll need to cover all the zodiac signs in that code, and ideally, provide a final else that handles bad values in some way.
You have global variables in the class containing main() that are neither necessary nor used.
I try to modify your code as little as possible for the answer (even if everything in my body strive against it).
Your class MysticLady
You have:
Thread.sleep(1000);
System.out.println(name + ", the galaxy is telling me that your zodiac sign is " + MysticHoroscope1.getZodiacSign());
Problem:
The class MysticHoroscope1 contains the logic for the horoscopy in the constructor, but that one is never called.
Solution. Just add one line in between:
Thread.sleep(1000);
new MysticHoroscope1(month, day);
System.out.println(name + ", the galaxy is telling me that your zodiac sign is " + MysticHoroscope1.getZodiacSign());
The class MysticHoroscope1 contains
Next class MysticHoroscope1
You have:
public static void setZodiacSign(String zodiacSign) {
MysticHoroscope1.zodiacSign = zodiacSign;
}
public static String dailyDescript;
{
if (zodiacSign.equals("Capricorn"))
setDailyDescript("There are many ways to journey through life,\nbut you will only know the path you choose to travel.\nThis is a wonderful day to expose yourself to new art,\nespecially if it's from a different culture.\nTurn the dial on your radio or television to a foreign-language broadcast.\nLeave it there for a few minutes. You'll be surprised how intriguing you find it.\nEvery now and then, it's wise to travel down an unfamiliar side street.");
if (zodiacSign.equals("Aquarius"));
setDailyDescript("Stand up for yourself and watch how quickly people back down.\nToday, you will be able to talk to absolutely anyone--even the folks who usually intimidate you.\nIt's a great day to ask for a raise, try to get some face time with the big boss, or ask someone out on a date.\nYou'll give off an unmistakable air of confidence, which might be a bit stronger than what you actually feel.\nThis level of boldness could open up some very important doors for you.");
if (zodiacSign.equals("Pisces"));
setDailyDescript("Finding a balance between what you want and what is best for everyone involved is important today.\nBefore making any decisions, you have to factor in other people's feelings and goals.\nThis could be difficult, because you can't exactly read minds.\nLuckily, your intuition is strong, and you can sense what people want.\nDon't bend too far backward to accommodate them, though.\nJust let them know you considered their feelings -- that's plenty of incentive.");
}
Problems:
The description for the horoscope is initialized in an anonymous block when the class is instantiated and depends on the zodiacSign. But the zodiacSign is initialized in the constructor (actually after the anonymous block is evaluated)
The if-statements ends with colons
Solution. Make this:
public static void setZodiacSign(String zodiacSign) {
MysticHoroscope1.zodiacSign = zodiacSign;
if (zodiacSign.equals("Capricorn"))
setDailyDescript("There are many ways to journey through life,\nbut you will only know the path you choose to travel.\nThis is a wonderful day to expose yourself to new art,\nespecially if it's from a different culture.\nTurn the dial on your radio or television to a foreign-language broadcast.\nLeave it there for a few minutes. You'll be surprised how intriguing you find it.\nEvery now and then, it's wise to travel down an unfamiliar side street.");
if (zodiacSign.equals("Aquarius"))
setDailyDescript("Stand up for yourself and watch how quickly people back down.\nToday, you will be able to talk to absolutely anyone--even the folks who usually intimidate you.\nIt's a great day to ask for a raise, try to get some face time with the big boss, or ask someone out on a date.\nYou'll give off an unmistakable air of confidence, which might be a bit stronger than what you actually feel.\nThis level of boldness could open up some very important doors for you.");
if (zodiacSign.equals("Pisces"))
setDailyDescript("Finding a balance between what you want and what is best for everyone involved is important today.\nBefore making any decisions, you have to factor in other people's feelings and goals.\nThis could be difficult, because you can't exactly read minds.\nLuckily, your intuition is strong, and you can sense what people want.\nDon't bend too far backward to accommodate them, though.\nJust let them know you considered their feelings -- that's plenty of incentive.");
}
public static String dailyDescript;
I strongly encourage you to rethink your design.
zodiacSign is holding the value of null in your program, so that's what it is printing. I would suggest you to check for null to eliminate that issue.
Your null check should look like this:Previously it was the same only not commented
if (zodiacSign!=null && !zodiacSign.isEmpty) {
//do your stuff here...
} else {
//what you want to do if get null zodiacSign
}
this is not an issue, but i suggest trying to format your code for better readability as it is staggered.

Input Validation regarding integers corresponding to days of the week

I have been reading through Java documentation, but I cannot really seem to find a solution. My program asks for a number of 1-7 corresponding to a day of the week. I want the program to return an error "Sorry, not a valid number" when they enter a wrong number, such as 8,9,20 etc (since they do not correspond to a specific day of the week) My method is not working, any input?
while (!stdln.hasNextInt(1,2,3,4,5,6,7)) {
System.out.println("Sorry, not a valid number.");
stdln.next();
}
I tried
while (dayOfTheWeek > 7) {
System.out.println("Sorry, try again");
stdln.next();
}
But this gets me stuck in a loop
This should do what you want. It will get an int from the user and report when the int out of range. You need to add a terminating condition that will break the loop or it will run until you terminat the application:
while (stdIn.hasNextInt()) {
dayOfTheWeek = stdIn.nextInt();
if (dayOfTheWeek == 0) {
System.out.println("Zero was entered. Exiting");
break;
}
if (dayOfTheWeek < 1 || dayOfTheWeek > 7) {
System.out.println("Sorry, not a valid number.");
}
// do something else with dayOfTheWeek
}
This method call in your code is invalid. This method doesn't take 7 integers as arguments :
stdln.hasNextInt(1,2,3,4,5,6,7)
Also keep in mind that next() method will get every char you input including new lines. You will also have to assign the result of next to a variable for it to be any use.

Categories

Resources