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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在代码确实有效,但是有一种更简单的方法可以在不使用For计数器的情况下生成交替的大写或小写输出吗?重写整个"更新"的变量是一个等待发生的事故.特别是对我.
我试图强迫它,因为我正在逐字逐句地选择,我无法做到.
主要目标是呼喊或低语,然后使用第二个字母的交替大写字母对单词进行排序.
您可以将单词转换为char数组,并使用for循环来交替大写和小写:
char [] c = word.toLowerCase().toCharArray();
for(int i = 1; i < c.length; i = i+2){
c[i] = Character.toUpperCase(c[i]);
}
Run Code Online (Sandbox Code Playgroud)
然后String用这个char数组构造一个new (使用构造函数String(char[] value)),你就会得到你的话.
| 归档时间: |
|
| 查看次数: |
320 次 |
| 最近记录: |