simulating one year with simple car - java

Create a method that loops from 1 to 365 to represent days in a year. Any even multiple of 7 represents Sunday. Therefore, day 1 is Monday and day 6 is Saturday.
The car is driven to work and back home on Monday through Friday. Use the dist parameter as the distance each way.
Every Saturday, the driver checks the oil and changes it if necessary. She also fills the gas tank without driving. Assume she lives at a gas station? The car is not driven on Sunday.
No additional messages are printed beyond the ones already embedded in the other methods.
public void simulateOneYear(int dist)- see above.
I have created the method and it runs well I am just unable to figure out how to add the miles driven to have the total at the end of the year.
Would I simply add dist each time I drive?
This is what I have so far (also I am new to this site so I'm sorry if it doesn't formal well)
public void simulateOneYear (int dist){
int day = 1;
for(int i = 1; i < 366; i++){
if(day != 6 && day != 7){
this.startEngine();
this.drive(dist);
this.stopEngine();
this.startEngine();
this.drive(dist);
this.stopEngine();
}
if(day == 6){
if(this.checkOil){
this.changeOil();
}
this.addGas(this.TANK_CAPACITY - this.checkGasGauge());
}
if(day==7){
day = 1;
}
else {
day++;
}
}
}

Related

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.

Iterator between two given hours

I was in a job interview and got this question: " Write a function that gets 2 strings s,t that represents 2 hours ( in format HH: MM: SS ). It's known that s is earlier than t.
The function needs to calculate how many hours between the two given hours contains at most 2 digits.
For example- s- 10:59:00, t- 11:00:59 -
Answer- 11:00:00, 11:00:01,11:00:10, 11:00:11.
I tried to do while loops and got really stuck. Unfortunately, I didn't pass the interview.
How can I go over all the hours (every second is a new time) between 2 given hours in java as explained above? Thanks a lot
Java 8 allows you to use LocalTime.
LocalTime time1 = LocalTime.parse(t1);
LocalTime time2 = LocalTime.parse(t2);
The logic would require you to count the amount of different digits in a LocalTime, something like
boolean isWinner(LocalTime current) {
String onlyDigits = DateTimeFormatter.ofPattern("HHmmss").format(current);
Set<Character> set = new HashSet<>();
for (int index = 0; index < onlyDigits.length(); index++) {
set.add(onlyDigits.charAt(index));
}
return set.size() <= 2;
}
You can loop between the times like this
int count = 0;
for (LocalTime current = time1; current.isBefore(time2); current = current.plusSeconds(1)) {
if (isWinner(current)) {
count++;
}
}
That's it.
The question is really more geared towards getting a feel of how you'd approach the problem, and if you know about LocalTime API etc.

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.

Java leapyear check program. No response to edge values

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();`

Categories

Resources