import java.util.Scanner;
public class ShoutandWhisper {
public static void main(String[] args)
{
//defining the variables
String word, word1;
//Input
Scanner kb = new Scanner(System.in);
System.out.print("Give me a word that has 7 letters > ");
word = kb.nextLine();
word1 = word.toUpperCase();
System.out.println("I shout " + word1 + " when I'm excited, but i whisper " + word + " when i can't disturb the neigbours.");
char achar = word.charAt(0);
char bchar = word.charAt(1);
char cchar = word.charAt(2);
char dchar = word.charAt(3);
char echar = word.charAt(4);
char fchar = word.charAt(5);
char gchar = word.charAt(6);
//Changing to uppercase
char Bchar = Character.toUpperCase(bchar);
char Dchar = Character.toUpperCase(dchar);
char Fchar = Character.toUpperCase(fchar);
System.out.println("And the mixed up word is " + achar+Bchar+cchar+Dchar+echar+Fchar+gchar);
}
}
现在代码确实可以工作,但是是否有更短的方法可以在不使用 For 计数器的情况下生成交替的大写或小写输出?重写整个"new"变量是一个等待发生的事故。尤其是对我来说。
当我逐个字母地选择时,我试图强制它,但我做不到。
主要目标是喊叫或耳语,然后使用第二个字母中交替的大写字母对单词进行排序。
最佳答案
您可以将单词转换为字符数组,并使用 for 循环来交替大小写:
char [] c = word.toLowerCase().toCharArray();
for(int i = 1; i < c.length; i = i+2){
c[i] = Character.toUpperCase(c[i]);
}
然后只需用这个 char 数组构造一个新的 String
(使用构造函数 String(char[] value)
),您就会明白了。
关于java - 纠结于大写或小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20024574/