首页 > 解决方案 > 如何根据索引轮换句子中的每个单词?

问题描述

我正在尝试在新行上读取包含两个句子的输入文件。我必须编写一个代码来将句子中的每个单词旋转到右侧并写入 output.txt 文件。例如,input.txt 文件包含以下内容:

Hello World.
Welcome to java programming.

假设“Hello”的索引为 1。它应该向右旋转一个字符,即oHell。“世界。” 索引为 2,它应该向右旋转 2 个字符,即ldWor。,保持句号(.)的位置

在下一行,索引再次以 1 开头。即索引为 1 的“欢迎”应向右旋转 1 个字符,索引为 2 的“to”应向右旋转 2 个字符,索引为 3 的“java”应旋转向右旋转 3 个字符,索引为 4 的“编程”应向右旋转 4 个字符。

所以,输出应该是:

oHell ldWor.
eWelcom to avaj mingprogram.

到目前为止,我已经设法读取文件并将单词存储在数组列表中。而且,我坚持旋转逻辑。下面是我的代码:

public static void main(String[] args) throws IOException {

        FileInputStream inputFile = new FileInputStream("input.txt");
        FileWriter outputFile = new FileWriter("output.txt");
        Scanner scanner = new Scanner(inputFile);
        //System.out.println("Enter a Sentence");

        while(scanner.hasNextLine()) {
            String str = scanner.nextLine();
            String str1[] = str.split(" ");
            ArrayList<String> words = new ArrayList<String>(Arrays.asList(str1));
            for(int i = 0; i < words.size(); i++) {
                System.out.print((i+1)+":"+words.get(i)+"\n");
                outputFile.write((i+1)+"\t");
                outputFile.write(words.get(i)+"\n");
            }
        }
        inputFile.close();
        outputFile.close();
        scanner.close();
     }

在这里,我只是想将数组列表打印到输出文件,看看我是否能够将它写入文件。

任何人都可以帮忙吗?谢谢。

标签: java

解决方案


如果您使用的是 java 8 或更高版本,这将解决您的问题。

    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;

    public class Test {
        public static void main(String[] args) throws IOException {
            rotate();
        }

        private static void rotate() throws IOException {
            FileInputStream inputFile = new FileInputStream("input.txt");
            FileWriter outputFile = new FileWriter("output.txt");
            Scanner scanner = new Scanner(inputFile);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String last = "";
                if(line.charAt(line.length()-1) == '.'){
                    last = ".";
                    line = line.substring(0,line.length()-1);
                }
                String str[] = line.split(" ");
                outputFile.write(IntStream.range(0, str.length).mapToObj(i -> rotate(str[i], i+1)).collect(Collectors.joining(" ")) +last+ "\n");
            }
            inputFile.close();
            outputFile.close();
            scanner.close();
        }

        private static String rotate(String str, int position) {
            return str.substring(str.length()-position)+str.substring(0,str.length()-position);
        }
    }

推荐阅读