+ 1

I am not getting result as exoected , pls help me .....

Here is code : import java.util.Scanner; public class Main { public static void main(String[] args) { int P; float R; int T ; float SI; System.out.println("Enter Principal"); Scanner newScan = new Scanner(System.in); P= newScan.nextInt() ; System.out.println("Enter Rate"); R=newScan.nextFloat() ; System.out.println("Enter Time"); T= newScan.nextInt(); System.out.println("You Entered P : " + P ); System.out.println("You Entered R : " + R ); System.out.println("You Entered T : " + T ); System.out.println("Is this correct ? Press Y/N"); String UserInput = newScan.nextLine(); String Y = "Y"; String N = "N"; if(Y == UserInput) { System.out.println("Continuing"); SI = P * R * T / 100; System.out.println("The Result is " + SI); }else if (N == UserInput) { System.out.println("You Have chosen to quit"); System.out.println("Quiting.....");} else { System.out.println("You made a wrong choice");} } } . . . This is output Enter Principal 45 Enter Rate 4 Enter Time 3 You Entered P : 45 You Entered R : 4.0 You Entered T : 3 Is this correct ? Press Y/N You made a wrong choice Please Help me

3rd Apr 2020, 6:15 AM
Aamir
Aamir - avatar
8 Antworten
+ 1
Read this, there is your answer. https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/amp/?ref=rp Because you take numbers with nextInt etc, they don't consume the last line feed from system.in So UserInput will be an empty string because the first character it finds is actually a line feed. Solution: before you ask for Y/N insert another nextLine()
3rd Apr 2020, 6:30 AM
Tibor Santa
Tibor Santa - avatar
+ 2
SoloLearn courses teach you only very basic stuff, so it won't be enough for Android development, but it's a good start. 😉
3rd Apr 2020, 7:07 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Always compare objects (non-primitive types) with the equals() method. if (N.equals(UserInput)) like that.
3rd Apr 2020, 6:22 AM
Tibor Santa
Tibor Santa - avatar
+ 1
It is not waiting for my 2nd input which is going to be held in UserInput variable.
3rd Apr 2020, 6:27 AM
Aamir
Aamir - avatar
+ 1
It worked, Thank You So Much buddy
3rd Apr 2020, 6:35 AM
Aamir
Aamir - avatar
+ 1
In if condition you should use equals method because it should match the values but not the references
4th Apr 2020, 5:07 PM
santhi kiran
0
i want to learn java for developing android applications , is Java from Solo learn enough for Android app development ???
3rd Apr 2020, 7:04 AM
Aamir
Aamir - avatar
0
can u tell me about some free sources from where i will be able to learn java for android
3rd Apr 2020, 7:28 AM
Aamir
Aamir - avatar