Why doesn't the while loop end with an additional "or" condition?
I want the while loop to end when the condition is "index> = maxlength".
The problem is that it just says "Please enter a string." The user enters a line, presses "Enter" and stays on the next line. Anything after the while loop is not executed.
Please Enter a String: *ddddddddddd*
|
If I don't have the "index> = maxlength" condition, the code works fine.
public static int getaline( char message[], int maxlength ) {
int index = 0;
int character = 0;
maxlength = 5;
System.out.print("Please enter a string: ");
character = fgetc(System.in);
while (character != '\n' || index >=maxlength){
message[index] = (char) character;
index++;
character = fgetc(System.in);
}
if (index >= maxlength){
System.out.println("Overflow");
}
System.out.println("The amount of elements in the array is" + index);
return 0;
}
source to share
Why doesn't the while loop end with an additional "or" condition?
Because your test says to continue the loop if index
more maxlength
.
It does what you said, not what you meant. Computers are like this :-)
Is there a way to prevent the user from entering more characters after the maximum length?
It depends what you mean:
-
If you are asking if there is a way to stop accepting characters after reading "max", @JohnKugelman's answer tells you how. (The problem is that characters until the end of the line remain unread ... and if you then try to accept another element from the user, your application will see those characters first. For example, if you called again
getaline
...) -
If you want to ignore characters after reading "max", you need to change the code so that it doesn't stop reading at "max", but it only adds them to
message
ifindex
less than max. -
If you want to prevent the user from entering characters, then there is no easy way to do this. And maybe not at all. (Chances are you don't want to try this because it will lead to various other problems.)
source to share