首页 > 解决方案 > 用java写文件,改变大小写和数字

问题描述

我正在编写一个导入文本文件并通过执行以下操作创建输出文件的程序:

input.txt 如下:

Here is A TEXT
File To Be
Processed FOR Lab09.
There are now 3459 ways to
DESIGN this kind of PROGRAM.
Here's hoping you can figure OUT 1, 2,
or 3 of these designs -
Or AT LEAST come close, even if
you don't find all 3459

我无法弄清楚Stringstochar与 a的转换以FileReader正确打印到控制台和文件。对这个新编码器的任何帮助将不胜感激。

import java.io.*;
import java.util.*;

/**
 * CSC110 Java 10am Lab09 Reading
 *
 * Writing Files file will create output file of the text formatted a certain way.
 */
public class Lab09 {

  public static void main(String[] args) throws FileNotFoundException, IOException {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter name of file: ");
    String fileName = input.next();
    System.out.println();

    Scanner fileInput = new Scanner(new File(fileName));
    FileWriter fw = new FileWriter("output.txt");
    PrintWriter pw = new PrintWriter(fw);

    while (fileInput.hasNext()) {
      char c = fileInput.next().charAt(0);
      String numberToWord = "";
      pw.println(fileInput.nextLine().toUpperCase());

      if (Character.isLowerCase(c)) {
        System.out.println(fileInput.nextLine().toUpperCase());
        pw.println(fileInput.nextLine().toUpperCase());
      } else if (Character.isUpperCase(c)) {
        System.out.println(fileInput.nextLine().toLowerCase());

        if (Character.isDigit(c)) {
          switch (c) {
            case '1':
              numberToWord = numberToWord + "one";
              pw.println(fileInput.next(numberToWord));
              System.out.println(numberToWord);
              break;

            case '2':
              numberToWord = numberToWord + "two";
              pw.println(fileInput.next(numberToWord));
              System.out.println(numberToWord);
              break;

            case '3':
              numberToWord = numberToWord + "three";
              pw.println(fileInput.next(numberToWord));
              System.out.println(numberToWord);
              break;

            case '4':
              numberToWord = numberToWord + "four";
              pw.println(fileInput.next(numberToWord));
              System.out.println(numberToWord);
              break;

            case '5':
              numberToWord = numberToWord + "five";
              pw.println(fileInput.next(numberToWord));
              System.out.println(numberToWord);
              break;

            case '6':
              numberToWord = numberToWord + "six";
              pw.println(fileInput.next(numberToWord));
              System.out.println(numberToWord);
              break;
          }
        }
      }
    }

    pw.close();
    fileInput.close();
  }
}

对不起,它很难看!我只是需要一些指导!任何帮助是极大的赞赏。

标签: javajava-io

解决方案


每个数字都有一个数组

String nums [] = {"zero", "one", "two"};  // etc

然后测试char是否为数字,如果是则减去'0'的ascii

char c = '2';

if (c >= '0' && c <= '9') {
    int index = c - '0';
    System.out.println(nums [index]);
}

推荐阅读