I am making a program which can make singular words plural, however I am unsure how I would go about checking the exceptions in the string array I created. I know there are more exceptions, but for now I just want to get what I have working. I made a method called "checkExceptions", but what would I put inside of it for the program to check that method first before moving on?
import java.util.Scanner;
public class FormingPlurals {
static final String SENTINEL = "done";
static final Scanner IN = new Scanner(System.in);
static String[] exceptions = {"fish", "fox", "deer", "moose", "sheep", "cattle"};
public static void run() {
while (true) {
System.out.println("Enter a word to make it plural. Enter 'done' to stop: ");
String noun = IN.nextLine();
if (noun.toLowerCase().equals(SENTINEL)) {
System.out.println("Goodbye...");
break;
}
System.out.println(makePlural(noun) + " ");
}
}
public static void checkExceptions() {
}
static String makePlural(String singularWord) {
String pluralWord = "";
int length = singularWord.length();
String checker = singularWord.substring(0, singularWord.length() - 1);
char lastLetter = singularWord.charAt(singularWord.length() - 1);
if (length == 1) {
pluralWord = singularWord + "'s";
} else
switch (lastLetter) {
case 's':
case 'x':
case 'z':
pluralWord = singularWord + "es";
break;
case 'h':
if ((singularWord.charAt(singularWord.length() - 2) == 'c') || (singularWord.charAt(singularWord.length() - 2) == 's')) {
pluralWord = singularWord + "es";
break;
}
case 'f':
if (EnglishConsonant(singularWord.charAt(singularWord.length() - 2))) {
pluralWord = checker + "ves";
break;
}
case 'y':
if (EnglishConsonant(singularWord.charAt(singularWord.length() - 2))) {
pluralWord = checker + "ies";
break;
}
default:
pluralWord = singularWord + "s";
break;
}
return pluralWord;
}
public static boolean EnglishConsonant(char ch) {
switch (Character.toLowerCase(ch)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return false;
default:
return true;
}
}
public static void main(String[] args) {
run();
}
}
It is also possible to do that with arrays, but it is easier to use a map in this case. You could create a map
Map<String,String> irregularPlurals = new HashMap<>();
irregularPlurals.put("sheep","sheep");
irregularPlurals.put("fox","foxes");
Then you could use simply Map interface's methods like get() or containsKey() to check if a given word is has an irregular plural form. A simple method to check it would then be:
String irregularPlural = irregularPlurals.get(singularWord);
if (irregularPlural != null){
return irregularPlural ;
}
BTW, it would be a good idea to rename the methods checkException(), as in Java exceptions and checked exceptions are language concepts, so a reader may think that that method is about handling Java exceptions.
For one, I'd place the exceptions array inside makePlural itself and handle it there.
Secondly, I'd go from the most specialized case to the least one, so
First look at word exceptions
Look at special plurals like 'es', 'ves' etc.
add 's' to the word and return it
Also, the moment I find a match in either the exceptions or special plurals, I'd calculate and immediately return the result, to prevent other rules from matching and adding more stuff to pluralWord
If I had to use a function for the exceptions, it would be
public static boolean isException(String word){
String[] exceptions={"fish", "deer"};
for(int i=0;i<exceptions.length();i++) {
if(exceptions[i].equals(word))
return true;
}
return false;
}
Related
I've been following Tim Buchalka's course Java Programming Masterclass for Software Developers and I've been modifying his program from lesson 118.
I want to update my list at the runtime while using the list iterator (navigate method). The program runs fine, but if I update my list, Java throws an error: ConcurrentModificationException
I have come up with the following solution:
Whenever a user performs a modification of the list, other methods run, and update the list and pass it to the navigate() method. By doing this, my program enters multi-level nested methods, and the problem comes up when a user wants to exit from the program (case 0: in navigate() method). User has to press 0 as many times as many nested methods were ran.
My initial idea was to count how many times navigate() was nested, then using for loop return as many times as it was nested. But later I understood it does not make sense
What can I do to exit from the program by using case 0: just once?
package com.practice;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class List extends Traveler {
private LinkedList<String> linkedList;
private String tripName;
public List(String travelerName, int travelerAge, String tripName) {//it has to have same amount of parameters or more with super constructor!
super(travelerName, travelerAge);
this.tripName = tripName;
this.linkedList = new LinkedList<>();
}
public List(){} //it has to have same amount of parameters or more with super constructor!
public LinkedList<String> getLinkedList() {
return linkedList;
}
public String getTripName() {
return tripName;
}
private void removeCity(LinkedList<String> cityList, String deletedCity) {
if(cityList.remove(deletedCity)) {
System.out.println(deletedCity + " has been removed");
} else System.out.println("Could not find the city you want to remove");
List.navigate(cityList);
}
//adds a new city and update the list without an error
private void noExceptionError(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator();
while((listIterator.hasNext())) {
int comparison = listIterator.next().compareTo(cityName);
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous();
break;
}
}
listIterator.add(cityName);
List.navigate(listOfCities);
}
private void loadToList(LinkedList<String> listOfCities) {
alphabeticallyAdd(listOfCities, "Poznan");
alphabeticallyAdd(listOfCities, "Gdansk");
alphabeticallyAdd(listOfCities, "Szczeczin");
alphabeticallyAdd(listOfCities, "Warszawa");
alphabeticallyAdd(listOfCities, "Lodz");
alphabeticallyAdd(listOfCities, "Wroclaw");
List.navigate(listOfCities);
}
private void alphabeticallyAdd(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator(); //just a setup; doesn't point to the 1st element
while((listIterator.hasNext())) {
//if value is greater, the word that is in the list is alphabetically bigger, thus, put it before the list element
//if equal, it is duplicate! return false
// else it is less, thus, we have to move further in the list
int comparison = listIterator.next().compareTo(cityName); //retrieves the 1st value and goes to the next
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous(); //because we've used .next() in the int comparison initialization
listIterator.add(cityName); //don't use linkedList.add because it doesn't know the int comparison, so cannot properly add!!!
return;
}
}
listIterator.add(cityName); //adding at the end of the list
}
public static void navigate(LinkedList<String> listOfCities) {
Scanner userChoice = new Scanner(System.in);
List travelListObject = new List();
ListIterator<String> listIterator = listOfCities.listIterator();
boolean goingForward = true;
while(true) {
Main.menu();
int choice = userChoice.nextInt();
userChoice.nextLine(); //takes care of enter key problem
switch(choice) {
case 0:
System.out.println("Goodbye");
//possible improvement
/* for(int i = 0; i <= List.amountNestedMethods; i++) {
return;
}*/
return;
case 1: //moving forward
if(!goingForward) {
if(listIterator.hasNext()) {
listIterator.next();
}
}
if(listIterator.hasNext()) {
System.out.println(listIterator.next());
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
goingForward = true;
} else {
System.out.println("No more cities in the list");
goingForward = false;
}
break;
case 2: //moving back
if(goingForward) {
if(listIterator.hasPrevious()) {
listIterator.previous();
}
goingForward = false;
}
if(listIterator.hasPrevious()) {
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
System.out.println(listIterator.previous());
} else {
System.out.println("You're at the beginning of the list");
goingForward = true;
}
break;
case 3:
Main.printCities(listOfCities);
break;
case 4:
break;
case 5:
System.out.println("Write new city");
String addedCity = userChoice.next();
travelListObject.noExceptionError(listOfCities, addedCity);
break;
case 6:
System.out.println("Write the city you want to delete");
String deletedCity = userChoice.next();
travelListObject.removeCity(listOfCities, deletedCity);
break;
case 7:
System.out.println("You have been in " + Traveler.getNumberVisitedCities() + " cities in total");
break;
case 9:
travelListObject.loadToList(listOfCities);
break;
default:
System.out.println("Something weird happened. Try to choose an option again");
}
}
}
}
If you want to exit the program you can simply call System.exit(n), where the n is an integer return code (the convention being that code 0 means normal execution and other values indicate some sort of error).
I'm trying to migrate this C# code to Java.
Is there any possibility to migrate the unicodeCategory to a regex in Java, or is there a possibility to do the Unicode category by Java directly?
foreach (var currentChar in preNormalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(currentChar);
//https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Globalization.UnicodeCategory.LowercaseLetter);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.6);k(DevLang-csharp)&rd=true
switch (unicodeCategory)
{
//case UnicodeCategory.NonSpacingMark:
//case UnicodeCategory.SpacingCombiningMark:
//case UnicodeCategory.EnclosingMark:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.OtherPunctuation:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.MathSymbol:
case UnicodeCategory.ModifierSymbol:
case UnicodeCategory.OtherSymbol:
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.ParagraphSeparator:
if (!isPreviousSpaceChar)
builder.Append(" ");
isPreviousSpaceChar = true;
break;
case UnicodeCategory.Control:
case UnicodeCategory.CurrencySymbol:
case UnicodeCategory.EnclosingMark:
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.Format:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherNotAssigned:
case UnicodeCategory.PrivateUse:
case UnicodeCategory.Surrogate:
// Caratères ignorés.
break;
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LetterNumber:
case UnicodeCategory.DecimalDigitNumber:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.OtherNumber:
case UnicodeCategory.TitlecaseLetter:
default:
builder.Append(currentChar);
isPreviousSpaceChar = false;
break;
}
}
var normalizedString = builder.ToString() ?? string.Empty;
normalizedString = normalizedString.ToUpper();
normalizedString = normalizedString.Trim();
return normalizedString;
There is a getType(char) that will return an int that you can then compare with a list of constants that are enumerated in the Java Docs.
Note that both C# code and the getType(char) are "wrong" because they don't support non-BMP characters (characters that use two char). But splitting a string in its "Rune" was a little more complex in C# until .NET Core 3.0.
public static String convert(String preNormalizedString) {
StringBuilder builder = new StringBuilder();
boolean isPreviousSpaceChar = false;
for (int i = 0; i < preNormalizedString.length(); i++) {
char currentChar = preNormalizedString.charAt(i);
int unicodeCategory = Character.getType(currentChar);
switch (unicodeCategory) {
case Character.DASH_PUNCTUATION:
case Character.CONNECTOR_PUNCTUATION:
//... You'll have to complete the list
if (!isPreviousSpaceChar)
builder.append(" ");
isPreviousSpaceChar = true;
break;
case Character.CONTROL:
case Character.CURRENCY_SYMBOL:
//... You'll have to complete the list
// Caratères ignorés.
break;
case Character.LOWERCASE_LETTER:
case Character.UPPERCASE_LETTER:
//... You'll have to complete the list
default:
builder.append(currentChar);
break;
}
}
String normalizedString = builder.toString();
normalizedString = normalizedString.toUpperCase();
normalizedString = normalizedString.trim();
return normalizedString;
}
How can I convert the following code to switch statement?
String x = "user input";
if (x.contains("A")) {
//condition A;
} else if (x.contains("B")) {
//condition B;
} else if(x.contains("C")) {
//condition C;
} else {
//condition D;
}
There is a way, but not using contains. You need a regex.
final Matcher m = Pattern.compile("[ABCD]").matcher("aoeuaAaoe");
if (m.find())
switch (m.group().charAt(0)) {
case 'A': break;
case 'B': break;
}
You can't switch on conditions like x.contains(). Java 7 supports switch on Strings but not like you want it. Use if etc.
Condition matching is not allowed in java in switch statements.
What you can do here is create an enum of your string literals, and using that enum create a helper function which returns the matched enum literal. Using that value of enum returned, you can easily apply switch case.
For example:
public enum Tags{
A("a"),
B("b"),
C("c"),
D("d");
private String tag;
private Tags(String tag)
{
this.tag=tag;
}
public String getTag(){
return this.tag;
}
public static Tags ifContains(String line){
for(Tags enumValue:values()){
if(line.contains(enumValue)){
return enumValue;
}
}
return null;
}
}
And inside your java matching class,do something like:
Tags matchedValue=Tags.ifContains("A");
if(matchedValue!=null){
switch(matchedValue){
case A:
break;
etc...
}
#Test
public void test_try() {
String x = "userInputA"; // -- test for condition A
String[] keys = {"A", "B", "C", "D"};
String[] values = {"conditionA", "conditionB", "conditionC", "conditionD"};
String match = "default";
for (int i = 0; i < keys.length; i++) {
if (x.contains(keys[i])) {
match = values[i];
break;
}
}
switch (match) {
case "conditionA":
System.out.println("some code for A");
break;
case "conditionB":
System.out.println("some code for B");
break;
case "conditionC":
System.out.println("some code for C");
break;
case "conditionD":
System.out.println("some code for D");
break;
default:
System.out.println("some code for default");
}
}
Output:
some code for A
No you cannot use the switch with conditions
The JAVA 7 allows String to be used with switch case
Why can't I switch on a String?
But conditions cannot be used with switch
you can only compare the whole word in switch.
For your scenario it is better to use if
also HashMap:
String SomeString = "gtgtdddgtgtg";
Map<String, Integer> items = new HashMap<>();
items.put("aaa", 0);
items.put("bbb", 1);
items.put("ccc", 2);
items.put("ddd", 2);
for (Map.Entry<String, Integer> item : items.entrySet()) {
if (SomeString.contains(item.getKey())) {
switch (item.getValue()) {
case 0:
System.out.println("do aaa");
break;
case 1:
System.out.println("do bbb");
break;
case 2:
System.out.println("do ccc&ddd");
break;
}
break;
}
}
public class A {
public void search(boolean[] searchList) {
// searchList array is used to identify what options to search for in a given order
// e.g. boolean [] searchList = new boolean [] {false, false, true, false};
boolean searchL = false;
boolean searchM = false;
boolean searchK = false;
boolean searchA = false;
if(searchList[0] == true) searchL = true;
if(searchList[1] == true) searchM = true;
if(searchList[2] == true) searchK = true;
if(searchList[3] == true) searchA = true;
if(searchL == true) // write a query to search for all Ls
if(searchM == true) // write a query to search for all Ms
...........
}
Is there a way I can simplify this code ?
#All : Sorry for posting a wrong question before. I was confused!
Thanks,
Sony
I am a big fan of enums:
public class A {
enum SearchType {
L, M, A, K;
}
public void search(SearchType type) {
switch (type) {
case L:
System.out.println("Searching for L");
break;
case M:
System.out.println("Searching for M");
break;
case A:
System.out.println("Searching for A");
break;
case K:
System.out.println("Searching for K");
break;
default:
System.out.println("what to do here?");
// throw exception?
}
note also: your scenario allowed more than one search boolean to be true at a time, I assumed that was not your goal, but if it is we can tweak this a bit.
You should convert your state into an enum. For example your search booleans seem to be exclusive so i would do something like this:
enum SearchOption {
searchA, searchK, searchL, searchM
}
// then you can do
SearchOption searchOption = searchA;
switch (searchOption) {
case searchA:
System.out.println("I am searching for A");
break;
case searchK:
System.out.println("I am searching for K");
break;
case searchL:
System.out.println("I am searching for L");
break;
case searchM:
System.out.println("I am searching for M");
break;
}
If your states aren't exclusive you should try build to build a super set of exclusive states initially.
Why don't employ OOP? Like:
public interface Seeker {
void seek();
}
public class LSeeker implements Seeker {
void seek() { System.out.println("Will search for L"); }
}
// ... More implementations of Seeker
public class SeekDriver {
void seek(Seeker seeker) { seeker.seek(); }
}
public class A {
public enum SearchOption {
SEARCH_L,
SEARCH_M,
SEARCH_A,
SEARCH_K;
}
/**
* Make them pass in an enum for your search.
* Pros: type safe, can only use the selections you give
* Cons: must add to the enum to add new types
* #param option
*/
public void enumSearch(SearchOption option) {
switch(option) {
case SEARCH_A:
System.out.println("I am searching for A");
break;
case SEARCH_K:
System.out.println("I am searching for K");
break;
case SEARCH_L:
System.out.println("I am searching for L");
break;
case SEARCH_M:
System.out.println("I am searching for M");
break;
}
}
/**
* Use a primitive for your input
* Pros: Gives you more options without updating the enum
* Cons: Users could enter input you don't really want them to use
* #param option
*/
public void charSearch(char option) {
switch(option) {
case 'a':
case 'A':
System.out.println("I am searching for A");
break;
case 'k':
case 'K':
System.out.println("I am searching for K");
break;
case 'l':
case 'L':
System.out.println("I am searching for L");
break;
case 'm':
case 'M':
System.out.println("I am searching for M");
break;
}
}
/**
* Use a primitive and don't even actually check it! Just run with it!
* #param option
*/
public void uncheckedSearch(char option) {
System.out.println("I am searching for " + option);
}
}
As per your comment, here's my updated example of that method - make sure the comment at the top is updated!
/**
* Perform the search based on the options provided
* The list should be in the order of L, M, A, K
* #note update this comment as more search options are added
* #param searchList the list of flags indicating what to search for
*/
public void search(boolean[] searchList) {
// as per docs, [0] denotes an L search:
if(searchList[0])
// write a query to search for all Ls
// as per docs, [1] denotes an M search:
if(searchList[1])
// write a query to search for all Ms
// as per docs, [2] denotes an A search:
if(searchList[2])
// write a query to search for all As
// as per docs, [3] denotes a K search:
if(searchList[3])
// write a query to search for all Ks
}
Latest idea:
// Use the SearchOption enum from above
Map<SearchOption, String> searches = new HashMap<SearchOption, String>();
public List<SearchResult> search(List<SearchOption> options) {
List<SearchResult> results = new LinkedList<SearchResult>();
for(SearchOption option : options) {
String query = searches.get(option);
SearchResult result = MySearchService.executeQuery(query);
results.add(result);
}
return results;
}
Like this: ?
public class A {
public void search() {
private static final int SEARCH_L = -1;
private static final int SEARCH_M = 0;
private static final int SEARCH_A = 1;
private static final int SEARCH_K = 2;
int status;
switch(status){
case SEARCH_L:
System.out.println("I am searching for L");
break;
case SEARCH_M:
System.out.println("I am searching for M");
break;
// Etc
default:
// Log error didn't hit a known status
break;
}
}
Just trying to figure out how to use many multiple cases for a Java switch statement. Here's an example of what I'm trying to do:
switch (variable)
{
case 5..100:
doSomething();
break;
}
versus having to do:
switch (variable)
{
case 5:
case 6:
etc.
case 100:
doSomething();
break;
}
Any ideas if this possible, or what a good alternative is?
The second option is completely fine. I'm not sure why a responder said it was not possible. This is fine, and I do this all the time:
switch (variable)
{
case 5:
case 6:
etc.
case 100:
doSomething();
break;
}
Sadly, it's not possible in Java. You'll have to resort to using if-else statements.
public class SwitchTest {
public static void main(String[] args){
for(int i = 0;i<10;i++){
switch(i){
case 1: case 2: case 3: case 4: //First case
System.out.println("First case");
break;
case 8: case 9: //Second case
System.out.println("Second case");
break;
default: //Default case
System.out.println("Default case");
break;
}
}
}
}
Out:
Default case
First case
First case
First case
First case
Default case
Default case
Default case
Second case
Second case
Src: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Maybe not as elegant as some previous answers, but if you want to achieve switch cases with few large ranges, just combine ranges to a single case beforehand:
// make a switch variable so as not to change the original value
int switchVariable = variable;
//combine range 1-100 to one single case in switch
if(1 <= variable && variable <=100)
switchVariable = 1;
switch (switchVariable)
{
case 0:
break;
case 1:
// range 1-100
doSomething();
break;
case 101:
doSomethingElse();
break;
etc.
}
One Object Oriented option to replace excessively large switch and if/else constructs is to use a Chain of Responsibility Pattern to model the decision making.
Chain of Responsibility Pattern
The chain of responsibility pattern
allows the separation of the source of
a request from deciding which of the
potentially large number of handlers
for the request should action it. The
class representing the chain role
channels the requests from the source
along the list of handlers until a
handler accepts the request and
actions it.
Here is an example implementation that is also Type Safe using Generics.
import java.util.ArrayList;
import java.util.List;
/**
* Generic enabled Object Oriented Switch/Case construct
* #param <T> type to switch on
*/
public class Switch<T extends Comparable<T>>
{
private final List<Case<T>> cases;
public Switch()
{
this.cases = new ArrayList<Case<T>>();
}
/**
* Register the Cases with the Switch
* #param c case to register
*/
public void register(final Case<T> c) { this.cases.add(c); }
/**
* Run the switch logic on some input
* #param type input to Switch on
*/
public void evaluate(final T type)
{
for (final Case<T> c : this.cases)
{
if (c.of(type)) { break; }
}
}
/**
* Generic Case condition
* #param <T> type to accept
*/
public static interface Case<T extends Comparable<T>>
{
public boolean of(final T type);
}
public static abstract class AbstractCase<T extends Comparable<T>> implements Case<T>
{
protected final boolean breakOnCompletion;
protected AbstractCase()
{
this(true);
}
protected AbstractCase(final boolean breakOnCompletion)
{
this.breakOnCompletion = breakOnCompletion;
}
}
/**
* Example of standard "equals" case condition
* #param <T> type to accept
*/
public static abstract class EqualsCase<T extends Comparable<T>> extends AbstractCase<T>
{
private final T type;
public EqualsCase(final T type)
{
super();
this.type = type;
}
public EqualsCase(final T type, final boolean breakOnCompletion)
{
super(breakOnCompletion);
this.type = type;
}
}
/**
* Concrete example of an advanced Case conditional to match a Range of values
* #param <T> type of input
*/
public static abstract class InRangeCase<T extends Comparable<T>> extends AbstractCase<T>
{
private final static int GREATER_THAN = 1;
private final static int EQUALS = 0;
private final static int LESS_THAN = -1;
protected final T start;
protected final T end;
public InRangeCase(final T start, final T end)
{
this.start = start;
this.end = end;
}
public InRangeCase(final T start, final T end, final boolean breakOnCompletion)
{
super(breakOnCompletion);
this.start = start;
this.end = end;
}
private boolean inRange(final T type)
{
return (type.compareTo(this.start) == EQUALS || type.compareTo(this.start) == GREATER_THAN) &&
(type.compareTo(this.end) == EQUALS || type.compareTo(this.end) == LESS_THAN);
}
}
/**
* Show how to apply a Chain of Responsibility Pattern to implement a Switch/Case construct
*
* #param args command line arguments aren't used in this example
*/
public static void main(final String[] args)
{
final Switch<Integer> integerSwitch = new Switch<Integer>();
final Case<Integer> case1 = new EqualsCase<Integer>(1)
{
#Override
public boolean of(final Integer type)
{
if (super.type.equals(type))
{
System.out.format("Case %d, break = %s\n", type, super.breakOnCompletion);
return super.breakOnCompletion;
}
else
{
return false;
}
}
};
integerSwitch.register(case1);
// more instances for each matching pattern, granted this will get verbose with lots of options but is just
// and example of how to do standard "switch/case" logic with this pattern.
integerSwitch.evaluate(0);
integerSwitch.evaluate(1);
integerSwitch.evaluate(2);
final Switch<Integer> inRangeCaseSwitch = new Switch<Integer>();
final Case<Integer> rangeCase = new InRangeCase<Integer>(5, 100)
{
#Override
public boolean of(final Integer type)
{
if (super.inRange(type))
{
System.out.format("Case %s is between %s and %s, break = %s\n", type, this.start, this.end, super.breakOnCompletion);
return super.breakOnCompletion;
}
else
{
return false;
}
}
};
inRangeCaseSwitch.register(rangeCase);
// run some examples
inRangeCaseSwitch.evaluate(0);
inRangeCaseSwitch.evaluate(10);
inRangeCaseSwitch.evaluate(200);
// combining both types of Case implementations
integerSwitch.register(rangeCase);
integerSwitch.evaluate(1);
integerSwitch.evaluate(10);
}
}
This is just a quick straw man that I whipped up in a few minutes, a more sophisticated implementation might allow for some kind of Command Pattern to be injected into the Case implementations instances to make it more of a call back IoC style.
Once nice thing about this approach is that Switch/Case statements are all about side affects, this encapsulates the side effects in Classes so they can be managed, and re-used better, it ends up being more like Pattern Matching in a Functional language and that isn't a bad thing.
I will post any updates or enhancements to this Gist on Github.
This is possible with switch enhancements in Java 14. Following is a fairly intuitive example of how the same can be achieved.
switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> System.out.println("this month has 31 days");
case 4, 6, 9 -> System.out.println("this month has 30 days");
case 2 -> System.out.println("February can have 28 or 29 days");
default -> System.out.println("invalid month");
}
According to this question, it's totally possible.
Just put all cases that contain the same logic together, and don't put break behind them.
switch (var) {
case (value1):
case (value2):
case (value3):
//the same logic that applies to value1, value2 and value3
break;
case (value4):
//another logic
break;
}
It's because case without break will jump to another case until break or return.
EDIT:
Replying the comment, if we really have 95 values with the same logic, but a way smaller number of cases with different logic, we can do:
switch (var) {
case (96):
case (97):
case (98):
case (99):
case (100):
//your logic, opposite to what you put in default.
break;
default:
//your logic for 1 to 95. we enter default if nothing above is met.
break;
}
If you need finer control, if-else is the choice.
JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.
Now you can:
directly assign variable from switch expression,
use new form of switch label (case L ->):
The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.
use multiple constants per case, separated by commas,
and also there are no more value breaks:
To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.
Switch expression example:
public class SwitchExpression {
public static void main(String[] args) {
int month = 9;
int year = 2018;
int numDays = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> {
if (java.time.Year.of(year).isLeap()) {
System.out.println("Wow! It's leap year!");
yield 29;
} else {
yield 28;
}
}
default -> {
System.out.println("Invalid month.");
yield 0;
}
};
System.out.println("Number of Days = " + numDays);
}
}
Basically:
if (variable >= 5 && variable <= 100)
{
doSomething();
}
If you really needed to use a switch, it would be because you need to do various things for certain ranges. In that case, yes, you're going to have messy code, because things are getting complex and only things which follow patterns are going to compress well.
The only reason for a switch is to save on typing the variable name if you're just testing for numeric switching values. You aren't going to switch on 100 things, and they aren't going to be all doing the same thing. That sounds more like an 'if' chunk.
From the last java-12 release multiple constants in the same case label is available in preview language feature
It is available in a JDK feature release to provoke developer feedback based on real world use; this may lead to it becoming permanent in a future Java SE Platform.
It looks like:
switch(variable) {
case 1 -> doSomething();
case 2, 3, 4 -> doSomethingElse();
};
See more JEP 325: Switch Expressions (Preview)
// Noncompliant Code Example
switch (i) {
case 1:
doFirstThing();
doSomething();
break;
case 2:
doSomethingDifferent();
break;
case 3: // Noncompliant; duplicates case 1's implementation
doFirstThing();
doSomething();
break;
default:
doTheRest();
}
if (a >= 0 && a < 10) {
doFirstThing();
doTheThing();
}
else if (a >= 10 && a < 20) {
doTheOtherThing();
}
else if (a >= 20 && a < 50) {
doFirstThing();
doTheThing(); // Noncompliant; duplicates first condition
}
else {
doTheRest();
}
//Compliant Solution
switch (i) {
case 1:
case 3:
doFirstThing();
doSomething();
break;
case 2:
doSomethingDifferent();
break;
default:
doTheRest();
}
if ((a >= 0 && a < 10) || (a >= 20 && a < 50)) {
doFirstThing();
doTheThing();
}
else if (a >= 10 && a < 20) {
doTheOtherThing();
}
else {
doTheRest();
}
It is possible to handle this using Vavr library
import static io.vavr.API.*;
import static io.vavr.Predicates.*;
Match(variable).of(
Case($(isIn(5, 6, ... , 100)), () -> doSomething()),
Case($(), () -> handleCatchAllCase())
);
This is of course only slight improvement since all cases still need to be listed explicitly. But it is easy to define custom predicate:
public static <T extends Comparable<T>> Predicate<T> isInRange(T lower, T upper) {
return x -> x.compareTo(lower) >= 0 && x.compareTo(upper) <= 0;
}
Match(variable).of(
Case($(isInRange(5, 100)), () -> doSomething()),
Case($(), () -> handleCatchAllCase())
);
Match is an expression so here it returns something like Runnable instance instead of invoking methods directly. After match is performed Runnable can be executed.
For further details please see official documentation.
One alternative instead of using hard-coded values could be using range mappings on the the switch statement instead:
private static final int RANGE_5_100 = 1;
private static final int RANGE_101_1000 = 2;
private static final int RANGE_1001_10000 = 3;
public boolean handleRanges(int n) {
int rangeCode = getRangeCode(n);
switch (rangeCode) {
case RANGE_5_100: // doSomething();
case RANGE_101_1000: // doSomething();
case RANGE_1001_10000: // doSomething();
default: // invalid range
}
}
private int getRangeCode(int n) {
if (n >= 5 && n <= 100) {
return RANGE_5_100;
} else if (n >= 101 && n <= 1000) {
return RANGE_101_1000;
} else if (n >= 1001 && n <= 10000) {
return RANGE_1001_10000;
}
return -1;
}
for alternative you can use as below:
if (variable >= 5 && variable <= 100) {
doSomething();
}
or the following code also works
switch (variable)
{
case 5:
case 6:
etc.
case 100:
doSomething();
break;
}
I found a solution to this problem... We can use multiple conditions in switch cases in java.. but it require multiple switch cases..
public class MultiCSwitchTest {
public static void main(String[] args) {
int i = 209;
int a = 0;
switch (a = (i>=1 && i<=100) ? 1 : a){
case 1:
System.out.println ("The Number is Between 1 to 100 ==> " + i);
break;
default:
switch (a = (i>100 && i<=200) ? 2 : a) {
case 2:
System.out.println("This Number is Between 101 to 200 ==> " + i);
break;
default:
switch (a = (i>200 && i<=300) ? 3 : a) {
case 3:
System.out.println("This Number is Between 201 to 300 ==> " + i);
break;
default:
// You can make as many conditions as you want;
break;
}
}
}
}
}