everything works perfect and I know more or less java sout formatting, but I ve been following this book and its been explaining how the logic works. One thing I can not seem to figure out is why my output is coming out vertical and in the book its perfectly horizontal? I have it formatted exactly the same way
this is my java code
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package b.elsestatements;
import java.util.*;
/**
*
* #author willc86
*/
public class Clock {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minuite = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);
if (hour > 17){
System.out.println("Good evening");
} else if (hour < 12) {
System.out.println("Goodmorning");
} else {
System.out.println("Good afternoon");
}
System.out.println("It is ");
if (minuite != 0) {
System.out.println("" + minuite + " ");
// if (minuite != 1) {
// System.out.println("minuites");
// } else {
// System.out.println("minuite");
// }
System.out.println((minuite != 1) ? "minuites" : "minuite ");
System.out.println("Past");
System.out.println((hour > 12) ? (hour - 12) : hour);
System.out.println("O clock on ");
//month case
switch (month) {
case 1:
System.out.println("Jan");
break;
case 2:
System.out.println("Feb");
break;
case 3:
System.out.println("Mar");
break;
case 4:
System.out.println("Apr");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("Jun");
break;
case 7:
System.out.println("Jul");
break;
case 8:
System.out.println("Aug");
break;
case 9:
System.out.println("Sept");
break;
case 10:
System.out.println("Oct");
break;
case 11:
System.out.println("Nov");
break;
case 12:
System.out.println("Dec");
}
System.out.println("On " + year + " day " + day);
}
}
}
Maybe on your book it doesn't say: System.out.println maybe it says: System.out.print
System.out.print("" + minuite + " ");
System.out.print((minuite != 1) ? "minuites" : "minuite ");
System.out.print("Past");
System.out.print((hour > 12) ? (hour - 12) : hour);
System.out.print("O clock on ");
Maybe that should solve your problem.
I mean change System.out.println to System.out.print
And your output should look like this:
Good afternoon
It is 52 minuitesPast2O clock on Apr
On 2014 day 28
System.out.println will create a new line (ln on the end stands for line) so if you take it out, it should print horizontal without creating new lines.
Another way to create new lines on a System.out.print is by using escape characters such as "\n" that will do the same as System.out.println
This case:
System.out.println("Hello"); //Will create a new line
System.out.println("World"); //Will create a new line
System.out.print("Hello"); //Won't create a new line
System.out.print("World"); //Won't create a new line
System.out.print("Hello \n"); //Will create a new line
System.out.print("World"); //Won't create a new line
The output for the 3 cases above will be:
Hello
World
Hello World
Hello
World
Related
I have been working on a code that registers students for courses. I was given a teachers copy and needed to write the code for the validateChoice method. I have it completed but I am still getting two errors. The program is recognizing 0 as a duplicate instead of an invalid course number, and is allowing the user to duplicate twice before throwing an invalid message. There should be no duplicates allowed. Any ideas on why this would happen? I have already turned this in because it runs correctly with the course codes I was given for the assignment, I just want to know for personal reference. Thanks!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package u6a1_consoleregisterforcourse;
import java.util.Scanner;
/**
*
* #author omora
*/
public class U6A1_ConsoleRegisterForCourse {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Kim's Copy");
Scanner input = new Scanner(System.in);
//choice is the current menu selection
//firstChoice is the first menu selection mande by the user
//secondChoice is the second menu selection mande by the user
//thirdChoice is the third menu selection mande by the user
// a choice of 0 means the choice has not been made yet
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
String yesOrNo = "";
do {
choice = getChoice(input);
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registerd for this " + ChoiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + ChoiceToCourse(choice) );
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
System.out.println("[1]IT4782\n[2]IT4784\n[3]IT4786\n[4]IT4789\n[5]IT2230\n[6]IT3345\n[7]IT3349");
System.out.print("Enter your choice : ");
return (input.nextInt());
}
//This method validates the user menu selection
//against the given registration business rules
//it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
int result = 0;
if (choice <=0 ||choice >7){
result = -1;
}
if(choice==firstChoice||choice == secondChoice||choice == thirdChoice) {
result = -2;
}
if(totalCredit == 3) {
result = 0;
}
if (totalCredit > 9) {
result = -3;
}
return result;
}
public static void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice) {
if (firstChoice == 0)
System.out.println("Current course registration: { none } " );
else if (secondChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + " }" );
else if (thirdChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + " }");
else
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + ", " + ChoiceToCourse(thirdChoice) + " }");
}
public static String ChoiceToCourse(int choice) {
String course = "";
switch (choice)
{
case 1:
course = "IT4782";
break;
case 2:
course = "IT4784";
break;
case 3:
course = "IT4786";
break;
case 4:
course = "IT4789";
break;
case 5:
course = "IT2230";
break;
case 6:
course = "IT3345";
break;
case 7:
course = "IT3349";
break;
default:
break;
}
return course;
}
}
I have looked around and haven't found any questions that has been directly answered for my problem, if i'm wrong, sorry. I'm writing a program that is supposed to take in your birth information, year, month, day, hour, minute and then ask if they would like to do it again but using a method and loop until a Y/N is entered.
My problem is im not able to get the method to take in the Y/N and end the program, as well as end when a N is entered.
I think there is supposed a while or some sort of loop that needs to be in the method but im having a hard time figuring that out.
All my other methods work except for this one, any help would be appreciated, thanks.
This is the code I have for my method now:
public static boolean getYNConfirm(Scanner pipe, String prompt)
{
String choice="";
System.out.println(prompt);
choice = pipe.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
return true;
}
else
{
return false;
}
}
And this is the code for my main program:
public static void main(String[] args)
{
int year, month, day, hour, minutes;
String msg="";
boolean done = false;
Scanner in = new Scanner(System.in);
while(!done)
{
year = SafeInput.getIntInRange(in, "Enter the year you were born: ", 1965, 2000);
month = SafeInput.getIntInRange(in, "Enter your month of birth: ", 1, 12);
switch (month)
{
case 1:
msg = "January";
break;
case 2:
msg = "February";
break;
case 3:
msg = "March";
break;
case 4:
msg = "April";
break;
case 5:
msg = "May";
break;
case 6:
msg = "June";
break;
case 7:
msg = "July";
break;
case 8:
msg = "August";
break;
case 9:
msg = "Septemeber";
break;
case 10:
msg = "October";
break;
case 11:
msg = "November";
break;
case 12:
msg = "December";
break;
}
hour = SafeInput.getIntInRange(in, "Enter the hour you were born in: ", 1, 24);
minutes = SafeInput.getIntInRange(in, "Enter the minutes you were born: ", 1, 59);
System.out.println("You were born: " + year + " , " + msg + " , " + hour + " hr. " + minutes + " mins. ");
SafeInput.getYNConfirm(in, "Would you like to play again?");
}
}
}
Thanks for any help.
Value of done is always false. Change on last line:
done = SafeInput.getYNConfirm(in, "Would you like to play again?");
EDIT:
Your logic does not fit if you return true Change here too:
if(choice.equalsIgnoreCase("Y"))
{
return false;
}
else
{
return true;
}
you need to change the value of done base on the return of the getYNConfirm method. So the last line should be
done = SafeInput.getYNConfirm(in, "Would you like to play again?");
I have a question that I can't figure it out , Thank you:
Write a program that prompts the user to enter an integer for today's day of the week (Sunday is 0 ,Monday is 1 ,... and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week .Here is the sample run:
Enter today's day: 1
Enter number of the day elapsed since today:3
Today is monday and the future day is thursday
My try is:
Scanner input = new Scanner(System.in);
System.out.print("Enter today's day (0 - 6): ");
int day = input.nextInt();
System.out.print("Enter the number of days elapsed since today: ");
int elapsed = input.nextInt();
if(day == 0)
{
System.out.println("Sunday");
}
if(day == 1)
{
System.out.println("Monday");
}
if(day == 2)
{
System.out.println("Tuesday");
}
if(day == 3)
{
System.out.println("Wednesday");
}
if(day == 4)
{
System.out.print("Thursday");
}
if(day == 5)
{
System.out.print("Friday");
}
if(day == 6)
{
System.out.print("Saturday");
}
System.out.print("Today is " + day + " and the future day is " + elapsed);
As you need day-number to day-string twice, put it in a separate function. I want to show you a couple of possible approaches. Version 1, basic, simple and tidy:
// isolate the daynumber --> daystring in a function, that's tidier
String dayFor (int daynumber) {
String dayAsString = "ERROR"; // the default return value
switch(dayNumber) {
case 0 :
dayAsString = "Sunday";
break;
case 1 :
dayAsString = "Monday";
break;
// and so on, until
case 6 :
dayAsString = "Saturday";
break;
}
return dayAsString;
}
A much shorter version that uses an array instead of the switch statement:
String dayFor (int daynumber) {
String dayStrings[] = new String[]{"Sunday","Monday", .... "Saturday"};
// notice that daynumber's modulo is used here, to avoid index out of
// bound errors caused by erroneous daynumbers:
return dayStrings[daynumber % 7];
}
It might be tempting to try something along the lines of the following function where each case returns immediately, but having multiple return statements is discouraged. Just showing it here because it is technically possible, and you'll encounter it sometimes
String dayFor (int daynumber) {
switch(dayNumber) {
case 0 :
return "Sunday";
case 1 :
return "Monday";
// and so on, until
case 6 :
return "Saturday";
}
// normally not reached but you need it because the compiler will
// complain otherwise anyways.
return "ERROR";
}
After this rather long intro the main function becomes short and simple. After the input you just need:
// present day + elapsed modulo 7 = the future day
int future = (day + elapsed) % 7;
System.out.print("Today is " + dayFor(day) + " and the future day is " + dayFor(future) );
Don't forget to add code to check your inputs!
You can do it better by using an array to store the the day names.
String[] dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
Now you can use the user input as the index
int nameIndex = //... get input
//validate input
//dayNames[nameIndex] is the day of the week
Now get the input for number of days to add
int numDays = //...get input
Then just add that many days to compute the index for future day of week
int futureNameIndex = nameIndex; //start with entered day of week index
for(int i=0; i<numDays; i++) {
futureNameIndex++; //increment by 1 for numDays times
if(futureNameIndex == dayNames.length) { //if the index reaches lenght of the array
futureNameIndex = 0; //reset it to 0
}
}
I think you will find that one easier to understand. Finally
//dayNames[futureNameIndex] is the future day of week.
The question gives you the days ranging from 0-6, instead of 1-7(conventional). Now, for example, if the day today is 1(Monday) and the daysElapsed since today is 3, then the day should be Thursday. Since this question has the initial day inclusive, the resulting day will be after 1(Monday),2,3(Wednesday) have passed, that is Thursday.
Let's take an example and apply it to the code below.
day = 1;
daysElased = 3;
else if(day > 0 && day < 7) , which is the case
{
sum = 1(day) + 3(daysElapsed); // sum = 4
}
If sum is in the range of 0-6, each if case can be created corresponding to each day. In the case above, the sum is less than 6, so it will be having its own if clause. Had the sum been greater, for example, days = 1 and daysElapsed = 6, then sum = 1(days) + 6(daysElapsed) = 7.
In this case it will match the clause if(sum > 6), then sum = sum % 7 = 7 % 7 = 0 = Sunday. This means that the days from 1(Monday) to 6(Saturday) have been elapsed, so the day will be Sunday(0).
if(day == 0) // If the present day entered is Zero(0 is for Sunday)
{
sum = daysElapsed; // daysElapsed will be entered by the user
}
else if(day > 0 && day < 7) // If the present day is > 0 but < 7 (1 - 6 days)
{
sum = day + daysElapsed; //
}
if(sum>6) // if 0<= sum <=6 , 6 if cases can be created. If sum > 6 :
{
sum = sum % 7;
}
if(sum == 0)
{
System.out.println("Day is Sunday.");
}
.
.
.
.
else if(sum == 6)
{
System.out.println("Day is Saturday.");
}
As I know, this question is from the book "Introduction To Java Programming". Where this question is asked, you don't have any knowledge of methods, loops, arrays etc. so I will just use Selections.
Here, when I tried to solve with a better way, I could not find any since we cannot use arrays which could be very helpful or methods which is even better. That's why this question is a little redundant in book.
And you really should not use if statements because switch is much better in this case.
System.out.println("Enter today's number (0 for Sunday, 1 for Monday...) :");
int todayNo = in.nextInt();
System.out.println("Enter the number of days elapsed since today:");
int elapsedDay = in.nextInt();
int futureDay = (todayNo + elapsedDay) % 7;
switch (todayNo) {
case 0:
System.out.print("Today is Sunday and");
break;
case 1:
System.out.print("Today is Monday and");
break;
case 2:
System.out.print("Today is Tuesday and");
break;
case 3:
System.out.print("Today is Wednesday and");
break;
case 4:
System.out.print("Today is Thursday and");
break;
case 5:
System.out.print("Today is Friday and");
break;
case 6:
System.out.print("Today is Saturday and");
break;
}
switch (futureDay) {
case 0:
System.out.print(" the future day is Sunday.");
break;
case 1:
System.out.print(" the future day is Monday.");
break;
case 2:
System.out.print(" the future day is Tuesday.");
break;
case 3:
System.out.print(" the future day is Wednesday.");
break;
case 4:
System.out.print(" the future day is Thursday.");
break;
case 5:
System.out.print(" the future day is Friday.");
break;
case 6:
System.out.print(" the future day is Saturday.");
break;
}
Here, the only thing that you maybe don't know is System.out.print();. The only difference with the System.out.println(); is with this method, this one doesn't print on a new line, it prints on the same line which is what we need here. Tinker with it to understand better.
package javaapplication2;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
int day, eday, fday;
String str, str1;
Scanner S = new Scanner(System.in);
System.out.println("Enter today's day: ");
day = S.nextInt();
System.out.println("Enter the number of days elapsed since today: ");
eday = S.nextInt();
if (day == 0) {
str = "Sunday";
System.out.print("Today is " +str + " and ");
}
else if (day == 1) {
str = "Monday";
System.out.print("Today is " +str + " and ");
}
else if (day == 2) {
str = "Tuesday";
System.out.print("Today is " +str + " and ");
}
else if (day == 3) {
str = "Wednesday";
System.out.print("Today is " +str + " and ");
}
else if (day == 4) {
str = "Thursday";
System.out.print("Today is " +str + " and ");
}
else if (day == 5) {
str = "Friday";
System.out.print("Today is " +str + " and ");
}
else if (day == 6) {
str = "Saturday";
System.out.print("Today is " +str + " and ");
}
fday = day + eday;
if (fday % 7 == 0) {
str1 = "Sunday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 1) {
str1 = "Monday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 2) {
str1 = "Tuesday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 3) {
str1 = "Wednesday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 4) {
str1 = "Thursday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 5) {
str1 = "Friday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 6) {
str1 = "Saturday";
System.out.print("Future day is " +str1);
}
}
The question is from a book titled "Introduction to Java programming" by Y. Daniel Liang. Apart from using the string type, which I believe is covered in the next chapter; the solution I wrote for this exercise uses only what you have been taught so far.
import java.util.Scanner;
public class Exercise_03_06 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter today's day: ");
int todaysDay = input.nextInt();
System.out.print("Enter the number of days elapsed since today: ");
int elapsedDays = input.nextInt();
int futureDay = (todaysDay + elapsedDays) % 7;
String day_of_week = "";
switch (todaysDay) {
case 0: day_of_week = "Sunday"; break;
case 1: day_of_week = "Monday"; break;
case 2: day_of_week = "Tuesday"; break;
case 3: day_of_week = "Wednesday"; break;
case 4: day_of_week = "Thursday"; break;
case 5: day_of_week = "Friday"; break;
case 6: day_of_week = "Saturday";
}
switch (futureDay) {
case 0:
System.out.println("Today is " + day_of_week + " and the future day is Sunday."); break;
case 1:
System.out.println("Today is " + day_of_week + " and the future day is Monday."); break;
case 2:
System.out.println("Today is " + day_of_week + " and the future day is Tuesday."); break;
case 3:
System.out.println("Today is " + day_of_week + " and the future day is Wednesday."); break;
case 4:
System.out.println("Today is " + day_of_week + " and the future day is Thursday."); break;
case 5:
System.out.println("Today is " + day_of_week + " and the future day is Friday."); break;
case 6:
System.out.println("Today is " + day_of_week + " and the future day is Saturday.");
}
}
}
Output:
Enter today's day: 0
Enter the number of days elapsed since today: 31
Today is Sunday and the future day is Wednesday.
Notes:
The first switch statement assigns a day of type string to the variable day_of_week which is later used for printing "today's day".
To obtain the future day, you must find the remainder of the sum of today's day and the number of days elapsed divided by 7.
The last switch statement "matches" a case number that is identical to the number stored within the futureDay variable (which is obtained by performing the mathematical operation noted above).
I have two classes for calculating the cost of an ISP plan and gathering input/displaying the cost. ISPMain.java and ISP.java ISPMain is supposed to display service plans and ask the user to select their plan by the letter of the package, like package a, package b, or package c. I have it set up so the user inputs the character to choose the plan. If the plan is the not package c (unlimited plan) the user is prompted to enter the hours they used.
Once the hours are entered and stored in hoursUsed, ISP.java calculates the cost and then ISPMain.java displays it. My problem is that my switch statement in ISP only is displaying the default value and I am not sure why. Can anyone explain?
public class ISPMain
{
public static void main(String[] args)
{
char pkg;
double hoursUsed;
Scanner kb = new Scanner(System.in);
System.out.println("The three packages offered are: ");
System.out.println("Package A: For $9.95 per month, 10 hours of access are provided. \nAdditional hours are $2.00 per hour.");
System.out.println("Package B: For $14.95 per month, 20 hours of access are provided. \nAdditional hours are $1.00 per hour.");
System.out.println("Package C: For $19.95 per month, unlimited access is provided.");
System.out.println("Please type the letter of the package you have: ");
pkg = kb.nextLine().toUpperCase().charAt(0);
if(pkg == 'A')
{
System.out.print("Enter number of hours: ");
hoursUsed = kb.nextDouble();
}
else if(pkg == 'B')
{
System.out.print("Enter number of hours: ");
hoursUsed = kb.nextDouble();
}
else if(pkg == 'C')
{
System.out.print("You have unlimited access! No need to enter hours used. \n");
}
ISP user = new ISP();
System.out.print("Total charges: " + user.calculateCharges());
}
}
switch statement from ISP.java:
public double calculateCharges()
{
switch (pkg)
{
case 'A':
if (hoursUsed < 10)
{
return 9.95;
}
else
{
return (hoursUsed - 10)*2 + 9.95;
}
case 'B':
if (hoursUsed < 20)
{
return 14.95;
}
else
{
return (hoursUsed - 20) + 14.95;
}
case 'C':
return 19.95;
default:
System.out.println("Invalid input!");
return 0;
}
}
to conclude, my if else works fine, but the switch only displays "Invalid input"
As others have said, you need to get the pkg variable into the scope of your switch statement. Try this:
public double calculateCharges(char pkg){
switch(pkg){
case('A'):{
//insert code here
break;
}
case('B'):{
//insert code here
break;
}
case('C'):{
//insert more code here
break;
}
default:{
//code here
break;
}
}
}
Then call your method like:
System.out.print("Total charges: " + user.calculateCharges(pkg));
The default: case statement will always run in your code because char pkg isn't defined as a parameter for your method.
The user may enter A, B, or C, but since it does not get passed the end result will always be default, therefore causing your Invalid input.
Try :
public double calculateCharges(char pkg){
switch (pkg)
{
case 'A':
if (hoursUsed < 10){
return 9.95;
}else{
return (hoursUsed - 10)*2 + 9.95;
}
case 'B':
if (hoursUsed < 20){
return 14.95;
}else{
return (hoursUsed - 20) + 14.95;
}
case 'C':
return 19.95;
default:
System.out.println("Invalid input!");
return 0;
}
was wondering if anyone could help me change an " If else statement " to a "switch"
Well c the pseudo code is.
Please help .
IF month is 1,2, or 3, season = "Winter
Else if month is 4, 5, or 6, season = "Spring"
Else if month is 7,8, 9, season = "Summer"
Else if month is 10,11, or 12, season = "Fall"
If season is "Winter", season = "Spring"
Else if season is "Spring", season = "Summer"
Else if season is "Summer", season = "Fall"
Else season = "Winter"
2.My code is
import java.util.Scanner;
public class mylab
{
public static void main(String[] args)
{ Scanner in = new Scanner(System.in);
int month;
int day;
String season= "seasons";
System.out.print("type a two digit month");
System.out.print(" and day");
month = in.nextInt();
day = in.nextInt();
String fall = " fall";
String winter = " winter ";
String summer = " summer";
String spring = " spring";
System.out.print(" Month="+ month +" Day= "+day);
if( month <= 3)
{ System.out.println(" Winter");
season= winter; }
else if ( month <=6)
{ System.out.println(" Spring ");
season=spring; }
else if ( month<= 9)
{ System.out.println(" Summer ");
season= spring; }
else if ( month<=12)
{ System.out.println(" Fall");
season= fall; }
3.I just need to change the 1st part to a switch statement.
This is what I have so far
switch( month )
{ case 1: season= " winter";if ( month <= 3) ;break;
case 2: season= " spring"; if ( month <= 6) ;break;
case 3: season = " summer"; if (month <= 9); break;
case 4: season= " fall"; if (month <= 12); break ;
}
,but it is not working .
IF month is 1,2, or 3, season = "Winter
Would simply become...
String season = "";
switch (month) {
case 1:
case 2:
case 3:
season = "Winter";
break;
case ...: // etc...
}
case will fall through to the next case unless there is a break
Take a look at The switch Statement for more details
How about some integer division?
switch( (month + 2) / 12 ) {
case 1:
// winter
break;
case 2:
// spring
break; // WOOHOO SPRING BREAK!
case 3:
// summer
break;
case 4:
// fall
break; // winter is coming...
default:
break;
}
Hints:
You need two switch statements. One for the first if/else chain, and one for the second. (Though you could easily fold the two chains into one!)
The syntax of a switch statement is illustrated in the Java Tutorial here.
The following statement does nothing:
if ( month <= 3) ;
It says "test if month is less or equal to 3, and then execute the empty statement. This is a "gotcha!" in Java syntax ... and one of the reasons that some people think that you should always use curly brackets with if and loop statements in Java and similar languages.