Im new at Java Console.
for (i=0;i<=noOfSP;i++)
{
System.out.println("NAME OF THE Plan #" + i + "?: 'Example input: 4GB' ");
nameOfPlan = scn.nextLine();
SubscriptionPlan subscriptionPlan = new SubscriptionPlan(nameOfPlan);
if ( !gsmProvider.addSubscriptionPlan(subscriptionPlan) )
{
System.out.println("Adding Error. Program Will Closing.");
System.exit(1);
}
}
In this codeblock I wanna read name. I read "noOfSP" from user type of Integer. But iteration 0 won't work? If noOfSP is 0, program skips for loop ? Why?
EDIT:
I edited inside the for loop. Okay but still can not read 0. iteration.
NUMBER OF SUBSCRIPTION PLANS ? : 'Example input: 1'
1
NAME OF THE Plan #0?: 'Example input: 4GB'
NAME OF THE Plan #1?: 'Example input: 4GB'
The 0. iteration is skipped ? Why?
Here is your solution. Change
nameOfPlan = scn.nextLine();
To
nameOfPlan = new Scanner(System.in).nextLine();
Why?
When you input any value and hit enter, a new-line character will be appended to the end of your input. in your case, when you press enter for the noOfSP value, a new-line character (/n) was appended by default.
Since you have use scn.nextInt() for noOfSP value (most probably), its only fetch the int, and there is still new-line characters (\n) left.
your first for loop iteration (iteration 0) fetch the \n thus, skip the scn.nextLine() in first iteration .
Note: you can also fix this by adding scn.nextLine(); just before your for loop:
....
scn.nextLine();
for (i=0;i<=noOfSP;i++){
.....
As for loop says i value should be less than noOfSP, that's why it skips the loop.
Change for loop to
for (i=0;i<=noOfSP;i++)
if i=0 and noOfSP is 0 at start, (0<0) will return false
use this instead:
for(i=0; i<=noOfSP;i++)
Related
In the following code from "Java: A Beginner's guide", the for loop seems to iterate more than once when a single character is typed, even though the loop control variable, i, should only be incremented by one each iteration.
The condition to enter the for loop is based on user input. The program will enter the loop and increment i by one until the character S is typed by the user. Every time the program enters the loop, i is printed out.
class ForTest {
public static void main(String args[])
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for(i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
So it is expected that when a character other than S is typed, the program prints out Pass #0 and then waits for the user to input the next character. Oddly, it loops thrice, printing Pass #0 Pass #1 and Pass #2 before asking for user to input the next character.
Expected:
a
Pass #0
b
Pass #1
S
Actual:
a
Pass #0
Pass #1
Pass #2
b
Pass #3
Pass #4
Pass #5
S
If you change a little the program in order to debug it:
char myChar;
for(i = 0; (myChar = (char) System.in.read()) != 'S'; i++)
System.out.println("Pass #" + i + " the character from the console is: " + (byte)myChar);
}
and then run it, you will see what characters are actually comming from the input stream:
Press S to stop.
Pass #0 the character from the console is: 97
Pass #1 the character from the console is: 10
Pass #2 the character from the console is: 98
Pass #3 the character from the console is: 10
97 - is a
10 - is line feed
98 - is b
10 - is line feed
I hope it is clear now to you - if you press a + Enter, then the console returns a + line feed characters to the program, that is two characters, not one.
in for loop it cheaks the condition first and if it is true then it executes the further code i recommend you to use do while loop because it executes the code first and then it cheaks the code
I'm fairly new at java and have a current assignment to take a given word, put the first word at the end, rebuild the word from reverse, and see if it's the same word as the original, such as: grammar, potato, uneven, dresser, banana etc. So far I have this:
Scanner input = new Scanner(System.in);
String original, reverse = "";
String exit = "quit";
int index;
System.out.println("Please enter a word (enter quit to exit the program): ");
original = input.next();
while (!original.equalsIgnoreCase(exit))
{
String endingChar = original.substring(0, 1);
String addingPhrase = original.substring(1);
reverse += endingChar;
for (index = addingPhrase.length() - 1; index >= 0; --index)
{
char ch = addingPhrase.charAt(index);
reverse += ch;
}
if (original.equals(reverse))
{
System.out.println("Success! The word you entered does have the gramatic property.");
}
else
{
System.out.println("The word you entered does not have the gramatic property."
+ " Please try again with another word (enter quit to exit the program): ");
}
original = input.next();
}
input.close();
When I run it and enter the word "banana," it properly recognizes that it is indeed the same backwards when the b is moved to the end, and does the same with the other words listed above, but when I enter a second word on the loop, it never recognizes it properly, and always responds with the print statement from the else block:
Please enter a word (enter quit to exit the program):
banana
Success! The word you entered does have the gramatic property.
banana
The word you entered does not have the gramatic property. Please try again
with another word (enter quit to exit the program):
I'm guessing it's something to do with either the way I made my for loop, or the way I asked for input at the end of the while loop, but like I said I'm fairly new and awful at debugging. Any help would be much appreciated, thanks a lot in advance.
You are changing string reverse in every iteration, but you are not clearing it. So before the end of the loop or at the beginning clear the string for example like so: reverse = "", and then it should be fine.
Just add reverse = ""; in the end of the while loop in order to set the variable reverse to its original state, i.e. empty string
Snippet of the code
while(!((input = sc.nextLine()) != null)) {
sc = new Scanner(input).useDelimiter(" ");
while (sc.hasNextLine()) {
in[index] = sc.next();
index++;
}
if (index < 3 || !in[0].equals("ping")) {
throw new IllegalArgumentException(
"Usage ping <destination> <port number missing> . . . ."
+ in[0] + " " + in[1] + " " + in[2]);
}
}
I want to keep reading user inputs but after the first iteration, i get no new line found. Scanner does not wait for the user input but rather advances on.
Thanks
Your top-level while loop is doing the opposite of what you want. First it sets input equal to sc.nextLine(), which is good. Then input is compared to null. If this comparison yields true, then you have input, which means that the loop should continue. However, you are then negating the result of that comparison, which makes the loop terminate when there is input.
Remove the exclamation point, and you should be good.
EDIT
On second thought, your inner while loop is exiting when sc.hasNextLine() returns false. After that, you will go through the conditional statement and return to the top. Since sc.hasNextLine() already returned false, of course sc.nextLine() will return null. The input has already ended in the inner loop, so the outer loop will exit as well.
I've been writing this program to count the vowels in string/a line of strings. Now, I've got the whole program worked out and it does correctly output the number of vowels for all inputs, but the problem is that the first input of the array is always 0 / nonexistant for some reason.
I'll give you an example and the code here, it's kind of hard to explain:
Scanner sc = new Scanner(System.in);
int numberOfEntries = sc.nextInt() //this would be the number of lines of strings
String[] array = new String[numberOfEntries];
int k = 0;
while(sc.hasNext() && k < numberOfEntries){
array[k] = sc.nextLine();
k++;
}
So this is the part of the code that is relevant to the problem, the rest of it is fine. For some reason, when I input the following lines:
5
abcd
efgh
ijkl
mnop
qrst
The output I will get if I outprint the array is this:
[, abcd, efgh, ijkl, mnop]
I've tried using just the
for(int i = 0; i < array.length; i++){
array[i] = sc.nextLine();
}
thinking that it might solve the issue but nothing changed. I am out of ideas now, though I am sure I just made some silly little error somewhere and I just don't see it.
Kind regards, George
You get the empty line because of the '\n' that sits in the buffer after you call nextInt(). You press Enter after typing in your integer. Scanner consumes the integer in the call of nextInt(), but it does not touch '\n' that follows.
To fix this problem, call nextLine after reading your int, and discard the result:
int numberOfEntries = sc.nextInt();
sc.nextLine(); // Throw away the '\n' after the int
The statement int numberOfEntries = sc.nextInt(); reads the number, leaving the next character (a newline) as the next character to be read.
The first call to sc.nextLine() see this newline and recognizes it as the end on an (empty) line. For your sample input, this causes the call to return an empty string.
The solution is to add an extra call to sc.nextLine() after the sc.nextInt() to consume (and then discard) any characters after the last digit up to the end of the line.
(Actually ... this is a fairly common beginner's mistake with the Scanner API.)
Thats because the Scanner.nextInt() method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine().
I want the while loop to end when the condition "index >=maxlength".
The problem is it just says "Please Enter a String". The user enters a string, clicks "Enter" and it just stays there on the next line. Anything after the while loop does not get executed.
Please Enter a String: *ddddddddddd*
|
If I do not have the condition "index >=maxlength", 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;
}
If you want the loop to end when the index is greater than or equal to maxlength then you need the condition to be the opposite: it should loop while the index is not greater than or equal to maxlength.
while (character != '\n' && index < maxlength)
Why doesn't the while loop end with the extra “or” condition?
Because your test says to continue looping if index is greater than maxlength.
It is doing what you said, not what you meant. Computers are like that :-)
Is there a way to not allow the user to input any more characters after the max length?
It depends what you mean:
If you are asking if there is a way to stop accepting characters after "max" have been read, the #JohnKugelman's answer says how. (The problem is that the characters up to the end of line remain unread ... and if you then attempt to accept another item from the user, your application will see those characters first. For example, if you called getaline again ...)
If you want to ignore characters after "max" have been read, then you need to change the code so that it doesn't stop reading at "max", but it only adds them to message if index is less than the max.
If you want to stop the user from entering the characters, then there is no easy way to do it. And maybe, no way at all. (You most likely do not want to try to do this because it will introduce various other problems.)