1
String[] v=s.split(" ");//it is reading only first character into v[0], But the remaining Strings are getting omitted.

ex: Consider "1 1 2011" is given as user input. It is taking v[0]=1, but 
 v[1] and v[2] are being empty.

This is the error I got.

1 1 2011
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at com.techm.Magic.main(Magic.java:15)

package com.techm;

My code

import java.util.Scanner;

public class Magic {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        String s=sc.next();
        int h=0;


        String[] v=s.split(" ");
         h=(Integer.parseInt(v[0])*Integer.parseInt(v[1]));

         String k=String.valueOf(h);
         int len=k.length();

         String d=v[2];
          int y=Integer.parseInt(d);
         int a=0;

         if(len==1)
         {
             a=y%10;

            if(h==a) 
                System.out.println("true");
            else
                System.out.println("false");
         }
         else if(len==2)
         {
             //d=s.substring(s.length()-2);
             a=y%100;
             if(h==a)
                 System.out.println("true");
             else
                 System.out.println("false");
         }

         else
         {
             //d=s.substring(s.length()-3);
             a=y%1000;
             if(h==a)
                 System.out.println("true");
             else
                 System.out.println("false");
         }   
        }
    }
fatihyildizhan
  • 7,103
  • 5
  • 54
  • 74

2 Answers2

0

Use String s=sc.nextLine() instead of String s=sc.next()

We need to use nextLine() method to read Strings.

Sarangan
  • 803
  • 7
  • 20
  • Sir, can u explain me why we need to use nextLine()? – jadeja prem Apr 27 '20 at 05:40
  • Using `next()` will only return what comes before the delimiter (defaults to whitespace).`next()` can read the input only till the space. It can't read two words separated by a space. Also, `next()` places the cursor in the same line after reading the input. `nextLine()` automatically moves the scanner down after returning the current line. `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. – Sarangan Apr 27 '20 at 05:43
  • And please stop calling me as sir :) – Sarangan Apr 27 '20 at 05:43
0

Use String s = sc.nextLine() instead of s= sc.next().

Also please go through: What's the difference between next() and nextLine() methods from Scanner class? to have better understanding.

Anu
  • 70
  • 10