java switch case question - java

public String sizeOfSupermarket() {
String size;
switch (this.numberOfProducts) {
case (this.numberOfProducts > 5000):
size = "Large";
break;
case (this.numberOfProducts > 2000 && this.numberOfProducts < 5000):
size = "Medium";
break;
case (this.numberOfProducts < 2000):
size = "Small";
break;
}
return size;
}
the above is wrong, how to write the compare statement in case statement?

You can use a derived value, in this case look at the number of thousands.
public String sizeOfSupermarket() {
switch (this.numberOfProducts/1000) {
case 0: case 1: return "Small";
case 2: case 3: case 4: return "Medium";
default: return "Large";
}
}
Note: you have a bug in your code such that if the numberOfProducts is exactly 2000 or 5000, it will return null (assuming it compiled)

You can't use expressions in case statements. The condition is evaluated by the switch statement, and the case statements check if the result matches.
To do what you are trying to do, you will have to use a series of if and else if statements:
if(this.numberOfProducts > 5000) {
size = "Large";
}
else if(this.numberOfProducts > 2000 && this.numberOfProducts < 5000) {
size = "Medium";
}
else {
size = "Small";
}

if (numberOfProducts >= 5000)
size = "Large";
else if (numberOfProducts >= 2000)
size = "Medium";
else
size = "Small";

You cannot use switch to test for boolean expressions. You need to use if.
You can use switch if you want to check if a variable has one certain value, i.e.:
public String sizeOfSupermarket() {
String size;
switch (this.numberOfProducts) {
case 5000:
size = "Large";
break;
case 2000:
size = "Medium";
break;
case 100):
size = "Small";
break;
}
return size;
}

Java 1.6 does not support a conditional switch statement, your best bet would be to use the if then else control structure

No way. By definition switch/case is based on enumerated types only (int, boolean, long, enum) in all C-like languages I know.
So you have to use if/else structure here:
public String sizeOfSupermarket() {
String size;
if (this.numberOfProducts > 5000) {
size = "Large";
} else if (this.numberOfProducts > 2000 && this.numberOfProducts < 5000) {
size = "Medium";
} else (this.numberOfProducts < 2000) {
size = "Small";
}
return size;
}

Related

Java, class, Boolean, logic mess

So, we were given to code this ScantronGrader for homework, and the specs say that we have to create this class isValid to check to validity of the options that fall into either A, B, C, or D (all uppercase), I first tried switch (error), if-else-if (error); do-while (Oh, I know so wrong and error). I tried for loop first, and the value didn't get incremented.
In its recent rendition, this is my issue. TBH, I don't even know what I am doing anymore.
public static boolean isValid(String inputstr)
{
int x = 0;
do
{
switch (inputstr.charAt(x))
{
case 'A':
case 'B':
case 'C':
case 'D':
return true;
default: return false;
x++;
}
} while (x < inputstr.length());
}
}
The problem with this is that it is not letting me increment the counter. Now, I need to do that, else, how would I shift right? Either way, please HALP.
Not sure if i understood what that method have to do, but if it has to return true only if the string have those letter you can do this:
public static boolean isValid(String inputstr)
{
int x = 0;
boolean bool = true;
do
{
if(!(inputstr.charAt(x) == 'A' || inputstr.charAt(x) == 'B' || inputstr.charAt(x) == 'C' || inputstr.charAt(x) == 'D'))
{
bool = false;
}
x++;
}while (x < inputstr.length());
return bool;
}
Okay, so after some ideas from here (Thank you for reaching out to help), I am toying with this one which seems to work. Just let me know if I am doing anything unnecessary/ useless, or there is a more efficient way to do this, please?
public static boolean isValid(String inputstr) {
int count = 0;
for (int x = 0; x < inputstr.length(); x++) {
switch (inputstr.charAt(x)) {
case 'A':
case 'B':
case 'C':
case 'D':
break;
default: count++;
}
}
if (count == 0) {
return true;
}
else {
return false;
}
}

TimeUnit on floating values

I created method like this, where I have 2 inputs.
first is type (e.g. 'd', 'h')
second is value (e.g. "15", "0.5")
I created function to convert it to minutes like this:
public Float toMinutes(char type, String value) {
Float minutes = 0f;
switch (type) {
case 'd': {
minutes += Integer.parseInt(value) * 1440;
break;
}
case 'h': {
minutes += Float.parseFloat(value) * 60;
break;
}
case 'm': {
minutes += Integer.parseInt(value);
break;
}
default: {
return 0f;
}
}
return minutes;
}
I decided to refactor it, because those multiplication looks "ugly" for me. I found a better solution called TimeUnit.
public Long toMinutes(char type, String value) {
Long minutesCounted = 0l;
TimeUnit tu = TimeUnit.MINUTES;
switch (type) {
case 'd': {
minutesCounted += tu.convert(Long.parseLong(value), TimeUnit.DAYS);
break;
}
case 'h': {
minutesCounted += tu.convert(Long.parseLong(value), TimeUnit.HOURS);
break;
}
case 'm': {
minutesCounted += tu.convert(Long.parseLong(value), TimeUnit.MINUTES);
break;
}
default: {
return 0l;
}
}
return minutesCounted;
}
The problem is that this converter allow only long values, so now it works only on inputs like 15h and it will not work on inputs like 1,5h. Any ideas how to improve my solution to work with floating numbers?
Instead of using magic constants, you could use TimeUnit to figure out the conversion rate for 1 d, h, etc. to minutes like this
public float toMinutes(char type, String value) {
switch (type) {
case 'd':
return Integer.parseInt(value) * TimeUnit.DAYS.toMinutes(1);
case 'h':
return Float.parseFloat(value) * TimeUnit.HOURS.toMinutes(1);
case 'm':
return Integer.parseInt(value);
default:
return 0;
}
}

How to optimize a lot of switch cases?

How could I optimize having a lot of switch cases? Is there some other method to do what I'm attempting to do?
I have a time slider and this slider updates a variable currentTime with the value (1-24) where the current slider is and calls the updateTime() method. In this method I have switch cases for 1 - 24 (only 3 in this example). Instead of making 24 switch cases, could I do this in a much simpler way?
private void updateTime() {
switch (currentTime) {
case 1:
hourlyData = weatherAPI.HourlyReport(1);
setHourlyData();
break;
case 2:
hourlyData = weatherAPI.HourlyReport(2);
setHourlyData();
break;
...
case 24:
hourlyData = weatherAPI.HourlyReport(24);
setHourlyData();
break;
default:
System.out.println("Oops");
break;
}
}
--
public Map HourlyReport(int hour) {
Hourly hourly = new Hourly(fio);
//In case there is no hourly data available
if (hourly.hours() < 0) {
System.out.println("No hourly data.");
} else {
hourlyData.put("Temp", hourly.getHour(hour).temperature()); // Temperature
hourlyData.put("TempFeel", hourly.getHour(hour).apparentTemperature()); // Feel Temperature
hourlyData.put("Humidity", hourly.getHour(hour).humidity()); // Humidity
hourlyData.put("WindSpeed", hourly.getHour(hour).windSpeed()); // Wind Speed
hourlyData.put("Precip", hourly.getHour(hour).precipProbability()); // Precipitation
hourlyData.put("TimeStamp", hourly.getHour(hour).time());// TimeStamp
}
return hourlyData;
}
The use of a switch is not justified in this case. Use a simple if
if (currentTime > 0 && currentTime < 25) {
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
} else {
System.out.println("Oops");
}
I would validate first
private void updateTime() {
if (currentTime < 1 || currentTime > 24)
throw new IllegalStateException("currentTime: " + currentTime);
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
}
You could use a simple if statement to validate currentTime's value and just pass it to weatherAPI.HourlyReport:
private void updateTime() {
if (currentTime >= 1 || currentTime <= 24) {
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
} else{
System.out.println("Oops");
}
}
private boolean isValidHour(){
if (currentTime >= 1 && currentTime <= 24)
return true;
else
return false;
}
private void updateTime() {
if(this.isValidHour())
hourlyData = weatherAPI.HourlyReport(currentTime);
else
System.out.println("Oops");
}

Switch Statement: Execute Code Once

If I have a switch statement testing the value of integer i, how can I execute the same code once?
For example:
switch(i) {
case 0:
if(j == 2) {
booleanA = true;
booleanB = false;
case 1:
if(j == 4) {
booleanA = true;
booleanB = false;
}
With 5 different cases, instead of me having to type out
booleanA = true;
booleanB = false;
five times, is there a way to say if one of the if statements is true, use this block of code? Is that possible?
Thanks!
You can do it without a switch statement...
int[] requiredJ = {2,4};
if (j == requiredJ[i]) {
booleanA = true;
booleanB = false;
}
I can not understand logic behind your code, but may be this can be done ( Like switch hit in cricket !!! :p).
Assign the values to your booleans, and revert in default case.
booleanA = true;
booleanB = false;
// more code blocks
switch(i) {
case 0:
// Process
break;
case 1:
// Process
break;
default :
booleanA = false;
booleanB = true;
}

how to write generics extensions for standart objects in java?

I beginner in Java and I ask tell me some words about Java tradition of writing generic code. I wrote helper class for pushing items into generic sorted collections in code below and I want to know it is accepted? Or I should extends some base class of collections? Or other ways to welcome more in Java?
package com.rkovalev.Helper;
import java.util.Comparator;
import java.util.List;
public abstract class ListExtensions {
public static <T> void addOnCompare(List<T> collection, T item, Comparator<T> comparator) {
synchronized(collection) {
int i = 0;
int size = collection.size();
if (size == 1) {
int diff = comparator.compare(item, collection.get(0));
switch(diff) {
case 1: i++; break;
default: break;
}
} else {
int range = size - 1;
i = size / 2;
int left = 0;
int right = range;
while(true) {
if (i <= 0) { i = 0; break; }
if (i > range) { i = range; break; }
int diff = comparator.compare(item, collection.get(i));
if (diff == 0) break;
else {
if (diff == -1) right = i;
if (diff == 1) left = i;
int near = i + diff;
if (near < 0) { i = 0; break; }
if (near > range) { i = range + 1; break; }
int diff_near = comparator.compare(item, collection.get(near));
if (diff_near == 0) { i = diff_near; break; }
if (diff_near == diff) {
int step = (right-left)/2;
if (step == 0) step = 1;
switch(diff){
case -1:
right = i;
i = i - step; break;
case 1:
left = i;
i = i + step; break;
}
} else if (diff > diff_near) {
i = near; break;
} else { break; }
}
}
}
collection.add(i, item);
}
}
}
If you want to make extra "generic" functionality available for all collection classes, then writing the functionality as a static method in a "helper" class is the right way to go.
Adding the method to a base class of the existing collection classes would not work. It would entail modifying the standard Java class library, and nobody in their right mind would do that. (It is technically possible, but you would be creating a portability nightmare for your code. Not to mention legal issues if you used the trademarked term "Java" in connection with your code.)

Categories

Resources