Запись файлов в Java, изменение регистра и числа * ИСПРАВЛЕНО * - PullRequest
0 голосов
/ 16 октября 2018

Я пишу программу, которая импортирует текстовый файл и создает выходной файл, выполнив следующие действия:

  • Обратный регистр всех букв в input.txt и отображение в output.txt.
  • Цифры будут отображаться в виде списка слов, разделенных дефисом, для цифр в номере (например, 123 = один - два - три).
  • Также на консоли должен отображаться номер строки..

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

Я не могу понять преобразование Strings в char с 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();
  }
}

Извините, на это сложно смотреть!Мне просто нужно руководство!Любая помощь очень ценится.


РЕДАКТИРОВАТЬ

Я исправил свой код и получил его работать.Здесь проблема решена.

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

открытый класс Lab09 {public static void main (String [] args) выдает FileNotFoundException, IOException {String input;String altInput;int lineCount = 0;PrintWriter outFile = new PrintWriter ("output.txt");Сканер inFile = новый сканер (новый файл ("input.txt"));

    while (inFile.hasNextLine()) {
        input = inFile.nextLine();
        lineCount++;
        altInput = "";
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c >= 'A' && c <= 'Z')
                altInput = altInput + ((char) (c + 32));
            else if (c >= 'a' && c <= 'z')
                altInput = altInput + ((char) (c - 32));
            else if (c >= '0' && c <= '9') {
                switch (c) {
                case '0':
                    altInput += "zero";
                    break;
                case '1':
                    altInput += "one";
                    break;
                case '2':
                    altInput += "two";
                    break;
                case '3':
                    altInput += "three";
                    break;
                case '4':
                    altInput += "four";
                    break;
                case '5':
                    altInput += "five";
                    break;
                case '6':
                    altInput += "six";
                    break;
                case '7':
                    altInput += "seven";
                    break;
                case '8':
                    altInput += "eight";
                    break;
                case '9':
                    altInput += "nine";
                    break;
                }
                if (i < input.length() - 1 && (input.charAt(i + 1) >= '0' && input.charAt(i + 1) <= '9'))
                    altInput += "-";
            } else
                altInput = altInput + input.charAt(i);
        }
        outFile.println(altInput);
        System.out.println(altInput);
    }
    inFile.close();
    outFile.close();

}

}

1 Ответ

0 голосов
/ 16 октября 2018

Иметь массив для каждого числа

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

, а затем проверить, является ли символ числом, и, если это так, вычесть ascii из '0'

char c = '2';

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