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);

        }

开始吧。你遇到了一些问题:

  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;
  }

最新更新