Number of Leap Years within two specific years - java

I have a small problem. I figured out how to solve this program, but I can't get the output to output ALL the leap years in a table format. Instead, the output shoots out the leap years one at a time, which is something I don't want with my program.
What could be the problem?
EDIT:
I'm trying to get all the years to pop out using a "JOptionPane" message box (JOptionPane.showMessageDialog(null, " ");), but I keep getting only one output per box and many boxes... compared to all the outputs in just one box.
Here is the code:
String enterYear = JOptionPane.showInputDialog(null, "Enter the starting year: \nExample: 2015"); // User enters an input (Year)
String enterLastYear = JOptionPane.showInputDialog(null, "Enter the ending year: ");
int i = Integer.parseInt(enterYear);
if (Integer.parseInt(enterYear) < Integer.parseInt(enterLastYear)){
for (i = Integer.parseInt(enterYear); i < Integer.parseInt(enterLastYear); i += 4){
if(i % 400 == 0 || i % 4 == 0) {
JOptionPane.showMessageDialog(null, i + "\n");
}
}
} else {
JOptionPane.showMessageDialog(null, "Error: Starting Year is greater than Ending Year!");
}
}
}

You Simply need to build the message before passing it to the JOptionPane.
Sample Code:
public class LeapYearTest {
public static void main(String[] args) {
LeapYearTest leapYearTest = new LeapYearTest();
leapYearTest.showLeapYears(2000, 2020);
leapYearTest.showLeapYears(2000, 2000);
}
private void showLeapYears(int start, int end) {
StringBuffer msg = new StringBuffer();
if (start < end) {
msg.append("<html><table><tr><td><b>Leap Years</b></td></tr>");
for (int i = start; i < end; i++) {
if(i % 400 == 0 || i % 4 == 0) {
msg.append("<tr><td>" + i + "</td></tr>");
}
}
msg.append("</table></html>");
} else {
msg.append("Error: Starting Year is greater than Ending Year!");
}
JOptionPane.showMessageDialog(null, msg.toString());
}
}
Outputs:

I think you should replace i += 4 with i++. Also correct formula for leap year is
year % 4 == 0 && year % 100 != 0 || year % 400 == 0

I guess you can apply this logic
public void calculateLeapYears(int fromYear,int tillYear){
int count=0;
int firstLeapYear;
if(fromYear% 4==0)
firstLeapYear=fromYear;
else
firstLeapYear=fromYear+(4-fromYear%4);
for(int i=firstLeapYear;i<=tillYear;i+=4)
count++;
System.out.println(count);
}

Related

Trying to correctly determine whether numbers are weird

Made a program that prints if a number is weird or not. If the number is odd, it's weird. If the number is even and inclusively between 2 and 5, it is not weird. If it's even and inclusively between 6 and 20, it's weird, and if it's even and greater than 20, it's not weird. The problem I'm having here is that instead of the output displaying "This number is weird/not weird", I get "Weird" or "Not Weird" on one line, followed by "This number is 0" if it's even, or "This number is 1" if it's odd.
public Weird(int num)
{
n = num;
}
public int EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && answer >= 2 && answer <= 5)
{
System.out.println("Not Weird");
}
else if (check == 0 && answer >= 6 && answer <= 20)
{
System.out.println("Weird");
}
else if (check == 0 && answer > 20)
{
System.out.println("Not Weird");
}
else if (check != 0)
{
System.out.println("Weird");
}
return check;
}
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
You actually return int which is value of check field. This is either 1 or 0.
When you call this line-
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
It prints either This number is 0 or This number is 1.
You can get desired output by two ways-
Way 1-
Change return type of method to void EvenOrOdd() like-
public void EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n >= 2 && n<= 5)
{
System.out.println("Not Weird");
}
else if (check == 0 && n>= 6 && n<= 20)
{
System.out.println("Weird");
}
else if (check == 0 && n> 20)
{
System.out.println("Not Weird");
}
else if (check != 0)
{
System.out.println("Weird");
}
}
and call method in main as-
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
w.EvenOrOdd();
a.EvenOrOdd();
}
Way 2- Change return type of method to String as-
public String EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n>= 2 && n<= 5)
{
return "Not Weird";
}
else if (check == 0 && n>= 6 && n<= 20)
{
return "Weird";
}
else if (check == 0 && n> 20)
{
return "Not Weird";
}
else
{
return "Weird";
}
}
And main method remains same-
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
You should return that string rather than printing it. In your function, you are returning an int but rather you should write a String. Besides that everything looks good but you can decrease the number of check like below:
public Weird(int num)
{
n = num;
}
public String EvenOrOdd()
{
int check = n % 2;
if (check == 1 || (check == 0 && n >= 6 && n <= 20)) {
return "Weird";
}else{
return "Not Weird";
}
}
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
The value you return from a method will kind of "replace" the method call. Because you returned check:
return check;
The calls:
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
are basically:
System.out.println("This number is " + 0);
System.out.println("This number is " + 1);
You seem to be confused about returning and printing. Your method should look like this:
public String EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n >= 2 && n <= 5)
{
return "Not Weird";
}
else if (check == 0 && n >= 6 && n <= 20)
{
return "Weird";
}
else if (check == 0 && n > 20)
{
return "Not Weird";
}
else
{
return "Weird";
}
}
Now the two calls is basically:
System.out.println("This number is " + "Weird");
System.out.println("This number is " + "Not Weird");

How to use arrays in a leap year finder

I am trying to create a program that can take input of multiple leap years ina row through an array and then output whether they are leap years or not on their own separate lines. I can't seem to figure out the problem. Here is my code.
import java.util.Scanner;
public class LeapYear2 {
static boolean[] leapYearStatus = new boolean[10];
public static void main(String[] args) {
System.out.println("Enter consecutive years above 1582 with");
System.out.println("spaces separating them then press enter.");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine()+ " ";
String[] inputString = new String[input.length()/5];
int[] inputValues = new int[input.length()/5];
inputString = input.split("\\s+");
for (int i =0; i < input.length()/5;i++)
inputValues[i] = Integer.parseInt(inputString[i]);
LeapYear2 check = new LeapYear2();
check.checkLeap(inputValues);
check.output(leapYearStatus, inputValues);
scan.close();
}
public void checkLeap(int value[]) {
for (int i = 0; i < value.length; i++) {
if (value[i] % 4 == 0)
if (value[i] % 400 == 0)
leapYearStatus[i] = true;
else if (value[i] % 100 == 0)
leapYearStatus[i] = false;
}
}
public void output(boolean[] leapYearStatus, int value[]) {
for(int i = 0; i < value.length; i++)
if(leapYearStatus[i] && value[i] > 1582){
System.out.println(value[i] + " is a leap year!");
}else if(!leapYearStatus[i] && value[i] > 1582 ){
System.out.println(value[i] + " is not a leap year.");
}else {
System.out.println(value[i] + " is too small! (<= 1582)");
}
}
}
Instead of nested if, you can reduce to one if. Its the same but more readable
if (value[i] % 400 == 0 || (value[i] % 4 == 0 && value[i] % 100 != 0) ) {
leapYearStatus[i] = true;
} else {
leapYearStatus[i] = false;
}

Java - Looping Number Strings

You all were so helpful yesterday in getting over my first hump in this problem that I wanted to see if there's a way I can modify my final product (Apologies if my formatting is off - Still trying to get indentations correct in my IDE.
import javax.swing.JOptionPane;
public class NumberLoops {
public static void main(String[] args) {
String strNum1;
String strNum2;
int intNum;
boolean isValid = true;
boolean isError = false;
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
JOptionPane.showMessageDialog(null, "Negative Digit Found - Enter Positive Numbers Only", "Error", JOptionPane.INFORMATION_MESSAGE);
isValid = false;
break;
}
}
if (isValid){
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
intNum = Character.getNumericValue(c);{
if (intNum > 0 && intNum <= 9){
isError = true;
break;
}
}
}
}
if (isError){
int aDigit,totalNum=0;
char chDigit;
strNum2 = String.valueOf(strNum1);
for (int count=0; count<strNum1.length();count++){
chDigit = strNum2.charAt(count);
aDigit = Character.getNumericValue(chDigit);
totalNum += aDigit;
if (aDigit > 0 && aDigit <= 9){
System.out.print(aDigit + " ");
}
}
System.out.print(" " + "The sum is: " + totalNum);
}
}
}
My question concerns the last loop. It functions as desired by printing to the console if I enter say 123123 into the message prompt, it lists that string as 1 2 3 1 2 3 and then the total of 12.
But that is in the console itself. What I'm trying to wrap my mind around is getting it to display in a message box instead of the console.
I'm guessing I need to create a new string like (incoming pseudocode):
if (aDigit > 0 && aDigit <= 9){
strNum3 = everycharinStr2 + " "
Which is the part I guess I'm not grasping.
FYI, this is a homework assignment so I don't necessarily want an outright answer, but I feel I am so close that I need some extra eyes on it to see if there's anything I can do. (I have read up on arrays and such but we aren't at that point yet so I don't think I'll go down that road quite yet.)
You only have to make a little change in your code:
strNum2 = String.valueOf(strNum1);
String resultString = "";
for (int count=0; count<strNum1.length();count++){
chDigit = strNum2.charAt(count);
aDigit = Character.getNumericValue(chDigit);
totalNum += aDigit;
if (aDigit > 0 && aDigit <= 9){
System.out.print(aDigit + " ");
resultString += aDigit + " ";
}
}
JOptionPane.showMessageDialog(null, resultString);
Create a new String and in each iteration append the number to this String, then show it in a dialog.
The errors are commented out.
//if (intNum > 0 && intNum <= 9){
if (intNum < 0 || intNum > 9){
isError = true;
break;
}
//if (aDigit > 0 && aDigit <= 9){
if (aDigit >= 0 && aDigit <= 9){
System.out.print(aDigit + " ");
//resultString+ = aDigit + " ";
resultString += "" + aDigit;
}
//if (isError) {
if (!isError) {
Just use a JLabel!
Since your already using swing, this would be your best choice. But then you'd need a frame and panel, so if you don't already have that, don't do this.
JLabel label = new JLabel()
label.setText("Random Text!")
You can also do this, with a pop up:
JOptionPane.showMessageDialog(null, "My String!");

Syntax error, insert "}" to complete ClassBody? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
For some reason I get a syntax error that says, "Syntax error, insert "}" to complete ClassBody." I checked every method, every statement to make sure I have complete opening and closing brackets, so I don't know why this is happening. Can anybody tell me why I might be getting this issue?
Copying the code into another file doesn't fix the problem, nor does going to Project > Clean.
import java.util.Scanner;
public class jloneman_Numerology
{
private String[] report;
private int day, month, year, num;
public jloneman_Numerology()
{
introduction();
report = new String[9];
num = 0;
}
public void introduction()
{
System.out.println("Welcome to ACME Numerology Reports! We will " +
"determine your special\nnumerology report based on your " +
"birth date.\n");
}
public void getDate()
{
char slash1, slash2;
do
{
System.out.print("Please enter your birth date (mm / dd / yyyy): ");
Scanner in = new Scanner(System.in);
String date = in.nextLine();
month = in.nextInt();
day = in.nextInt();
year = in.nextInt();
slash1 = date.charAt(3);
slash2 = date.charAt(8);
} while (validDate(slash1, slash2) == false);
calcNum();
}
public boolean validDate(char slash1, char slash2)
{
boolean isValid = true;
// Check for valid month
if (month < 1 || month > 12)
{
isValid = false;
System.out.printf("Invalid month: %d\n", month);
}
// Check for valid day
if (day < 1 || day > 31)
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
// Check for months with 30 days, else 31 days = invalid
if ((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30))
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
else if (day < 1 || day > 31)
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
// Check for valid year
if (year < 1880 || year > 2280)
{
isValid = false;
System.out.println("Please enter a valid year between 1880 and 2280.");
}
// Check for correct separating character
if (slash1 != '/' || slash2 != '/')
{
isValid = false;
System.out.println("Invalid separating character, please use forward slashes");
}
if (leapYear() == true)
{
if (month == 2 && day > 29)
{
isValid = false;
System.out.printf("Invalid day for 2/%d: %d", year, day);
}
}
return isValid;
}
public boolean leapYear()
{
boolean isLeap;
if (year % 4 == 0 && year % 400 != 0)
isLeap = false;
else
isLeap = true;
return isLeap;
}
public void calcNum()
{
// Separate each digit of the date and add to a single number
// Test number for debugging
num = 5;
}
public void printReport()
{
report[0] = ":1: ";
report[1] = ":2: ";
report[2] = ":3: ";
report[3] = ":4: ";
report[4] = ":5: ";
report[5] = ":6: ";
report[6] = ":7: ";
report[7] = ":8: ";
report[8] = ":9: ";
System.out.println(report[num]);
}
}
78,0-1 Bot
Try removing (or commenting out) one method and see if the problem persists. If it does, remove or comment out an additional method, and so on, until the error disappears. Then restore everything but the last method.
If the error doesn't reappear, the problem is probably in that last method.
If it does reappear, the problem is more subtle; perhaps a control character embedded in the code. Try copying and pasting the code into a text-only editor (so any control characters will be ignored, save it, and recompiling.
I too had this error.
There are NO errors in the code above (when I used the code above as as a sub class).
I corrected my error by cleaning up my IDE's workspace and making sure the caller was working properly.
Project settings
Run settings
Made sure that main was listed properly
public static void main(String[] args) { ... }
I have faced the similar problem, solved it by deleting the class file and then recreated the file again and pasted the same code. It worked.
Take out the System.out.println and put it into the main function instead of the introduction() inside of the main(String[] args).

Best Before Puzzle [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Spotify puzzle problem
Been working on this puzzle because I am new to Java and would like to learn it. SO, I have been solving this puzzle for Spotify. But everytime I submit it. It says wrong answer. Im pretty sure its right though can anyone see what I am missing. This is the problem. http://www.spotify.com/us/jobs/tech/best-before/
Here is my solution
import java.io.*;
import java.util.Arrays;
public class best_before {
static boolean next;
static String month, day, year;
public static void main(String[] args) throws IOException{
//Setup to grab the input
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input = "";
input = br.readLine();
//Spilt the input to grab each integer entered by user
String bits = input;
String[] tokens = bits.split("/");
int a_value1 = Integer.parseInt(tokens[0]);
int b_value1 = Integer.parseInt(tokens[1]);
int c_value1 = Integer.parseInt(tokens[2]);
//Sort the array in order from lowest to highest
int[] int_array = new int[] {a_value1, b_value1, c_value1};
Arrays.sort(int_array);
int a_value = int_array[0];
int b_value = int_array[1];
int c_value = int_array[2];
year = Integer.toString(a_value);
month = Integer.toString(b_value);
day = Integer.toString(c_value);
//Check the integers entered to put them in the right order
int check_days = Integer.parseInt(day);
int check_month = Integer.parseInt(month);
int check_year = Integer.parseInt(year);
//Check to make sure none of the values are a negative integer
if(check_days < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
else if(check_month < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
else if(check_year < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
//Will only change the values around if the highest date in the array is bigger than 31
if(check_days > 31){
//Only reorganize if year if larger than month
if(check_month > check_year){
month = Integer.toString(check_year);
}
//Otherwise just keep month at its current value
else{
month = Integer.toString(check_month);
}
//Change date and year around since one is bigger than the other
year = Integer.toString(check_days);
day = Integer.toString(check_month);
}
else if(check_year == 0){
if(check_month < check_days){
month = Integer.toString(check_month);
}
else{
month = Integer.toString(check_days);
}
}
//Get the length so I can zero pad the numbers
int length_year = year.length();
int length_month = month.length();
int length_day = day.length();
//Doing my zero pad thing right here
if(length_year == 1){
year = "200" + year;
}
else if(length_year == 2){
year = "20" + year;
}
else if(length_year == 3){
year = "2" + year;
}
if(length_month == 1){
month = "0" + month;
}
if(length_day == 1){
day = "0" + day;
}
//A last check to make sure everything is Kosher
int last_check = Integer.parseInt(year);
int last_check_month = Integer.parseInt(month);
int last_check_day = Integer.parseInt(day);
//Checking to see if it is a leap year. Is the year Divisible by 4?
if (last_check % 4 == 0) {
// Is the year Divisible by 4 but not 100?
if (last_check % 100 != 0) {
next = true;
}
// Is the year Divisible by 4 and 100 and 400?
else if (last_check % 400 == 0) {
next = true;
}
// It is Divisible by 4 and 100 but not 400!
else {
next = false;
}
}
// It is not divisible by 4.
else {
next = false;
}
//Check to make sure the date is legal and valid :)
if(last_check > 2999 || last_check < 2000)
{
//Date must be between 2000 and 2999 inclusive
System.out.println(input + " is illegal");
}
else if(last_check_month > 12)
{
//Date month must be less than 12
System.out.println(input + " is illegal");
}
else if(last_check_day > 31)
{
//Date day must be less than 31
System.out.println(input + " is illegal");
}
else if(next == false && last_check_day > 28 && last_check_month == 2){
//if next is false and the day is greater than 28 and its not a leap year something is wrong
System.out.println(input + " is illegal");
}
else if(next == true && last_check_day > 29){
//if next is true and the day is greater than 29 and it is a leap year something is wrongs
System.out.println(input + " is illegal");
}
else if(last_check_month == 4 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 6 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 9 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 11 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check == 2000){
//Check to make sure there are no other days that are zero too because you cant have two zeros
if(last_check_day == 0 || last_check_month == 0){
System.out.println(input + " is illegal");
}
else{
System.out.print(year + "-" + month + "-" + day);
}
}
else{
System.out.print(year + "-" + month + "-" + day);
}
}
}
Your program fails for the input 31/9/73, where it returns 2073-09-31 instead of 31/9/73 is illegal. Since September only has 30 days, your program should check for September (and a couple of other months), and output the error.
In the updated version, your program still fails the input 1/2/31; it should give 2031-1-2.
By the way, the main intent behind these puzzles is not to solve them, but to solve them elegantly. Try reducing the number of variables, and avoiding duplicate lines etc.

Categories