2014-09-16 10 views
-2

Каждый символ должен переключаться между верхним и нижним регистром. Моя проблема в том, что я не могу заставить ее работать правильно. Это то, что у меня есть до сих пор:java-символы верхнего и нижнего регистра

 oneLine = br.readLine(); 
     while (oneLine != null){ // Until the line is not empty (will be when you reach End of file) 
      System.out.println (oneLine); // Print it in screen 
      bw.write(oneLine); // Write the line in the output file 
      oneLine = br.readLine(); // read the next line 
     } 
     int ch; 
     while ((ch = br.read()) != -1){ 

      if (Character.isUpperCase(ch)){ 
       Character.toLowerCase(ch); 

      } 
      bw.write(ch); 


     } 
+0

и делает этот код работает (т.е. компилировать и запускать без ошибок во время выполнения)? Что это делает? почему вы думаете, что это так? –

+0

'$ tr 'A-Za-z' 'a-zA-Z' < input.txt > output.txt' –

ответ

0

Здесь вы идете. У вас было несколько проблем:

  1. Вы никогда не сохраняли результат переключения символьного символа.
  2. Вам нужно сохранить возвращение строки с каждой строкой
  3. Я разразившийся переключателем случая, чтобы сделать его легче читать

Вот измененный код:

public static void main(String args[]) { 
    String inputfileName = "input.txt"; // A file with some text in it 
    String outputfileName = "output.txt"; // File created by this program 
    String oneLine; 

    try { 
     // Open the input file 
     FileReader fr = new FileReader(inputfileName); 
     BufferedReader br = new BufferedReader(fr); 

     // Create the output file 
     FileWriter fw = new FileWriter(outputfileName); 
     BufferedWriter bw = new BufferedWriter(fw); 

     // Read the first line 
     oneLine = br.readLine(); 
     while (oneLine != null) { // Until the line is not empty (will be when you reach End of file) 
     String switched = switchCase(oneLine); //switch case 
     System.out.println(oneLine + " > "+switched); // Print it in screen 
     bw.write(switched+"\n"); // Write the line in the output file 
     oneLine = br.readLine(); // read the next line 
     } 

     // Close the streams 
     br.close(); 
     bw.close(); 
    } catch (Exception e) { 
     System.err.println("Error: " + e.getMessage()); 
    } 
    } 

    public static String switchCase(String string) { 
    String r = ""; 
    for (char c : string.toCharArray()) { 
     if (Character.isUpperCase(c)) { 
     r += Character.toLowerCase(c); 
     } else { 
     r += Character.toUpperCase(c); 
     } 
    } 
    return r; 
    } 
Смежные вопросы