java 菜鸟求助 这题怎么做?

如题所述

你好提问者:

若解决了你的问题,请采纳,若有疑问请追问,谢谢!

public class Work3_b {
public static void main(String[] args) {
int num1,num2,num3;
num1=0;
num2=0;
num3=0;
char ch ='A';
switch (ch) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
num1++;
break;
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
num2++;
break;

default:
num2++;
break;
}
System.out.println("num1="+num1+"  num2="+num2+"  num3="+num3);
}

}

结果:
num1=1  num2=0  num3=0

追问

我想String a ="乱打一串字母",然后用switch语句判断这串字母里面有多少个num123,要怎么写呢

追答

其实我没太明白你追问的问题。我根据自己的理解写了段代码,你看下:
package com.gc.action.baiduTest;

public class ChaXunZiMu {

public static void main(String[] args) {

String str="asdfghjkl_num123_qwertyuiop_num123";
int count=0;
String str1="num123";

while (str.contains(str1)) {//判断字符串中是否存在子串
System.out.println("存在字符串");
int number = str.indexOf(str1); //字串首次出现的位置
System.out.println("首次出现的位置"+number);
count++;
str = str.substring(number+str1.length(), str.length());//截取剩余字符串
}
System.out.println("字串出现了"+count+"次");
}

}
结果:
存在字符串
首次出现的位置10
存在字符串
首次出现的位置12
字串出现了2次

如果你非得用switch的话。只能是写多余代码了:
package com.gc.action.baiduTest;

public class ChaXunZiMu {

public static void main(String[] args) {

String str="asdfghjkl_num123_qwertyuiop_num123";
int count=0;
String str1="num123";
while (str.contains(str1)) {//判断字符串中是否存在子串
System.out.println("存在字符串");
int number = str.indexOf(str1); //字串首次出现的位置
System.out.println("首次出现的位置"+number);
switch (str1) {
case "num123":
count++;
break;

default:
break;
}
str = str.substring(number+str1.length(), str.length());//截取剩余字符串
}
System.out.println("字串出现了"+count+"次");
}

}

追问

.....我偷懒了,我写详细点
String a ="乱打一串字母",然后用switch语句判断这串字母里面有多少个大写元音(AEIOU,用num1表示)、小写元音(aeiou,用num2表示)、其他(用num3表示),要怎么写呢

追答

package com.gc.action.baiduTest;

public class Work3_b {

public static void main(String[] args) {

int num1,num2,num3;
num1=0;
num2=0;
num3=0;
String str ="AEIOU_aeiou_123";//qwertyuiop_ASDFGHJKL_zxcvbnm
char[] ch = new char[str.length()] ;
for (int i = 0; i < str.length(); i++) {
String s=str.substring(i, i+1);
System.out.println("字母是:"+s);
ch[i]=s.charAt(0);
System.out.println("数组字母是:"+ch[i]);
}
for(int i=0;i<ch.length;i++ ){
switch (ch[i]) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
num1++;
break;
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
num2++;
break;

default:
num3++;
break;
}
}
System.out.println("num1="+num1+" num2="+num2+" num3="+num3);
}

}
结果:
字母是:A
数组字母是:A
字母是:E
数组字母是:E
字母是:I
数组字母是:I
字母是:O
数组字母是:O
字母是:U
数组字母是:U
字母是:_
数组字母是:_
字母是:a
数组字母是:a
字母是:e
数组字母是:e
字母是:i
数组字母是:i
字母是:o
数组字母是:o
字母是:u
数组字母是:u
字母是:_
数组字母是:_
字母是:1
数组字母是:1
字母是:2
数组字母是:2
字母是:3
数组字母是:3
num1=5 num2=5 num3=5

赚你这十财富值,真不容易。。。

追问

char[] ch = new char[str.length()] ;String s=str.substring(i, i+1);

ch[i]=s.charAt(0);这3行代码什么意思啊,没学过。我只知道str.length()和s.charAt(0)的意思,其他的不会

追答

char[] ch = new char[str.length()] ;//定义字符数组,长度是字符串的长度。 String s=str.substring(i, i+1); //循环截取字符串中的每一个字符,赋值给s; ch[i]=s.charAt(0);//将字符串转换成字符,分别放入对应的字符数组中。

温馨提示:答案为网友推荐,仅供参考
相似回答