我有下一个代码,它会打开一个这个文件:
procedure TeTruena is
PI : constant Float := 3.141592;
MAX: constant Int := 30;
type Array is array(1 .. MAX ) de
Int;
type Matrix es array( 1 .. MAX, 1.. MAX )
of Int;
我必须将这个文件中的每个单词分别用于标记:
程序(一个标记),是(另一个标记)等。
并且这段代码应该完成所有这些:
public class Lexic {
public static void main(String[] args) {
int car;
String nameFile,lexem;
Scanner t = new Scanner(System.in);
System.out.print("Give me the name of the file: ");
nameFile = t.nextLine();
t.close();
try
{
File file = new File(nombreArchivo);
RandomAccessFile af = new RandomAccessFile(file,"r");
while((car = af.read()) != -1)
{
if(car != ' ' && car != '\n')
{
lexem = Lexic.readFile(nameFile,af);
System.out.print("["+lexem+"]");
}
}
af.close();
}
catch(IOException ex)
{
System.out.println("Can not open file");
}
}
public static String readFile(String name,RandomAccessFile r)
{
int car;
char c;
long position;
String s = null;
StringBuilder sb = new StringBuilder();
try
{
position = r.getFilePointer();
r.seek(position-1);
car = r.read();
if(specialChar(car))
{
c = (char)car;
sb.append(c);
s = sb.toString();
}
else
{
while((car != -1) && (car != ' ') && (car!= '\n') && (!specialChar(car)))
{
c = (char)car;
sb.append(c);
car = r.read();
s = sb.toString();
}
if(esCaracterEspecial(car))
{
position = r.getFilePointer();
r.seek(position-1);
}
}
}
catch(IOException ex)
{
System.out.println("Can not open file");
}
return s;
}
public static boolean specialChar(int car){
char character[] ={'+','-','*','/','%',';',',','{','}','(',')','=','<','>',':'};
for(int i = 0;i < character.length;i++){
if(car == character[i])
return true;
}
return false;
}
但问题是代码并没有忽略&#39; \ n&#39;并打印出来:
[程序] [TeTruena] [是 ]
为什么会这样?
答案 0 :(得分:0)
当输入文件使用Unix字符返回(\ n)时,您的代码按预期工作。
我怀疑你正在使用Windows输入,所以请调整此行:
while ((car != -1) && (car != ' ') && (car != '\n') && (!specialChar(car))) {
到此:
while ((car != -1) && (car != ' ') && (car != '\n') && (car != '\r') && (!specialChar(car))) {
它会起作用。