Java Cognizant
Java Cognizant
Practice questions
1. WAP to accept a number from the user and find the numb er of digits in the input
number. If the number entered is negative, print "invalid input", else print the
number.
Sample Input
123
Sample Output
3
Sample Input
-7
Sample Output
invalid input
When we use nextInt() or in general any non String input method folowed by
nextLine(), the program have chances to throw exception.
Solution:
a)Follow the nextInt() statement by a dummy nextLine().
b) Even for non String input, use nextLine() method plus Wrapper class combination.
//int age=sc.nextInt();
int age=Integer.parseInt(sc.nextLine());
String name=sc.nextLine();
System.out.println(age+":"+name);
Integer.parseInt();
Wrapper classes provide methods to tranform String input into equivalent pdt.
int num=21;
Integer.toString(num);// returns String equivalent of a number of base 10.
Integer.toString(num,2);//10101
Suppose we write,
Character wrapper class provides methods like isDigit(), isLetter() to find whether
a charater is a digit or not.
Sample Input
ABCDE1234H
Sample Output
10
A=65
a=65+32=97
Z=65+25=90
z=97+25=122
0=48
9=48+9=57
When we write Date dt=new Date(); it returns current date and time. But, if I need
to work with some other date...
We will use java.text.SimpleDateFormat class.
The above class has two powerfull methods
a) parse that converts String to Date ref
b) format that converts Date ref back to String
Other than that, two other supporting methods are
c) applyPattern(String pattern);
d) setLenient(boolean t);
WAP to accept a date from user as String and print the day.
Sample Input
01-09-2018
Sample Output
Saturday
What is supported?
long x=1234_1234_1597L;