Reputation: 226
Scanner kb=new Scanner(System.in);
System.out.println("\nDo you want to continue");
char answer=kb.next().charAt(0);
if(Character.toUpperCase(answer)=='Y') {
System.out.println("\nType any message to get Value");
String input=kb.nextLine();
class2 obj=new class2(input);
System.out.println("\n"+obj.getValue());
}
My program is not passing input to class2
, it's just executing my method with empty input. I just tried every method, but none are working.
Upvotes: 1
Views: 125
Reputation: 2751
You have two options:
1) make char answer=kb.nextLine().charAt(0);
2) make String input=kb.next();
Option 1: If you make it nextLine()
it will consume the whole line and moves the cursor to next line. Thus there is no remaining string to be consumed.
Option 2: next()
only consumes line till it finds a space
and also it does not advances cursor to the next line. Thus for the first input if you type "yopo"
the nextLine()
will consume the remaining blank
and you will not get anything.
In your case you should prefer the 1st option.
Upvotes: 1
Reputation: 152
This will be solved by changing
char answer = kb.next().charAt(0);
to
char answer = kb.nextLine().charAt(0);
This is the solution because the next() method in Java does not advance the Scanner to the next line while nextLine() does.
Upvotes: 1