I am doing a POC on Java 7 new features. I have code to use String in switch statement and it works. I want to make it work in case insensitive also. Is there a way to check out with ignoreCase on String?
package com.java.j7;
public class Test {
final private String _NEW ="NEW";
final private String _PENDING = "PENDING";
final private String _CLOSED = "CLOSED";
final private String _REJECTED ="REJECTED";
public static void main(String... strings){
Test j = new Test();
j.processItem("new");
j.processItem("pending");
j.processItem("closed");
j.processItem("rejected");
}
void processItem(String s){
switch (s) {
case _NEW:
System.out.println("Matched to new");
break;
case _PENDING:
System.out.println("Matched to pending");
break;
case _CLOSED:
System.out.println("Matched to closed");
break;
case _REJECTED:
System.out.println("Matched to rejected");
break;
default:
System.out.println("Not matching any more");
break;
}
}
}
no, but you could switch on s.toUpperCase(). so:
switch (s.toUpperCase()) {
//same as before
}
and while we're nitpicking, you better upper-case things in the english locale to avoid issues with turkish
using String in switch Example from oracle docs Using Strings in switch Statements
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
From oracle docs switch with string
The String in the switch expression is compared with the expressions associated with each case label as if the String#equals method were being used.
You can use
switch(s.toUpperCase()){
...
.....
}
See also
String#toUpperCase
Related
This question already has answers here:
Is calling static methods via an object "bad form"? Why?
(4 answers)
Static method in Java can be accessed using object instance [duplicate]
(5 answers)
Closed 3 years ago.
I am trying to invoke the static Method. What I know is that we have to use the class name to invoke a static method. However, I found that static methods can be invoked even with the help of object.
For example:
public class SwitchStaticMethod {
//static methods can also be called by object
/**
* #param args the command line arguments
*/
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber; }
switch (month.toLowerCase()) {
case "january": monthNumber = 1; break;
case "february": monthNumber = 2; break;
case "march": monthNumber = 3; break;
case "april": monthNumber = 4; break;
case "may": monthNumber = 5; break;
case "june": monthNumber = 6; break;
case "july": monthNumber = 7; break;
case "august": monthNumber = 8; break;
case "september": monthNumber = 9; break;
case "october": monthNumber = 10; break;
case "november": monthNumber = 11; break;
case "december": monthNumber = 12; break;
default: monthNumber = 0; break; }
return monthNumber; }
public static void main(String[] args) {
// TODO code application logic here
String month = "August";
SwitchStaticMethod objSNM = new SwitchStaticMethod();
int returnedMonthNumber = objSNM.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
} // TODO c
}
}
Similarly, I can invoke static method without the help of an object as in the following code:
public class SwitchStaticMethod2 {
/**
* #param args the command line arguments
*/
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber; }
switch (month.toLowerCase()) {
case "january": monthNumber = 1; break;
case "february": monthNumber = 2; break;
case "march": monthNumber = 3; break;
case "april": monthNumber = 4; break;
case "may": monthNumber = 5; break;
case "june": monthNumber = 6; break;
case "july": monthNumber = 7; break;
case "august": monthNumber = 8; break;
case "september": monthNumber = 9; break;
case "october": monthNumber = 10; break;
case "november": monthNumber = 11; break;
case "december": monthNumber = 12; break;
default: monthNumber = 0; break; }
return monthNumber; }
public static void main(String[] args) {
// TODO code application logic here
String month = "August";
//SwitchStaticMethod2 objSNM = new SwitchStaticMethod2();
int returnedMonthNumber = SwitchStaticMethod2.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
} // TODO c
}
}
I feel this is a confusion. Both are giving same answer but which is the correct way of invoking static methods?
It is better to call the static method using the class, just like you did in the second version.
They will both work the same way, but calling a static method from the object will have no gain, since they can't be inherited. It will only cause confusion in the end.
It is always better to invoke static methods by the class name. Why to unnecessarily create an object if your requirement is fulfilled without creating an object.
I fixed my setMonthnum method, but now my input will set the month number to 0, 13, etc. based off of my input. I need to know how to go and ask again for input and not to set my Monthnum to the incorrect input. If you have any suggestions to simply better my code, please feel free to state them! My code is as follows:
import java.util.Scanner;
public class whichMonth {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the month name or number: ");
int monthNumber = input.nextInt();
//set up variable access to the class
AnyMonth inputMonthNumber = new AnyMonth();
// set the month number from user input
inputMonthNumber.setMonthnum.input.nextInt(monthNumber);
// get the month name from user input number
String monthName = inputMonthNumber.getMonthName(monthNumber);
}
}
class AnyMonth {
int Monthnum;
String monthName;
public AnyMonth() {
Monthnum = 1;
}
public AnyMonth(int currentMonthNumber) {
Monthnum = currentMonthNumber;
switch(currentMonthNumber) {
case 1:
Monthnum = 1;
monthName = "January";
System.out.println("January");
break;
case 2:
Monthnum = 2;
monthName = "February";
System.out.println("February");
break;
case 3:
Monthnum = 3;
monthName = "March";
System.out.println("March");
break;
case 4:
Monthnum = 4;
monthName = "April";
System.out.println("April");
break;
case 5:
Monthnum = 5;
monthName = "May";
System.out.println("May");
break;
case 6:
Monthnum = 6;
monthName = "June";
System.out.println("June");
break;
case 7:
Monthnum = 7;
monthName = "July";
System.out.println("July");
break;
case 8:
Monthnum = 8;
monthName = "August";
System.out.println("August");
break;
case 9:
Monthnum = 9;
monthName = "September";
System.out.println("September");
break;
case 10:
Monthnum = 10;
monthName = "October";
System.out.println("October");
break;
case 11:
Monthnum = 11;
monthName = "November";
System.out.println("November");
break;
case 12:
Monthnum = 12;
monthName = "December";
System.out.println("December");
break;
default:
Monthnum = 1;
monthName = "January";
}
}
public AnyMonth(String userMonthName) {
switch(userMonthName) {
case "January":
Monthnum = 1;
monthName = "January";
System.out.println("January");
break;
case "February":
Monthnum = 2;
monthName = "February";
System.out.println("February");
break;
case "March":
Monthnum = 3;
monthName = "March";
System.out.println("March");
break;
case "April":
Monthnum = 4;
monthName = "April";
System.out.println("April");
break;
case "May":
Monthnum = 5;
monthName = "May";
System.out.println("May");
break;
case "June":
Monthnum = 6;
monthName = "June";
System.out.println("June");
break;
case "July":
Monthnum = 7;
monthName = "July";
System.out.println("July");
break;
case "August":
Monthnum = 8;
monthName = "August";
System.out.println("August");
break;
case "September":
Monthnum = 9;
monthName = "September";
System.out.println("September");
break;
case "October":
Monthnum = 10;
monthName = "October";
System.out.println("October");
break;
case "November":
Monthnum = 11;
monthName = "November";
System.out.println("November");
break;
case "December":
Monthnum = 12;
monthName = "December";
System.out.println("December");
break;
default:
Monthnum = 1;
monthName = "January";
}
}
public void setMonthnum (int userMonth) {
Monthnum = userMonth;
if (userMonth < 1 || userMonth > 12){
System.out.println("Invalid input");
this.Monthnum = userMonth;
}
}
public int getMonthnum(int currentMonthNumber) {
Monthnum = currentMonthNumber;
return currentMonthNumber;
}
public String getMonthName(int currentMonthName) {
Monthnum = currentMonthName;
// use swtich-case here instead, default case should return 1/Jan
switch(currentMonthName) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";;
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";
break;
default:
monthName = "January";
}
return monthName;
}
public String toString(String monthNameToString){
monthName = monthNameToString;
return monthNameToString;
}
public boolean equals(int month) {
if (Monthnum == month) {
return true;
}
else {
return false;
}
}
public boolean greaterThan(int month) {
if (Monthnum > month) {
return true;
}
else {
return false;
}
}
public boolean lessThan(int month) {
if (Monthnum < month) {
return true;
}
else {
return false;
}
}
}
change
inputMonthNumber.setMonthnum.input.nextInt(monthNumber);
to
inputMonthNumber.setMonthnum(monthNumber);
Also, in all the getXXX methods, remove the below statement:
Monthnum = currentMonthName;
Getters are desiged to return the value. Setting the values via getter methods is not a good practice. This article explains why getters and setters are needed any how to write them :)
The program is to write a calss PhoneNumber.java
I understand that I am supposed to test if the string is a digit or a letter and then if it is a letter its supposed to be decoded by decode(char c);
However, I dont think char c should be in between the ( ) If any one has suggestions thatd be great thanks!! The toString is left unreturned intentionally because i have not gotten that far in the program yet. Also, have to keep it in the case 'A' format Thanks
public class PhoneNumber {
private int areacode;
private int number;
private int ext;
PhoneNumber() {
areacode = 0;
number = 0;
ext = 0;
}
PhoneNumber(int newnumber) {
areacode = 216;
number = newnumber;
ext = 0;
}
PhoneNumber(int newarea, int newnumber, int newext) {
areacode = newarea;
number = newnumber;
ext = newext;
}
PhoneNumber(String newnumber) {
String areacode = str[0];
String number = str[1];
String[] str = newnumber.split("-");
String[] number = newnumber;
boolean b1, b2;
int i = 0;
int place = 0;
for (int x: newnumber){
newnumber.charAt[i] = place;
b1 = Character.isDigit(place);
if (b1 == true){
number = place;
i++;
} else {
b2 = Character.isLetter(place);
} if (b2 == true) {
number = decode(place);
i++;
} else {
System.out.print("invalid phone number!");
}
}
System.out.print(areacode.concat(number));
return newnumber;
}
private String decode(place) {
switch (c) {
case 'A': case 'B': case 'C': return "2";
case 'D': case 'E': case 'F': return "3";
case 'G': case 'H': case 'I': return "4";
case 'J': case 'K': case 'L': return "5";
case 'M': case 'N': case 'O': return "6";
case 'P': case 'Q': case 'R': case 'S': return "7";
case 'T': case 'U': case 'V': return "8";
case 'W': case 'X': case 'Y': case 'z': return "9";
default: return "";
}
}
public boolean equals(PhoneNumber pn) {
}
public String toString() {
}
}
G:\CIS260\Assignments>javac PhoneNumber.java
PhoneNumber.java:53: error: <identifier> expected
private String decode(place) {
^
1 error
In the constructor, you need to declare the array before you put things in it. You also can't say String[] number = newnumber because number is a String[] and newnumber is a String. equals() and toString() need to return something. And, to answer your question, just say
private String decode(char c){
I have a double split up into an int array, however the problem I am facing, is that I need it to fill in from the back, like this:
int[] arrayA = new int[5];
int[] arrayB = new int[5];
x = 23456.08;
//code here
//what im left with:
arrayA [0,2,3,4,5,6];
arrayB [0,8];
Heres how im cutting up the double:
public static void main(System args[])
{
Scanner input = new Scanner(System.in);
String answer = "";
int count = 0;
int thatone = 0;
int[] splitD = new int[5]; //main num
int[] splitDec = new int[1]; //decimal
//Enter the Number
System.out.print("Enter a number to convert: ");
double num = input.nextDouble();
// convert number to String
String convert = num + "";
// split the number
String[] split = convert.split("\\.");
String firstPart = split[0];
char[] charArray1 = firstPart.toCharArray();
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
// the decimal part
if (split.length > 1)
{
String secondPart = split[1];
char[] charArray2 = secondPart.toCharArray();
splitDec = new int[charArray2.length];
for (int i = 0; i < charArray2.length; i++)
{
// convert char to int
splitDec[i] = Character.getNumericValue(charArray2[i]);
}
}
for(int i =0; i<count;i++)
{
if(i ==0) // x00000.00 or 000x00.00
{
if(splitD[0] != "0")
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else
{
answer+= "";
}
}
else if(i ==1)//this goes with i =2 //0x0000
{
if(splitD[i] == 1)
{
switch (splitD[i+1])
{
case 9: answer+="Nineteen"; break;
case 8: answer+="Eighteen"; break;
case 7: answer+="Seventeen"; break;
case 6: answer+="Sixteen"; break;
case 5: answer+="Fifteen"; break;
case 4: answer+="Fourteen"; break;
case 3: answer+="Thirteen"; break;
case 2: answer+="Twelve"; break;
case 1: answer+="ten"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
thatone = 1;
}
else
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirty"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
}
}
else if(i == 2) //00x000
{
if(thatone ==0)
{
switch (splitD[i])
{
case 9: answer+=" Nine"; break;
case 8: answer+=" Eight"; break;
case 7: answer+=" Seven"; break;
case 6: answer+=" Six"; break;
case 5: answer+=" Five"; break;
case 4: answer+=" Four"; break;
case 3: answer+=" Three"; break;
case 2: answer+=" Two"; break;
case 1: answer+=" One"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
}
else
{
}
}
else if(i ==3)
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else if(i ==4) //0000x0
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirdy"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
answer+= " ";
}
else if(i ==5) //00000x
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
}
}
if(splitDec[0] == 0)
{
answer += " and 00/100 Dollars";
}
else if(splitDec[1] == 0)
{
answer += " and " +splitDec[0] + "0/100 Dollars";
}
else
{
answer += " and " +splitDec[0] +splitDec[1] +" /100 Dollars";
}
System.out.println(answer);
}
}
What should I do to make the array add 0 in the appropriate places?
such as if I typed in 54.00 I would get:
int[] SplitD = {0,0,0,0,5,4};
Thanks!
Instead of re-initializing the array:
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
Use the existing (with length = 5), iterating from the back:
if(charArray1.length > 5) // heavy hard-code, would prefer something better
throw new IllegalArgumentException("Maximum 5 digits, on both decimal sides.");
// watch out of ArrayIndexOutOfBoundsException
for (int i = charArray1.length - 1, j = splitD.length -1 ;
i >=0 && j >=0; i--, j--)
{
// convert char to int
splitD[j] = Character.getNumericValue(charArray1[i]);
count++;
}
Recall, int arrays are filled with zeros, at initialization.
Think creating an array of String, one String for each character (including the decimal point), would be a better approach:
String[] chars = String.valueOf(num).split("(?<=.)");
Job done.
Edit:
To use a switch, don't even split:
for (byte b : String.valueOf(num).getBytes()) {
switch(b) {
case '.':
case '1':
}
}
trying to run the program below but am getting an error when using the switch method
import java.util.Scanner;
/**
*
* #author kern
public class loans {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//variabled decleared
double rate, payment,principal,interest,n;
int length;
String period;
//input
System.out.print("Enter the amount of money borrowed: $");
principal = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
interest = input.nextDouble();
System.out.print("Enter the payment period :");
period = input.next();
System.out.print("Enter Loan Length:");
length = input.nextInt();
//process
rate=interest/100;
payment= principal*(rate*Math.pow((1+rate),n)/ Math.pow ((1+rate),n));
if (period==annually) {
n=1*length;
System.out.prtintf(Your monthly sum is %f:,payment);{
if (period==semiannuall) {
n=2*length;
System.out.prtintf(Your monthly sum is %f:,payment);{
if (period== quarterly) {
n=4*length;
System.out.prtintf(Your quarterly sum is %f:,payment);{
if (period==monthly) {
n=12*length;
System.out.prtintf(Your monthly sum is %f:,payment);{
}
}
String as case value are supported from java 7
See
Switch case
You need to use it like
if("annually".equals(period)){
}
Per Jigar Joshi link you can do strings now:
Using Strings in switch Statements
In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}