我希望输入是一个单词中的任意数量的字母,这样我就可以将它们混为一谈,如下所示。我不知道我怎么能有任何数量的信件,他们都可以改为.uppercase和.lowercase请帮忙。我刚刚在一个月前启动了java,我不理解for和while函数。请帮我。 不使用7个字母时的输出是 线程" main"中的例外情况java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:4 在java.lang.String.charAt(未知来源) 在TempCheck.main(TempCheck.java:16) 当输入为"四"
import java.util.*;
public class ShoutAndWhisper {
public static void main(String[] args) {
Scanner kb= new Scanner(System.in);
System.out.println("Now, give me a seven letter word: ");
String word2 = kb.nextLine();
word2 =word2.toUpperCase();
System.out.println("I shout "+word2.toUpperCase()+ " when I’m excited, but I whisper "+ word2.toLowerCase() + " when I can't disturb the neighbours!");
char e1 = word2.charAt(0);
char e2 = word2.charAt(1);
char e3 = word2.charAt(2);
char e4 = word2.charAt(3);
char e5 = word2.charAt(4);
char e6 = word2.charAt(5);
char e7 = word2.charAt(6);
e1 = Character.toLowerCase(e1);
e2 = Character.toUpperCase(e2);
e3 = Character.toLowerCase(e3);
e4 = Character.toUpperCase(e4);
e5 = Character.toLowerCase(e5);
e6 = Character.toUpperCase(e6);
e7 = Character.toLowerCase(e7);
System.out.println("The word jumbled is: ");
System.out.print(e1);
System.out.print(e2);
System.out.print(e3);
System.out.print(e4);
System.out.print(e5);
System.out.print(e6);
System.out.print(e7);
kb.close();
}
}
答案 0 :(得分:1)
public static void main(String[] args) {
Scanner kb= new Scanner(System.in);
System.out.println("Now, give me a seven letter word: ");
String word2 = kb.nextLine();
word2 = word2.toUpperCase();
System.out.println("I shout "+word2.toUpperCase()+ " when I’m excited, but I whisper "+ word2.toLowerCase() + " when I can't disturb the neighbours!");
char e1;
System.out.println("The word jumbled is: ");
for(int i = 0; i < word2.length(); i++)
{
e1 = word2.charAt(i);
if(i % 2 == 0)
{
System.out.print("" + Character.toUpperCase(e1));
}
else
{
System.out.print("" + Character.toLowerCase(e1));
}
}
kb.close();
}
这将允许您将任何大小的单词作为输入,然后它将遍历单词并将每个其他字符更改为小写或大写。 %2是模块化分区,因此它将返回余数。如果数字是偶数,则如果它是奇数则为0,那么它将不为0.