Finding the count of an variable using switch Statment - java

In this application I have to enter the total sales of every month from Jan 2010 to Dec 2014.(48 inputs)
I need to display the month of the year which has min sales and max sales.
The problem is I am not getting the desired output.
package xxxxxxx;
import java.util.Scanner;
public class test{
public static void main ( String [] args ){
Scanner keyboard = new Scanner( System.in );
int getInt=0;
int count = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double average = 0;
boolean number = true;
int choice=0;
while ( number == true )
{
System.out.println("Enter A Sales for a month : ");
getInt = keyboard.nextInt();
choice++;
if ( getInt < 0 )
number = false;
else
{
if ( getInt > max )
max = getInt;
if ( getInt <= min )
min = getInt;
sum += getInt;
count++;
}
}
int maxy=choice%12;
switch(maxy){
case 1 :
System.out.println("It's Month is : "+" Januray of 2010 !"+max);
break;
case 2 :
System.out.println("It's Month is : "+" Februray of 2010 !"+max);
break;
case 3 :
System.out.println("It's month is : "+" March of 2010 !"+max);
break;
case 4 :
System.out.println("It's month is : "+" April of 2010 !"+max);
break;
case 5 :
System.out.println("It's month is : "+" May of 2010 ! "+max);
.
.
.
}
average = ( sum ) / ( count );
System.out.println( "Sum = " + sum );
System.out.println( "Average = " + average );
System.out.println( "Max = " + max );
System.out.println( "Minimum = " + min );
}
}

I believe what you're wanting is the following if you have to use a switch and don't want to use something like a Date formatting class:
int year = 2010 + choice / 12;
int month = 1 + choice % 12;
switch (month) {
case 1: System.out.println("January " + year);
break;
case 2: System.out.println("February " + year);
break;
// so on
}
BTW I don't see anything in your code that restricts the # of inputs to 48 like you say is a spec. You can easily add this to your while loop:
while (number == true && count < 48) {
}
And further reduce it to:
while (number && count < 48) {
}
Because booleans are a boolean themselves you do not need to check if (value == true) and if (value == false), rather you should check if (value) and if (!value).
However your number variable is actually redundant and can be removed entirely if you use a break. I also think you mean to exit before incrementing choice IE looks like the user enters a negative number to end early. If you increment the control this will screw up your average. It looks like you created your second variable count for this purpose but I don't think you need it. You just need to refactor.
I also recommend checking count before doing your average. In your code right now the user can abort the loop immediately and you'll get a divide by zero.
do {
System.out.println("Enter a sales for the month: ");
getInt = keyboard.nextInt();
if (getInt < 0) break;
if (getInt > max) max = getInt;
if (getInt < min) min = getInt;
sum += getInt;
count++;
} while (count < 48);
if (count == 0) {
System.out.println("No sales ever!");
return;
}
int year = 2010 + count / 12;
int month = 1 + count % 12;

To get the current month just use this
int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
and the year is
int year = Calendar.getInstance().get(Calendar.YEAR);
putting it all together
private static String getMonthName(int month) {
switch (month - 1) {
case Calendar.JANUARY: return "January";
case Calendar.FEBRUARY: return "February";
case Calendar.MARCH: return "March";
case Calendar.APRIL: return "April";
case Calendar.MAY: return "May";
case Calendar.JUNE: return "June";
case Calendar.JULY: return "July";
case Calendar.AUGUST: return "August";
case Calendar.SEPTEMBER: return "September";
case Calendar.OCTOBER: return "October";
case Calendar.NOVEMBER: return "November";
case Calendar.DECEMBER: return "December";
default:
System.err.println("month " + month
+ " unknown, use January.");
return "January";
}
}
public static void main(String[] args)
throws IOException {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -48);
for (int i = 0; i <= 48; i++) {
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
System.out.println(getMonthName(month) + " " + year);
cal.add(Calendar.MONTH, 1);
}
}

Related

What to revise to make it implement modularization using methods

I already have these 3 codes made but our prof said to revise it again using methods now. Can you help or can you show me what to revise in each code?
1.)
public class HeadsOrTails {
public static void main(String[] args) {
int Heads = 0;
int Tails = 0;
for(long simulation = 1; simulation <= 2000000; simulation += 1)
{
int FlipResult = FlipCoin();
if(FlipResult == 1)
{
Heads += 1;
}
else if(FlipResult == 0)
{
Tails += 1;
}
}
System.out.println("Numer of heads appeared: " + Heads);
System.out.println("Numer of tails appeared: " + Tails);
}
private static int FlipCoin()
{
return (int) (Math.random() + 0.5);
}
}
2.)
import java.util.Scanner;
public class DecToHex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int number = input.nextInt();
int rem;
String result = "";
char
hex[]= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(number > 0)
{
rem = number % 16;
result = hex[rem]+result;
number = number/16;
}
System.out.println("Hexadecimal Number: "+result);
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
/* *****************************************************************************
METHOD NAME : main
DESCRIPTION : Executes the main program to test the class
DayOfTheWeek
********************************************************************************/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
Your professor wants you to avoid typing duplicate code. They want you to minimize the amount of code you have to repeatedly type. For example, look at the main method from your DayOfTheWeek class.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
//After this is more code below that we don't care about for now
}
You had to do 3 System.out.print() calls. You also did 3 input.nextInt() calls. That's 6 calls total.
Notice how there is a System.out.print() call, and then a input.nextInt() call immediately after? We can slim that down to something like this.
public static int fetchInput(Scanner input, String message) {
System.out.print(message);
return input.nextInt();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = fetchInput(input, "Enter Year: (e.g., 2012): ");
int month = fetchInput(input, "Enter Month: 1-12: ");
int day = fetchInput(input, "Enter the Day of the month: 1-31:");
//After this is more code below that we don't care about for now
}
Now, we only have to type fetchInput() 3 times, which has a call to both System.out.print() and input.nextInt(), giving us a total of 5 calls.
So, 5 is less than 6, which means we have made progress towards our goal, but since it is only one less call, it may not seem significant. But in reality, there's a lot more repeats in your code - I just handed you one of them. On top of that, your professor is teaching you good habits that will help you if you ever become a programmer. What if instead of fetching 3 things, you needed to fetch 20? This is common in the real world, by the way. Using your old style, you would have had to type 20 System.out.print() and 20 input.nextInt() calls at least, putting you at around 40 calls. But doing it this new way, you would only need to type 20 fetchInput() calls, which has a System.out.print() call and an input.nextInt() call within it, putting our total at 22 calls for the new method. 40 vs 22 things to type is an easier to see example of how writing code that minimizes retyping the same thing saves you time.

Unable to figure out why my output is incorrect for this program

I'm creating a program that turns a user inputted number into English (eg 56 = fifty six). However, my output is completely incorrect. I've tried playing around with it and I'm not sure exactly what's wrong. This is the code I'm using! The number 7 outputs "zero thousand zero", the number 86 outputs "zero thousand eight", and the number 7556 outputs an error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 53 out of bounds for length 8
at SayingNumbers.twoDigitToStr(SayingNumbers.java:51)
at SayingNumbers.threeDigitToStr(SayingNumbers.java:70)
at SayingNumbers.numToStr(SayingNumbers.java:120)
at SayingNumbers.main(SayingNumbers.java:135)
This is the code I've been using! Any help troubleshooting would be much appreciated!
//This program takes a user inputted number and writes out the corresponding words in English
import java.util.Scanner;
public class SayingNumbers {
//This returns the English word for numbers 0 - 9
public static String oneDigitToStr(int num) {
switch (num) {
case 0 : return "zero";
case 1 : return "one";
case 2 : return "two";
case 3 : return "three";
case 4 : return "four";
case 5 : return "five";
case 6 : return "six";
case 7 : return "seven";
case 8 : return "eight";
case 9 : return "nine";
}
return"";
}
//This returns the English words for numbers 10 - 99
public static String twoDigitToStr(int num) {
//This returns the English word for numbers 10 - 19
switch(num){
case 10 : return "ten";
case 11 : return "eleven";
case 12 : return "tweleve";
case 13 : return "thirteen";
case 14 : return "fourteen";
case 15 : return "fifteen";
case 16 : return "sixteen";
case 17 : return "seventeen";
case 18 : return "eighteen";
case 19 : return "nineteen";
}
//This returns the English word for multiples of 10 up until 90.
String tens[] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
int onesPlace;
int tensPlace;
int i;
i = num;
onesPlace = i%10; //Finds ones place
i /= 10;
tensPlace = i; //Finds tens place
if(tensPlace == 0) {
return oneDigitToStr(onesPlace); //Calls oneDigitToStr for single digit numbers
}
if(onesPlace == 0) {
return tens[tensPlace - 2]; //Multiples of 10
}
//Returns all other two digit numbers > 20
return tens[tensPlace - 2] + " " + oneDigitToStr(onesPlace);
}
//Returns the English words for numbers 100-999
public static String threeDigitToStr (int num) {
String hundreds = "hundred";
int hundredsPlace;
int tensPlace;
int onesPlace;
int i;
i = num;
onesPlace = i % 100;
hundredsPlace = i / 100;
i = num;
i = i - hundredsPlace;
tensPlace = i / 10;
if (hundredsPlace == 0) {
return twoDigitToStr(tensPlace);
}
i = num - hundredsPlace;
return oneDigitToStr(hundredsPlace) + " hundred " + twoDigitToStr(i);
}
//Returns the English words for numbers 1000+ (within int parameters)
public static String numToStr (int num) {
String userNum = Integer.toString(num);
int billions;
int millions;
int thousands;
int hundredsPlace;
int tensPlace;
int onesPlace;
int i = num;
int n = userNum.length();
if (n > 9) {
if (n < 12) {
n = 12 - n;
while (n > 0) {
userNum = "0" + userNum;
n--;
}
}
billions = Integer.parseInt(userNum.substring(0,3));
millions = Integer.parseInt(userNum.substring(3,6));
thousands = Integer.parseInt(userNum.substring(6,9));
hundredsPlace = Integer.parseInt(userNum.substring(9,12));
return threeDigitToStr(billions) + " billion " + threeDigitToStr(millions) + " million " + threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace);
}
else if (n > 6 && n <= 9) {
if (n < 9) {
n = 9 - n;
while (n > 0) {
userNum = "0" + userNum;
n--;
}
}
millions = Integer.parseInt(userNum.substring(0,3));
thousands = Integer.parseInt(userNum.substring(3,6));
hundredsPlace = Integer.parseInt(userNum.substring(6,9));
return threeDigitToStr(millions) + " million " + threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace);
}
else if (n > 3) {
if (n < 6) {
n = 6 - n;
while (n > 0) {
userNum = "0" + userNum;
n--;
}
}
thousands = Integer.parseInt(userNum.substring(0,3));
hundredsPlace = Integer.parseInt(userNum.substring(3,6));
return threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace);
}
else {
return threeDigitToStr(Integer.parseInt(userNum));
}
return "";
}
//This gets user input
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numEntered;
while(true) {
System.out.print("Enter an integer to pronounce (any negative value to exit): ");
numEntered = scnr.nextInt();
if (numEntered < 0) {
break;
}
System.out.println(numEntered);
String numToString = numToStr(numEntered);
System.out.println(numToString);
}
System.out.println("kthxbye!");
}
}
In your code, there are multiple problems but at one line your logic fails and that line is in method threeDigitToStr(the last line i.e. return statement has i in place of onesPlace. So, change below-suggested code:
instead of
return oneDigitToStr(hundredsPlace) + " hundred " + twoDigitToStr(i);
modify to
return oneDigitToStr(hundredsPlace) + " hundred " + twoDigitToStr(onesPlace);
Complete code can be viewed online.

How do I get Min and max values to only print when "year" is entered?

Creating program where user can enter a month and see average temp for that month. User can enter "year" and see all months and avg temps for each month, as well as the yearly average and highest and lowest monthly average. So far I am having difficulty with the max/low average. It is printing when the month is entered and it shouldn't. I have tried to move the code around to different points but it doesn't seem to matter as it still prints when year or a month is entered.
import java.util.Scanner;
import java.util.*;
public class MonthlyTemp {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//set up arrays//
final int NUM_MONTHS = 12;
int [] avgMonthTemp = new int [NUM_MONTHS];
String [] monthName = new String[NUM_MONTHS];
int i = 0;
String userMonthName ="";
monthName[0] = "January";
monthName[1] = "February";
monthName[2] = "March";
monthName[3] = "April";
monthName[4] = "May";
monthName[5] = "June";
monthName[6] = "July";
monthName[7] = "August";
monthName[8] = "September";
monthName[9] = "October";
monthName[10] = "November";
monthName[11] = "December";
avgMonthTemp[0] = 75;
avgMonthTemp[1] = 75;
avgMonthTemp[2] = 79;
avgMonthTemp[3] = 82;
avgMonthTemp[4] = 85;
avgMonthTemp[5] = 86;
avgMonthTemp[6] = 90;
avgMonthTemp[7] = 90;
avgMonthTemp[8] = 90;
avgMonthTemp[9] = 86;
avgMonthTemp[10] = 81;
avgMonthTemp[11] = 77;
System.out.println("Enter a month or the word year: ");
userMonthName = scnr.nextLine();
for(i=0; i < NUM_MONTHS; i++) {
if(userMonthName.equalsIgnoreCase("year")) {
System.out.println(monthName[i] + " " + avgMonthTemp[i]);
}
}
for(i=0; i < NUM_MONTHS; i++) {
if(userMonthName.equalsIgnoreCase(monthName[i])) {
System.out.println(monthName[i] + " " + avgMonthTemp[i]);
}
}
Arrays.sort(avgMonthTemp);
System.out.println("Minimum = " + avgMonthTemp[0]);
System.out.println("Maximum = " + avgMonthTemp[avgMonthTemp.length-1]);
}
}
Any guidance would be greatly appreciated!
Thank you.
The Min/Max has no if clause around it, so it always runs.
if( userMonthName.equalsIgnoreCase("year") )
{
// User entered "year" - print out all values
for( i=0; i < NUM_MONTHS; i++ )
{
System.out.println( monthName[i] + " " + avgMonthTemp[i] );
}
Arrays.sort( avgMonthTemp );
System.out.println( "Minimum = " + avgMonthTemp[0] );
System.out.println( "Maximum = " + avgMonthTemp[avgMonthTemp.length-1] );
}
else
{
// Did the user enter a month name? If so print just that
for( i=0; i < NUM_MONTHS; i++ )
{
if ( userMonthName.equalsIgnoreCase( monthName[i] ) )
{
System.out.println( monthName[i] + " " + avgMonthTemp[i] );
}
}
}
If I understand you correctly, you only want to print the max/min values if the user asks that you print the full year's averages. The issue at hand is that you haven't guarded the two println statements (for maximum/minimum) with an if statement, so they'll always print.
The proper way to do this, in my opinion, would be to first determine if the user has asked for the full year's data and save that to a boolean:
boolean requestedAll = userMonthName.equalsIgnoreCase("year");
Then, you can iterate and print:
for(int i = 0; i < NUM_MONTHS; i++) {
if(requestedAll || userMonthName.equalsIgnoreCase(monthName[i])) {
System.out.println(monthName[i] + " " + avgMonthTemp[i]);
}
}
And then, at the end, you can just print the maximum and minimum values if this was a yearly request:
if(requestedAll) {
Arrays.sort(avgMonthTemp);
System.out.println("Minimum = " + avgMonthTemp[0]);
System.out.println("Maximum = " + avgMonthTemp[avgMonthTemp.length-1]);
}

Java - error in prompts [duplicate]

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).

asking user for another prompt after wrong input in java

so i'm asking the user for a month and a year. month has to be one of the twelve months and year has to be a number and no letters. i'm trying to figure out the best way to make the program say "wrong input, try again" and prompt them for input again. here's the section of code i'm working with for the month section.
public class MonthLength {
public static void main(String[] args) {
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
if (userInput.trim().toLowerCase().equals("january")) {
month = 1;
} else if (userInput.trim().toLowerCase().equals("february")) {
month = 2;
} else if (userInput.trim().toLowerCase().equals("march")) {
month = 3;
} else if (userInput.trim().toLowerCase().equals("april")) {
month = 4;
} else if (userInput.trim().toLowerCase().equals("may")) {
month = 5;
} else if (userInput.trim().toLowerCase().equals("june")) {
month = 6;
} else if (userInput.trim().toLowerCase().equals("july")) {
month = 7;
} else if (userInput.trim().toLowerCase().equals("august")) {
month = 8;
} else if (userInput.trim().toLowerCase().equals("september")) {
month = 9;
} else if (userInput.trim().toLowerCase().equals("october")) {
month = 10;
} else if (userInput.trim().toLowerCase().equals("november")) {
month = 11;
} else if (userInput.trim().toLowerCase().equals("december")) {
month = 12;
}
// Terminate program if month is not a proper month name
if (month < 1 || month > 12) {
System.out.println("Illegal month name; try again");
return;
}
and here's what i'm working with for the year section:
// Prompt the user to enter a year
SimpleIO.prompt("Enter a year: ");
userInput = SimpleIO.readLine();
int year = Integer.parseInt(userInput);
//Here, trying to use hasNextInt to make sure input is an integer
//If it's not, need to give an error message and prompt input again
// public boolean hasNextInt()
//Prompt input again if year is negative
if (year < 0) {
System.out.println("Year cannot be negative; try again");
return;
}
// Determine the number of days in the month
int numberOfDays;
switch (month) {
case 2: // February
numberOfDays = 28;
if (year % 4 == 0) {
numberOfDays = 29;
if (year % 100 == 0 && year % 400 != 0)
numberOfDays = 28;
}
break;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
numberOfDays = 30;
break;
default: numberOfDays = 31;
break;
}
// Display the number of days in the month
System.out.println("There are " + numberOfDays +
" days in this month");
}
}
after seeing the code i'm sure it will be more clear what i'm asking. if they enter a word that isn't a month, prompt them and ask for input again. same thing if they enter a year that isn't integers. thanks in advance!
Running it in a loop, will do:
String userInput;
int month;
do{
SimpleIO.prompt("Enter a month name: ");
userInput = SimpleIO.readLine();
try{
month = Integer.parseInt(userInput);
} catch(NumberFormatException e){
continue;
}
}while(month <= 0 || month > 12);
You should create a loop that keeps prompting the user until the month is correctly inserted. Something in the following lines:
boolean correct_month = false; // Control variable
while(!correct_month)
{
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
...
// If the month is indeed correct
// then correct_month = true;
}
Then you apply the same idea to the years.
Instead of having all of those conditions on the month, I think it is better to add all the month strings into an ArrayList:
ArrayList <String> all_months = new ArrayList <String> ();
and then you just have to use all_months.indexOf with the string insert by the user. If it returns -1 the string is not a valid month, otherwise, it will give you the position where the month is on the list. For example
month = all_months.indexOf(userInput);
if(month != -1){
correct_month = true;
}
Thus, the complete solution would be something like:
ArrayList <String> all_months = new ArrayList <String> ();
all_months.add("january");
... // and so one
int month = 0; // Control variable
while(month <= 0)
{
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
month = all_months.indexOf(userInput.trim().toLowerCase()) + 1;
}

Categories