Jump to content

Just started learning some Java in this online course created by the University of Helsinki. There's a small exercise I'm having trouble with. 

 

And here's a link to my code - https://pastebin.com/W0MACx1i

Here's a screenshot of the exercise. I'll appreciate any kind of help!

 

The problem: when I enter 2012 for example, it says it isn't a leap year, even though it is!

image.thumb.png.c51b75150395f3feba66d3ba7faa26ee.png

Link to comment
https://linustechtips.com/topic/1237908-i-need-java-help-very-simple-code/
Share on other sites

Link to post
Share on other sites

The issue with your code is the else if, which checks if the number is divisble by 100 and 400.

During this check, most numbers will fall there.

 

What you're checking if a number is BOTH not divisble by 100 and not divisble by 400. Most number are not cleanly divisble by those two, thus it will trigger as 'not a leap year'.

 

Something like this would work:

if(myYear % 4 == 0)
{
	if(myYear % 400 == 0 || myYear % 100 != 0)
	{
		System.out.println("The year is a leap year.");
	}
	else
	{
		System.out.println("The year is not a leap year.");
	}
}
else
{
	System.out.println("The year is not a leap year.");
}

 It isn't the cleanest code, but I felt it was a bit clearer than then neater variant (which I paste below in the spoiler).

It first checks if a number is divisible by 4. This is the first requirement, easy enough.

Then, follow another if with a OR (||) comparison. If either one or both of the comparisons returns true, it's a match.

 

What it's checking there is:

- is the number cleanly divisible by 400? Then it will be a leap year, no need to even go over the second comparison.

- The second comparison, is the number NOT divisible by 100? With these two checks, I will make sure every "divisible by 100" number will fall away, while all divisible by 4 AND 400 numbers will succeed.

 

The ugliness in that code would be the two else + System.out.println statements.

By combining the two ifs, you get this cleaner code:

Spoiler

if((myYear % 4 == 0) && (myYear % 100 != 0 || myYear % 400 == 0))
{
	System.out.println("The year is a leap year.");
}
else
{
	System.out.println("The year is not a leap year.");
}

Here I do the same as the above code, except in one single if-statement. So first check if it's divisible by 4, then (separated by parenthesis) it checks the 100/400 stuff.

Result of either code:

image.png.1193c077795eb68abd011bbf922f2933.png

 

If anything was unclear, be sure to press the quote button and I would be happy to help you further!

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to post
Share on other sites

20 minutes ago, Crossbourne said:

Just started learning some Java in this online course created by the University of Helsinki. There's a small exercise I'm having trouble with. 

 

And here's a link to my code - https://pastebin.com/W0MACx1i

Here's a screenshot of the exercise. I'll appreciate any kind of help!

 

The problem: when I enter 2012 for example, it says it isn't a leap year, even though it is!

My work was sniped my @minibois. Their work seems to cover everything. A few notes, though...

 

I believe Integer.parseInt is preferred to Integer.valueOf; alternatively, you could use Scanner.nextInt and skip that step entirely.

 

Also, don't forget to close your Scanner (scan.close()) at the end of your program, as good Java etiquette.

Main System (Byarlant): Ryzen 9 5950X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 32GB G.Skill DDR4 3600MT/s CL16 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 990 EVO Plus 4TB | Corsair RM750X | StarTech 4× USB 3.0 Card | Realtek RTL8127 10G NIC | Hyte Y60 Case | Dell U3415W Monitor | Keychron K12 Blue (RGB backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB DDR4 3200MT/s (soldered) | Vega II 384SP Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi | Asus 2.5G USB NIC | Asus ProArt PA278QV | Keychron K4 Brown (white backlight)

 

Proxmox Server (Veda): Ryzen 7 3800XT | ASRock Rack X470D4U | Corsair H80i v2 | 128GB Micron DDR4 ECC 3200MT/s | 2× Samsung PM963a 960GB SSD / 4× WD 10TB / 4× Seagate 14TB Exos / 4× Micron MX500 2TB / 8× WD 12TB (custom external SAS enclosure) | Seasonic Prime Fanless 500W | Intel X550-T2 10G NIC | LSI 9300-8i HBA | Adaptec 82885T SAS Expander | Fractal Design Node 804 Case

 

Proxmox Server (La Vie en Rose)GMKtec Mini PC | Ryzen 7 5700U | 32GB Lexar DDR4 (SODIMM) | Vega II 512SP Graphics | Lexar 1TB 610 Pro SSD | 2× Realtek 8125 2.5G NICs


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / TEAMGROUP MS30 1TB | Corsair CX450M | Viewcast Osprey 260e Video Capture | TrendNet (AQC107) 10G NIC | LG WH14NS40 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Workbench (Doven Wolf): Lenovo m715q | Ryzen Pro 3 2200GE | 16GB Crucial DDR4 3200MT/s (SODIMM) | Vega 8 Graphics | SKHynix (OEM) 256GB NVMe SSD | uni 2.5G USB NIC | HDMI add-in module

 

Network:

Spoiler
                       ┌─────────────── Office/Rack ───────────────────────────────────────────────┐
Google Fiber Webpass ── Cloud Gateway Max ══╦═ Pro XG 8 ══╦═ Flex 2.5-8 ══╦═ Doven Wolf
                      La Vie en Rose (DNS) ═╬═ Narrative  ╠═ Veda-NAS     ╠═ La Vie en Rose (vmbr)
                                Veda (DNS) ─┘             ╠═ Veda (vmbr)  ├─ Ptolemy (vmbr)
╔═════════════════════════════════════════════════════════╩═ Ptolemy-NAS  ├─ Veda (Mgmt)
║   ┌ Closet ┐      ┌───────── Bedroom ─────────┐                         └─ Veda (IPMI)
╚═══ Flex XG ══╦╤═══ Flex XG ══╤╦═ Byarlant
       (PoE)   ║│              │╠═ Narrative 
Kitchen Jack ══╣└─ Dual PoE ┐  │╚═ Jesta Cannon*
   (Testing)   ║┌─ Injector ┘  └── Work Laptop
     Bedroom ══╝│        ┌─────── Media Center ────────────────────────────┐
     Jack #2    └──────── Switch 8 ────────────┬─ nanoHD Access Point (PoE)
Notes:                                         ├─ Sony PlayStation 4 
─── is Gigabit / ═══ is Multi-Gigabit          ├─ Pioneer VSX-S520
* = cable passed from Bedroom to Media Center  └─ Sony XR65A80K (Google TV)
Link to post
Share on other sites

@minibois @AbydosOne Thank you so much to both of you guys! I was initially confused about the criteria regarding the calculation of leap years. Turns out it should be divisible by all three numbers (4, 100, 400). I was also worried about nested if else statements, but you just taught me a better way to do it. Much appreciated!

Link to post
Share on other sites

11 hours ago, Crossbourne said:

@minibois @AbydosOne Thank you so much to both of you guys! I was initially confused about the criteria regarding the calculation of leap years. Turns out it should be divisible by all three numbers (4, 100, 400). I was also worried about nested if else statements, but you just taught me a better way to do it. Much appreciated!

The way leap years work, you just have look at a year and check these two criteria:

- divisible by 4 and NOT by 100? Leap year.

- divisible by 400? Leap year.

Anything else isn't a leap year, so it's all about writing something that checks both these scenarios.

11 hours ago, Crossbourne said:

This is what really confused me at first. 
image.thumb.png.5236dd68a3b9303e7e3ca714e1dcb39c.png

It has always been a debate whether you should start from a place where you know it's true or false.

Personally I have always learned: assume the number will fail (won't be a leapyear) unless proven otherwise (by and if statement).

So by that logic, I would do an if statement to see if a number falls within the requirements and otherwise it will fall into else statement and won't work.

 

EDIT: I just realized this comparison is way simpler and cleaner:

if(((myYear % 4 == 0) && (myYear % 100 != 0)) || (myYear % 400 == 0))
{
	console.log("The year is a leap year.");
}
else
{
	console.log("The year is not a leap year.");
}

This just checks these two:

Quote

- divisible by 4 AND not by 100?

OR

- divisible by 400?

= true

 

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×