+ 1

java basics

hello, when I try to get user input I have issue when I enter integer and string value using nextLine() method .so how I overcome this problem (sorry if iam asking a silly question)

5th Nov 2021, 8:44 AM
Lina Akatuki
Lina Akatuki - avatar
4 Respostas
+ 3
Could you please put your code in a script on playground and link it here So we can check on your code? Without seeing the code it us hard to tell what is going on
5th Nov 2021, 8:59 AM
Lisa
Lisa - avatar
+ 2
nextLine() Reads Strings for Numerical input : nextInt(); , nextDouble(); , nextFloat(); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); double d = scanner.nextDouble();
5th Nov 2021, 9:28 AM
**🇦🇪|🇦🇪**
**🇦🇪|🇦🇪** - avatar
+ 1
Not silly at all So in order to get a value using nextLine() method Scanner s= new Scanner(System.in); // Create a Scanner called s(you can name it whatever you want though) System.out.println("Enter your name"); //here you are telling the user what input are you asking for String name = s.nextLine(); // Read user input System.out.println("name: " + name); // Output user input there are diffrent methods that you can practice too like nextBoolean() ,nextLong(), read about them so that you can accumulate knowledge
5th Nov 2021, 9:00 AM
Dareen Moughrabi
Dareen Moughrabi - avatar
+ 1
nextLine() reads entire line as input but where as nextInt() reads an integer next in console input and stay in same line. So in combination: nextInt(); nextLine(); input must in same line as ex: 12 string_input Ex: input: 12 String_input //this will not read by nextLine(), because it's already read \n carriage after 12. To overcome this: read similar datatypes in sequence,then add a empty nextLine(); or read all inputs by nextLine() and convert to appropriate compatible needed types....
5th Nov 2021, 11:44 AM
Jayakrishna 🇮🇳