Reputation: 13
I want to take a string input from keyboard. But when I ran this program there are no option to take string input. I don't know what my fault is.
Here my code is:
import java.util.Scanner;
public class Input_Program {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int a,b;
System.out.println("Enter the first number :");
a=in.nextInt();
System.out.println("Enter the second number :");
b=in.nextInt();
System.out.println("Value of first number:"+a);
System.out.println("Value of second number:"+b);
System.out.println("Do you want Add two numbers");
System.out.println("To Continue: Type Yes");
String S=in.nextLine();
if("Yes".equals(S)||"yes".equals(S))
{
int sum=a+b;
System.out.println("Summation :"+sum);
}
}
}
I want to take an input from this code. But it's not working.
String S=in.nextLine();
if("Yes".equals(S)||"yes".equals(S))
{
int sum=a+b;
System.out.println("Summation :"+sum);
}
And the result of this code is :
run:
Enter the first number :
2
Enter the second number :
3
Value of second number:3
Do you want the Summation of two numbers
To Continue: Type Yes
BUILD SUCCESSFUL (total time: 9 seconds)
Upvotes: 0
Views: 129
Reputation: 368
1) nextLine() according to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html "Advances this scanner past the current line and returns the input that was skipped" which is not the behavior you are looking for.
2) It seems that you are new to java, and there are naming conventions. Please do not start variable names with uppercase letters
3) I fixed your indentation, and also generalized the input to take in anything that starts with y. In the future make sure you write your code this way since it's easier to tell which lines of code are in if statements, and loops and such.
import java.util.Scanner;
public class Input_Program {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the first number :");
int a = in.nextInt();
System.out.println("Enter the second number :");
int b = in.nextInt();
System.out.println("Value of first number:" + a);
System.out.println("Value of second number:" + b);
System.out.println("Do you want Add two numbers");
System.out.println("To Continue: Type Yes");
String s = in.next();
if(s.toLowerCase().contains("y")){
int sum=a+b;
System.out.println("Summation :"+sum);
}
}
}
Upvotes: 2