Java 在字符串中使用开关
试图在字符串中使用switch,首先将字符串转换为char,然后应用switch,但仍然没有做到……这是我的代码Java 在字符串中使用开关,java,switch-statement,Java,Switch Statement,试图在字符串中使用switch,首先将字符串转换为char,然后应用switch,但仍然没有做到……这是我的代码 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.swing.JOptionPane; class HappyBirthday { public static void main(String[] args)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
class HappyBirthday {
public static void main(String[] args) throws IOException {
String Month;
char[] Months = Month.toCharArray();
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter your month.");
Month = JOptionPane.showInputDialog("enter month");
String month1 = { "January", "feb"};
char[] month2 = month1.toCharArray();
// String s=month1.equals(Month);
// System.out.print(month2Array[0]);
switch (month2) {
case 0:
System.out.println("kool");
break;
case 1:
System.out.println("not kool");
break;
default:
}
}
}
/**
* if (month1[1].equals(Month)) System.out.println("kool"); else
* if(month1[0].equals(Month)) System.out.println("kooooooooooooool"); else
* System.out.println("Big kooooool");
**/
看看这个主题。你不能打开char[]类型。打开char[0]并使用
大小写'J':
等等(尽管-因为有些月份以同一个字母开始,算法可能是次优的)请注意,在Java 7中会打开字符串。目前,您无法打开字符串。语言规范明确说明了您可以打开什么:
表达式的类型必须是char
、byte
、short
、int
、Character
、byte
、short
、Integer
或枚举类型,否则会发生编译时错误
根据您要执行的操作,您可以在字符串的每个字符上切换:
String s = "Coffee, tea, or me?";
int vowelCount = 0;
int punctuationCount = 0;
int otherCount = 0;
for (char letter : s.toUpperCase().toCharArray()) {
switch (letter) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowelCount++;
break;
case ',':
case '.':
case '?':
punctuationCount++;
break;
default:
otherCount++;
}
}
System.out.printf("%d vowels, %d punctuations, %d others",
vowelCount, punctuationCount, otherCount
); // prints "7 vowels, 3 punctuations, 9 others"
我差点就否决了这个问题,因为代码格式是一个desaster!下一次,请在发布之前花一分钟清理一下。(虚拟+1用于skaffman清理;-))使用开关中的字符串是Java7的一部分根据变更日志,此代码已进入代码库。
String s = "Coffee, tea, or me?";
int vowelCount = 0;
int punctuationCount = 0;
int otherCount = 0;
for (char letter : s.toUpperCase().toCharArray()) {
switch (letter) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowelCount++;
break;
case ',':
case '.':
case '?':
punctuationCount++;
break;
default:
otherCount++;
}
}
System.out.printf("%d vowels, %d punctuations, %d others",
vowelCount, punctuationCount, otherCount
); // prints "7 vowels, 3 punctuations, 9 others"