0

I having this as

input

3
Hong Kong
India
Usa
12
130
20
And Expected output is 
Hong Kong
Usa
India
12
20
130

But i'm getting the only Exception in thread "main" java.util.InputMismatchException
How to get the full string.

public class Main{
    public static void main (String[] args) {
        Scanner sc=new Scanner(System.in);
        int no=sc.nextInt();
        String[] cname=new String[no];
        int[] pop=new int[no];
        for(int i=0;i<no;i++){
             cname[i]=sc.nextLine();
        }
        for(int i=0;i<no;i++){
            pop[i]=sc.nextInt();
        }
genpfault
  • 47,669
  • 9
  • 68
  • 119
  • Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Johannes Kuhn May 21 '20 at 20:53
  • Happens after you read the first integer, then you read the lines `""`, `"Hong Kong"` and `"India"`, now you ask for an int, but the next token is `USA`. – Johannes Kuhn May 21 '20 at 20:54
  • what are you trying to achieve? , could you please clarify more. – Mahmoud Odeh May 21 '20 at 23:19

1 Answers1

1

You can add values like this and also put value into array:

int no = Integer.parseInt(sc.nextLine());
----------------------------------------
pop[i] =Integer.parseInt(sc.nextLine());
Göksel ÖZER
  • 249
  • 1
  • 8
  • Yep, this is the correct solution for my problem. Can you tell me how Integer.parseInt help in taking the input? – Pradeep Pant May 22 '20 at 07:02
  • ``nextLine()`` recognize Enter button and ``nextInt()`` recognize Space button. When you use ``nextInt()`` and press Enter button it gets number but ``nextLine()`` method takes the line before you press enter. Also ``nextInt()`` takes number like this: https://imgur.com/d3LzeBl. – Göksel ÖZER May 22 '20 at 10:21