電子書籍の厳選無料作品が豊富!

こんにちは。
javaの勉強をやっているのでですが
思うとおりに進みません。
一文字ずつ小文字なら大文字に大文字なら小文字に変換するといったものです。
途中経過です。
import java.io.*;

class Ex60{
public static void main(String args[])throws IOException{
String str3 ="0";
String output = "0";
String s1 = new String("end");
while(str3.equals(s1) == false ){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

while(str3.equals(s1) == false ){
System.out.print(">");
str3 = br.readLine();
if(str3.equals(s1) == true)
break;

for(int i=0; i<str3.length(); i++){
char c = str3.charAt(i);
if(Character.isLowerCase(c))
output = str3.toUpperCase();
else if(Character.isUpperCase(c))
output= str3.toLowerCase();
}
System.out.println("入力された文字列は" + str3 + "です。");
System.out.println("大文字小文字を変換すると" + output + "です。");
}
}
}
}
/*
実行結果
>abc
入力された文字列はabcです。
大文字小文字を変換するとABCです。
>AbC
入力された文字列はAbCです。
大文字小文字を変換するとabcです。
>AAb
入力された文字列はAAbです。
大文字小文字を変換するとAABです。
*/
条件として一文字が大文字か小文字の判定にはCharacterクラスの
isLowerCase()メソッド、isUpperCase()メソッド
一文字の変換はtoUpperCase()メソッド、toLowerCaseメソッドを使います。
どなたかよろしくおねがいします。

A 回答 (2件)

こんな感じでどうですか?


・変換部分を[convert]メソッドとして分離しました。
・文字列[end]との比較を一箇所にしました。
・[equals]メソッドは真偽を返すので[==][!=]を使った冗長な比較をなくしました。

public class Ex60 {
 public static String convert(String str) {
  char[] ca = str.toCharArray();
  for (int i = 0; i < ca.length; i++) {
   if (Character.isLowerCase(ca[i]))
    ca[i] = Character.toUpperCase(ca[i]);
   else
    ca[i] = Character.toLowerCase(ca[i]);
  }
  return new String(ca);
 }
 
 public static void main(String[] args) {
  while (true) {
   try {
    System.out.print(">");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String input = br.readLine();

    if(input.equals("end")){
     break;
    }
    else{
     String output = convert(input);
     System.out.println("入力された文字列は" + input + "です。");
     System.out.println("大文字小文字を変換すると" + output + "です。");
    }
   } catch (IOException e) {
    e.printStackTrace();
    break;
   }
  }
 }
}
    • good
    • 0

class Ex60{


public static void main(String args[])throws IOException{
String str3 ="";
String output = "";
String s1 = new String("end");
while(str3.equals(s1) == false ){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

while(str3.equals(s1) == false ){
System.out.print(">");
str3 = br.readLine();
if(str3.equals(s1) == true)
break;

for(int i=0; i<str3.length(); i++){
char c = str3.charAt(i);
if(Character.isLowerCase(c)){
String CC=String.valueOf(c); //char>String
output = output+CC.toUpperCase();
}
else if(Character.isUpperCase(c)){
String CC=String.valueOf(c); //char>String
output= output+CC.toLowerCase();
}
}
System.out.println("入力された文字列は" + str3 + "です。");
System.out.println("大文字小文字を変換すると" + output + "です。");
output="";//初期化

}
}
}
}
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!