문제
이것은 내 이전과 관련이 있습니다 의문
UVA의 편집 단계 사다리를 풀고 온라인 판사가 내 답변을 준수하도록 노력하고 있습니다.
텍스트 파일 읽기 프로그램을 조정하기 위해 readln () 메소드를 사용했습니다.
import java.io.*;
import java.util.*;
class LevenshteinParaElJuez implements Runnable{
static String ReadLn(int maxLength){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte line[] = new byte [maxLength];
int length = 0;
int input = -1;
try{
while (length < maxLength){//Read untill maxlength
input = System.in.read();
if ((input < 0) || (input == '\n')) break; //or untill end of line ninput
line [length++] += input;
}
if ((input < 0) && (length == 0)) return null; // eof
return new String(line, 0, length);
}catch (IOException e){
return null;
}
}
public static void main(String args[]) // entry point from OS
{
LevenshteinParaElJuez myWork = new LevenshteinParaElJuez(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
public void run(){
ArrayList<String> theWords = new ArrayList<String>();
try
{
/// PLACE YOUR JAVA CODE HERE
String leido=LevenshteinParaElJuez.ReadLn(100);
//System.out.println("lo leido fue "+leido);
while (!leido.equals(" ")){
theWords.add(leido);
leido=LevenshteinParaElJuez.ReadLn(100);
}
}catch(Exception e){
System.out.println("El programa genero una excepcion");
}
int maxEdit=0;
int actualEdit=0;
int wordsIndex1 =0, wordsIndex2=0;
while (wordsIndex1<= theWords.size())
{
while (wordsIndex2<= theWords.size()-1){
actualEdit=Levenshtein.computeLevenshteinDistance(theWords.get(wordsIndex1),theWords.get(wordsIndex2));
if (actualEdit>maxEdit){maxEdit=actualEdit;}
wordsIndex2++;
}
wordsIndex1++;
}
System.out.println(maxEdit+1);
}
}
class Levenshtein {
private static int minimum(int a, int b, int c) {
if(a<=b && a<=c)
return a;
if(b<=a && b<=c)
return b;
return c;
}
public static int computeLevenshteinDistance(String str1, String str2) {
return computeLevenshteinDistance(str1.toCharArray(),
str2.toCharArray());
}
private static int computeLevenshteinDistance(char [] str1, char [] str2) {
int [][]distance = new int[str1.length+1][str2.length+1];
for(int i=0;i<=str1.length;i++)
distance[i][0]=i;
for(int j=0;j<=str2.length;j++)
distance[0][j]=j;
for(int i=1;i<=str1.length;i++)
for(int j=1;j<=str2.length;j++)
distance[i][j]= minimum(distance[i-1][j]+1,
distance[i][j-1]+1,
distance[i-1][j-1]+
((str1[i-1]==str2[j-1])?0:1));
return distance[str1.length][str2.length];
}
}
키보드를 통해 작성된 온라인 판사의 입력 전체를 읽어야하지만 위 프로그램을 실행할 때 읽기를 중단 할 수는 없습니다. 그것은 다음과 같습니다.
abc
cba
aba
cca
콘솔 읽기를 중지하지 않고. 이걸 어떻게 되나요 ?? 문제가 내 루프의 조건부에 있다고 생각합니다.
String leido=LevenshteinParaElJuez.ReadLn(100);
//System.out.println("lo leido fue "+leido);
while (!leido.equals(" ")){
theWords.add(leido);
leido=LevenshteinParaElJuez.ReadLn(100);
}
나는 또한 사용했다 :
while (!leido.equals(null)){
theWords.add(leido);
leido=LevenshteinParaElJuez.ReadLn(100);
}
그리고 도착했다.
편집 : 선언은 실제로 다음과 같습니다.
while (leido != null)){
theWords.add(leido);
leido=LevenshteinParaElJuez.ReadLn(100);
}
왜 실패했는지 알지 못합니다. 첫 번째 빈 줄이 입력 될 때 키보드를 통한 입력을 읽는 것이 중지되기를 원합니다.
편집 : Rodion의 답변 덕분에 Readln 메소드가 다음으로 변경되었습니다.
if ((input < 0) || (length == 0)) return null; // eof
대신에:
if ((input < 0) && (length == 0)) return null; // eof
이제 정수 출력을 생성하기 전에 두 개의 빈 공간을 읽고 있습니다. 하나만 읽기 위해 어떻게 변경하려면?
해결책
문제는 널을 반환하는 선에 도달 할 때 입력이 <0이되지 않는다는 것입니다.
while (leido.length() != 0) {
....
}
다른 팁
당신의 문제를 올바르게 이해하는지 확실하지 않습니다. 단지 프로그램이 콘솔에서 읽기를 중단하기를 원한다면 CTRL+D (LINUX) 또는 CTRL+Z (Windows)를 눌러 콘솔을 "닫을"수 있습니다. 이로 인해 System.in.read ()가 -1로 반환되므로 readln 메소드가 NULL을 반환합니다.
Nathaniel이 제안한 것처럼 Null을 확인하십시오.
편집하다: (귀하의 의견에 따라)
문제는 Readln 메소드 에서이 조건에 관한 것입니다.
if ((input < 0) && (length == 0)) return null;
빈 줄을 입력하면 길이는 0이면 입력이> 0이됩니다 (시스템이 새로운 라인을 나타내는 데 사용하는 것은 무엇이든). 당신이 그것을 바꾸면
if ((input < 0) || (length == 0)) return null;
입력 스트림이 닫히거나 빈 줄이 입력되면 메소드가 NULL을 반환합니다.강한 텍스트
대신에 !leido.equals(" ")
, 간단히 사용하십시오 !leido.equals("")
. 전자는 공간 만 포함 된 선이 입력 될 때 종료되고, 후자는 빈 줄이 입력 될 때.
나는 당신의 문제를 많이 이해하지 못하지만 내 옆에서 제안은 이런 식으로 당신의 상태를 사용한다는 것입니다.
while(!" ".equals(leido)){
//instead of
while (!leido.equals(" ")){
변수가 null이 포함되어 있으면 코드가 예외를 던지기 때문에 왜?