[英]Java 7 Issue reading character by character
I need to be able to manipulate each character in a string. 我需要能够操纵字符串中的每个字符。 Could someone tell me what I'm doing wrong here? 有人可以告诉我我在做什么错吗?
import java.io.*;
public class encryptedWrite {
public static void main(String[] args) {
try {
File file = new File("code.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
BufferedReader read
= new BufferedReader(new InputStreamReader(System.in));
int charNumber = 0;
String content = read.readLine();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String numberString = charNumber + "";
String modCont = content.charAt(numberString);
while (!(modCont.equals("#"))) {
bw.write(modCont);
charNumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I need to be able to output each character of content to code.txt. 我需要能够将内容的每个字符输出到code.txt。
There are a couple issues that I see. 我看到几个问题。 First, charAt takes a numeric argument, not a String argument. 首先,charAt需要一个数字参数,而不是String参数。 Second, you need to read inside the loop, not outside. 其次,您需要在循环内部而不是外部阅读。 I would replace: 我将替换为:
String modCont = content.charAt(numberString);
while (!(modCont.equals("#"))) {
bw.write(modCont);
charNumber++;
}
with 同
while (true) {
String modCont = (String) content.charAt(charNumber);
if (modCont.equals("#")) {
break;
}
bw.write(modCont);
charNumber++;
}
String的类方法:charAt()以int作为参数,您正在传递String对象作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.