I have an assignment where I have to use switch. The program is supposed to terminate when the integer -1 is entered. And any number between 1 and 7 will display a day of the week. any other number between 1 and 7 and -1 will display: "Only numbers from 1 to 7 are accepted".
How can I make the program terminate when -1 is entered. Here is the code so far:
Scanner s = new Scanner(System.in);
String res = "";
System.out.println("Input a number ");
int day = s.nextInt();
if(day==-1){
System.exit(0);
}
switch (day) {
case 1:
res="Today is Sunday";
break;
case 2:
res="Today is Monday";
break;
case 3:
res = "Today is Tuesday";
break;
case 4:
res = "Today is Wednesday";
break;
case 5:
res = "Today is Thursday";
break;
case 6:
res = "Today is Friday";
break;
case 7:
res = "Today is Saturday";
break;
default:
res = "Only numbers from 1 to 7 are accepted ";
break;
}
System.out.println(res);
}
}
updated the code with my solution.
Why do you even need the %? You're already explicitly handling every case...let the default handle everything else.
Switch(day)
{
case 1:
..
default:
}
If you give your code 8, well 8%7 == 1 so you'd get Today is Sunday.
try this check whether the day gets greater then the 1,then send it to switch case.
if(day>=1){
System.exit(0);
}else{
switch(day%7){
case:
}
}
Your program is asking for input 1-7 but it will not work for input 7 as you are switching day % 7, if day = 7 then day % 7 = 0. You need to remove day % 7 and place only day. Then the complete solution will be:
System.out.println("Input a number ");
int day = s.nextInt();
switch (day) {
case -1:
System.exit(0);
break;
case 1:
res="Today is Sunday";
break;
case 2:
res="Today is Monday";
break;
case 3:
res = "Today is Tuesday";
break;
case 4:
res = "Today is Wednesday";
break;
case 5:
res = "Today is Thursday";
break;
case 6:
res = "Today is Friday";
break;
case 7:
res = "Today is Saturday";
default:
res = "Only numbers from 1 to 7 are accepted ";
break;
}
System.out.println(res);
}
As Sage's answer, you can put case -1: System.exit(0); break; or use return statement if the logic is in a method (I think using return statement is more graceful than using System.exit()).
However your logic never reach the 'case 7', since you use 'day %7' it will return remnant after dividing by 7, so it will be between 0 and 6 if day is positive or between -6 and 0 if day is negative
Using a do while should help you get your required behaviour
{
Scanner s = new Scanner(System.in);
String res = "";
Integer day;
do{
System.out.println("Input a number ");
day = s.nextInt();
System.out.println(day);
switch (day) {
case 1:
res="Today is Sunday";
break;
case 2:
res="Today is Monday";
break;
case 3:
res = "Today is Tuesday";
break;
case 4:
res = "Today is Wednesday";
break;
case 5:
res = "Today is Thursday";
break;
case 6:
res = "Today is Friday";
break;
case 7:
res = "Today is Saturday";
default:
res = "Only numbers from 1 to 7 are accepted ";
break;
}
System.out.println(res);
}
while (!day.equals(-1));
}
Related
Below the code:
{
System.out.println("Please enter the date you would like to split");
System.out.println("Please make sure it is in the format DDMMYYYY");
date = sc.nextInt();
day = date / 1000000;
month = (date / 10000) - (day * 100);
year = date - (date / 10000) * (10000);
switch(day)
{
case 1: case 21: case 31:
suffix = "st";
break;
case 2: case 22:
suffix = "nd";
break;
case 3: case 23:
suffix = "rd";
break;
case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 24: case 25: case 26: case 27: case 28: case 29: case 30:
suffix = "th";
break;
default:
System.out.println("Error, Please enter a valid day (i.e. DD) that is between 01 - 31");
break;
}
switch(month)
{
case 4: case 6: case 9: case 11:
if ((day < 1) || (day > 30))
{
System.out.println("Error this day does not exist");
}
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if ((day < 1) || (day > 31))
{
System.out.println("Error this day does not exist");
}
break;
case 2:
if ((day < 1) || (day > 28))
{
if ((day != 29))
{
System.out.println("Error this day does not exist");
}
else if ((year % 4 != 0) || ((year % 400 != 0) && (year % 100 == 0)))
{
System.out.println("Error this day does not exist");
}
//If it isn't a leap year, febuary cannot have 29 days
}
break;
default:
System.out.println("Error this day does not exist");
}
switch(month)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "Febuary";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
default:
System.out.println("Error, Please make sure the month (i.e. MM) is between 01 and 12");
break;
}
if ((day == 29) && (month == 2))
{
System.out.println("It is the 29th day of Febuary in " + year + ".");
}
else
{
System.out.println("It is the " + day + suffix + " day of " + monthName + " in " + year + ".");
}
}
So, basically when I run this program, and input 70702020 value, I'll get all the following outputs:
Error, Please enter a valid day (i.e. DD) that is between 01 - 31
Error this day does not exist
Error, Please make sure the month (i.e. MM) is between 01 and 12
And then it would output the final output (this was only intended if the user entered a valid date)
break breaks out of switch statement only
The break commands in your switch statements bail out of the switch statement only, not your entire method.
You have a series of three switch statements.
When you break out of the first switch statement, the flow of control moves on to the second switch statement.
When you break out of the second switch statement, the flow of control moves on to the third switch statement.
When you break out of the third switch statement, the flow of control moves on to the remaining statements.
One of the core concepts of programming is scope. You must learn to think in terms of boxes nested within boxes, like the Russian nesting dolls. Within a switch statement, the break command's scope is just that one statement rather than your entire method. The switch statement is one layer of scope nested within the outer method. The break within the switch statement can only "see" its immediate containing box: the switch statement.
java.time
By the way, parsing as text via the modern java.time classes is much simpler.
try {
LocalDate ld =
LocalDate
.parse(
"70702020" ,
DateTimeFormatter.ofPattern( "ddMMuuuu" )
)
;
} catch ( DateTimeParseException e ) {
…
}
Invalid inputs throw a DateTimeParseException.
You are using a switch instead of an if(blah blah) statement. Meaning, that the statement is true and producing now errors. Your code says nothing is wrong with you input. Your suffix will still print, but print empty quotes as it is an empty string I believe. I suggest checking for entry before using the switch. Or using "System.exit(1)" where your system will exit if incorrect input.
Edit: Also your day by calculation would equal "70" thus making other errors.
I suggest to see the comment, and then execute the code yourself.
I add some comments.
public class TestFormatDate{
public static void main(String []args){
System.out.println("Please enter the date you would like to split");
System.out.println("Please make sure it is in the format DDMMYYYY");
//your input:70702020
int date = 70702020;
//70
int day = date / 1000000;
//70
int month = (date / 10000) - (day * 100);
//2020
int year = date - (date / 10000) * (10000);
String suffix = null;
String monthName = null;
switch(day)
{
case 1: case 21: case 31:
suffix = "st";
break;
case 2: case 22:
suffix = "nd";
break;
case 3: case 23:
suffix = "rd";
break;
case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 24: case 25: case 26: case 27: case 28: case 29: case 30:
suffix = "th";
break;
// day is 70, so the default is executed.
default:
System.out.println("Error, Please enter a valid day (i.e. DD) that is between 01 - 31");
break;
}
switch(month)
{
case 4: case 6: case 9: case 11:
if ((day < 1) || (day > 30))
{
System.out.println("Error this day does not exist");
}
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if ((day < 1) || (day > 31))
{
System.out.println("Error this day does not exist");
}
break;
case 2:
if ((day < 1) || (day > 28))
{
if ((day != 29))
{
System.out.println("Error this day does not exist");
}
else if ((year % 4 != 0) || ((year % 400 != 0) && (year % 100 == 0)))
{
System.out.println("Error this day does not exist");
}
//If it isn't a leap year, febuary cannot have 29 days
}
break;
// month is 70, so the default is executed.
default:
System.out.println("Error this day does not exist");
}
switch(month)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "Febuary";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
// month is 70, so the default is executed.
default:
System.out.println("Error, Please make sure the month (i.e. MM) is between 01 and 12");
break;
}
if ((day == 29) && (month == 2))
{
System.out.println("It is the 29th day of Febuary in " + year + ".");
}
// day is 70, so the else is executed.
else
{
System.out.println("It is the " + day + suffix + " day of " + monthName + " in " + year + ".");
}
}
}
So here is a link to another persons question and its my exact assignment.
https://stackoverflow.com/questions/39834840/concatenating-switch-statements-for-playing-cards-assignment
How can I get my result string to display the valueofCard then the suitofCard in this format "value of suit"
Also, how can I shorten up the 2-10 value range within a switch case?
I am aware I have " of " and a couple other lines that make no sense, I just figured I am missing something big anyways.
Thanks for any help, have lots of catching up to do.
System.out.print("Please enter a letter/integer of a playing card (A, J, Q, K, or 2 - 10),\nfollowed by card type (D, H, S, C):");
Scanner kbd = new Scanner(System.in);
String userInput = kbd.nextLine();
String valueofCard = userInput.substring(0, userInput.length() / 2); // gives first half of string
String suitofCard = userInput.substring(userInput.length() / 2); //give last half of string with + 1 if odd
StringBuilder result = new StringBuilder();
switch (valueofCard) {
case "A":
result.append("Ace of ");
break;
case "J":
result.append("Jack of ");
break;
case "Q":
result.append("Queen of ");
break;
case "K":
result.append("King of ");
break;
case "2":
result.append("2 of ");
case "3":
result.append("3 of ");
case "4":
result.append("4 of ");
case "5":
result.append("5 of ");
case "6":
result.append("6 of ");
case "7":
result.append("7 of ");
case "8":
result.append("8 of ");
case "9":
result.append("9 of ");
case "10":
result.append("10 of ");
break;
}
switch (suitofCard) {
case "D":
result.append("Diamonds");
break;
case "H":
result.append("Hearts");
break;
case "S":
result.append("Spades");
break;
case "C":
result.append("Clubs");
break;
}
System.out.println(result.toString());
kbd.close();
}
}
Option 1 - You could use a Stringbuilder to do this.
StringBuilder cardAndSuit = new StringBuilder();
switch (valueofCard) {
case "A":
cardAndSuit.append("Ace of");
.....
switch (suitofCard) {
case "D":
cardAndSuit.append("Diamonds");
break;
...
// Print the final string
System.out.println(cardAndSuit.toString()); // Ace of Diamonds
Option 2 - You could also just create a regular String and append to it.
String cardAndSuit = '';
cardAndSuit += "Ace of";
cardAndSuit += " Diamonds";
System.out.println(cardAndSuit); // Ace of Diamonds
2 is probably easier and more terse. Option 2 will actually be turned into option 1 by the compiler behind the scenes.
I am trying to do the following for a Java switch method with a series of JUnit Asserts but am stuck on using "less than" and "greater than" for two cases (see string/int error below), and am not sure how to use the ">" and "<" in my cases.
Here is the exercise followed by my code, followed by the error.
/*
Create a method which uses a switch statement to return a String representing the int passed in as a parameter to the method:
• given 1 return "One"
• given 2 return "Two"
• given 3 return "Three"
• given 4 return "Four"
• given an integer > 4, return "Too big"
• given an integer < 1, return "Too small"
*/
#Test
public void switchIntExample() {
assertEquals("One", stringRepInt(1));
assertEquals("Two", stringRepInt(2));
assertEquals("Three", stringRepInt(3));
assertEquals("Four", stringRepInt(4));
assertEquals("Too big.", stringRepInt(>4));
// assertEquals("Too small.", stringRepInt(<4));
}
//Switch statement for above:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
//TODO: question on how to do LESS THAN and GREATER THAN:
// error line:
case (numVar > 4):
numVar = "Too big.";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
ERROR:
Error:(293, 27) java: bad operand types for binary operator '>'
first type: java.lang.String
second type: int
case statements only support constant expressions (you cannot do less than, or greater than, in a case and you can't test numVar - the String - with less than). You can use an if and something like
public String stringRepInt(int numberSize) {
String numVar = null;
if (numberSize > 4) {
numVar = "Too big.";
} else {
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
You should add it to the default section, so like this:
default:
numVar = "Too Big";
break;
The purpose of the default section is to deal with all cases not dealt with by the switch cases. You should be taking advantage of that (as #GreenMatt and #FredK mentioned in comments) by putting the 'if checks' in the default section, as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
break;
}
System.out.println(numVar);
return numVar;
}
Further, you could add else if (numberSize < 1) numVar = "Too small"; under the if statement if you want to check for number's smallest than one. This is also important because it prevents your method from returning null. (Which currently happens if the user enters a value less than 1)
The resulting code is as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
else
numVar = "Too small";
break;
}
System.out.println(numVar);
return numVar;
}
In the error line you are comparing String and int.
error line: case (numVar > 4): numVar = "Too big."; break;
you have declared numVar as String and comparing that with int value 4. Please correct that or I think you are trying to compare numberSize with value 4. Convert that String to int and compare it.
My instructor requires us to take the package from our code and make it a default package. The only problem is he taught us how to do that through Windows and I have a MacBook so his way isn't working. I can't figure out how to do it. I've attached the code to the bottom in case that will help.
package romannumeralcalculator;
import java.util.*;
public class RomanNumeralCalculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int integer;
do {
System.out.print("Please enter an interger from 1 to 5999. Enter a negative number to exit. \n ->");
integer = input.nextInt();
} while (integer >= 6000);
while (integer == 0) {
System.out.println("");
break;
}
String results = "";
int ones = integer % 10;
int tens = (integer / 10) % 10;
int hundreds = (integer / 100) % 10;
int thousands = (integer / 1000) % 1000;
switch (thousands) {
case 1:
results += "M";
break;
case 2:
results += "MM";
break;
case 3:
results += "MMM";
break;
case 4:
results += "MMMM";
break;
case 5:
results += "MMMMM";
break;
default:
System.out.println("");
}
switch (hundreds) {
case 1:
results += "C";
break;
case 2:
results += "CC";
break;
case 3:
results += "CCC";
break;
case 4:
results += "CD";
break;
case 5:
results += "D";
break;
case 6:
results += "DC";
break;
case 7:
results += "DCC";
break;
case 8:
results += "DCCC";
break;
case 9:
results += "CM";
break;
default:
System.out.println("");
}
switch (tens) {
case 1:
results += "X";
break;
case 2:
results += "XX";
break;
case 3:
results += "XXX";
break;
case 4:
results += "XL";
break;
case 5:
results += "L";
break;
case 6:
results += "LX";
break;
case 7:
results += "LXX";
break;
case 8:
results += "LXXX";
break;
case 9:
results += "XC";
break;
default:
System.out.println("");
}
switch (ones) {
case 1:
results += "I";
break;
case 2:
results += "II";
break;
case 3:
results += "III";
break;
case 4:
results += "IV";
break;
case 5:
results += "V";
break;
case 6:
results += "VI";
break;
case 7:
results += "VII";
break;
case 8:
results += "VIII";
break;
case 9:
results += "IX";
break;
default:
System.out.println("");
}
System.out.println(results);
}
}
In the projects tab of Netbeans in the top-left:
Expand the tree for your Project.
Expand the Source Packages folder.
Expand the package with your java file.
Drag the java file from under the package to the Source Packages folder.
A dialog box will pop up with the title Move Class. On that dialog click the Refactor button.
This should be the same procedure in Windows. I am not sure why your professor told you something different.
Sonar gives a major violation error ("Cyclomatic Complexity") for the following code. Following method is used to get the date in a special format, e.g. 14-02-3 (Year-month-weekid).
How can I overcome this violation?
private String finalDateForProject;
public String getFinalDateForProject() {
return finalDateForProject;
}
public void setFinalDateForProject(Integer year,Integer month, Integer weekId) {
String projectMonth;
switch (month) {
case 0: projectMonth = "01";
break;
case 1: projectMonth = "02";
break;
case 2: projectMonth = "03";
break;
case 3: projectMonth = "04";
break;
case 4: projectMonth = "05";
break;
case 5: projectMonth = "06";
break;
case 6: projectMonth = "07";
break;
case 7: projectMonth = "08";
break;
case 8: projectMonth = "09";
break;
case 9: projectMonth = "10";
break;
case 10: projectMonth = "11";
break;
case 11: projectMonth = "12";
break;
default: projectMonth = " ";
break;
}
String yearEdited = year.toString();
yearEdited = yearEdited.replace("20", "");
String projectTrendDate = yearEdited +"-"+projectMonth+"-W"+weekId.toString();
this.finalDateForProject =projectTrendDate;
}
One way to reduce cyclomatic complexity that I see is to replace the switch statement. Just create an array or HashMap that will map month index to number;
public void setFinalDateForProject(Integer year,Integer month, Integer weekId) {
String[] months = new String[] {"01", "02", "03", "04", "05", ...}
// Replace switch statement
String projectMonth = months[month];
// Rest of your code
...
}
Another way to solve this problem will be to replace mapping of numbers to strings with converting integer to String using String.format. Use something like:
String projectMonth = String.format("%02d", month + 1);
A simple way to think about it is, cyclomatic complexity increases the more "branches" you have in your code. So with your switch statement you have a whole lot of branches (13 in fact, if I'm counting right). The switch statement can be replaced with this:
if (month < 0 || month > 11) {
projectMonth = " ";
} else {
month++;
projectMonth = ((month < 10) ? "0" : "") + Integer.toString(month);
}
Note that this still has branches, namely the if/else and ternary ?. But these could probably be removed as well, a good alternative with an array is given in the other answer.
The question shouldn't be "How can I reduce the cyclomatic complexity?", but rather "What is the best way to write this function?". One answer is return String.format("%02d-%02d-W%2d", year-2000, month+1, weekId);.