java - 如何根据索引轮换句子中的每个单词?
问题描述
我正在尝试在新行上读取包含两个句子的输入文件。我必须编写一个代码来将句子中的每个单词旋转到右侧并写入 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 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);
}
}
推荐阅读
- python - 计算同一列之间的差异,在python中由另一列分组的连续行
- sql-server - 将新行更改为新记录
- assembly - (如果 BYTE PTR [ebp+0x8] 得到一个大于 1 字节的参数会怎样?比如 0xcdc485c1
- python - 使用python和django测试参考值
- reactjs - 使用 react-places-autocomplete 包获取邮政编码
- node.js - 如何使用 Nodejs 部署 Mongodb 数据库
- java - Java - 输入字节在 300 处的结束字节不正确
- typescript - 未找到模块:错误:无法解析“@types/svgo”
- node.js - 查找某人是否在 discord.js 上获得了新角色
- python - 具有特定输出的 Elasticsearch DSL 查询