I am trying to write a program that finds the longest line of text that the user provides. However, it does not work properly; it gives the last entered array with the first letter missing.
import java.io.*;
public class longestNoCopy{
static final int MAXLINE = 100;
public static void main(String[] args) throws IOException{
int len;
int max;
char line[] = new char[MAXLINE];
char longest[] = new char[MAXLINE];
max=0;
while((len=getLine(line,MAXLINE))>0){
System.out.printf("len: %d\n", len);
if(len>max){
// System.out.println("New record");
max=len;
longest=line;
}
/* System.out.print("\nLine: ");
for(int i=0;line[i]!=0;i++)
System.out.print(line[i]);*/
System.out.println("Longest line so far:");
for(int i=0;longest[i]!=0;i++)
System.out.print(longest[i]);
}
if(max>0){
System.out.printf("Longest line:\n");
int i;
for(i=0;i<longest.length;i++)
System.out.print(longest[i]);
System.out.printf("\ni: %d, Length: %d\n", i, max);
}
}
static int getLine(char s[], int lim) throws IOException{
InputStreamReader r = new InputStreamReader(System.in);
int c = 0, i = 0;
for(i=0;i<lim-1&&(c=r.read())!=-1&&c!='\n';++i){
s[i]=(char)c;
// System.out.printf("s[%d]: %c\n", i, s[i]);
}
if(c=='\n'){
s[i]=(char)c;
++i;
}
// System.out.printf("i: %d\n", i);
s[i]='\0';
return i;
}
}
I commented out some print statements so you have the choice of activating them. If I enter:
Hi
my
name
is
It says: Longest line: s
Whereas the longest line should be: name By the way, I am running on the Ubuntu command line and use Ctrl+D to quit. I know a lot of the code is weird; I took some C code and tried to change it until it became a Java program to compare the two languages. Why is this error happening? To emphasize, I know this is not the usual way to do things in Java, I know about the Scanner class, etc. I am not using this code for a real application. I just want to know why this error occurs.