0
package day1.example;

import java.util.Scanner;

public class ExampleInput {


    private static Scanner obj;

    public static void main(String[] args) {
        obj = new Scanner(System.in);
        int a;
        float b;
        String c;
        System.out.println("Enter a No : ");
        a = obj.nextInt();
        System.out.println("a = " + Math.pow(a,2));
        System.out.println("Enter a Float : ");
        b = obj.nextFloat();
        System.out.println("b = " + b);
        System.out.println("Enter a String :");
        c = obj.nextLine();
        System.out.println("Name = " + c);


    }

}

it asks for integer and float but doesnt accept string. Do I need to add some ignore escape sequence as we do in C++ (cin.ignore)

Tunaki
  • 116,530
  • 39
  • 281
  • 370
Ammar Hussain
  • 204
  • 1
  • 10

1 Answers1

0
 c = obj.next();

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Kumaresan Perumal
  • 1,700
  • 20
  • 31