Java Conditional Statement : Exercises, Practice, Solution
Java Conditional Statement Exercises [32 exercises with solution]
[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]1. Write a Java program to get a number from the user and print whether it is positive or negative.
2. Write a Java program to solve quadratic equations (use if, else if and else).
Test Data
Input a: 1
Input b: 5
Input c: 1
Expected Output :
The roots are -0.20871215252208009 and -4.7912878474779195
Click me to see the solution
3. Write a Java program that takes three numbers from the user and prints the greatest number.
Test Data
Input the 1st number: 25
Input the 2nd number: 78
Input the 3rd number: 87
Expected Output :
The greatest: 87
4. Write a Java program that reads a floating-point number and prints «zero» if the number is zero. Otherwise, print «positive» or «negative». Add «small» if the absolute value of the number is less than 1, or «large» if it exceeds 1,000,000.
Test Data
Input a number: 25
Expected Output :
Input value: 25
Positive number
5. Write a Java program that takes a number from the user and generates an integer between 1 and 7. It displays the weekday name.
Test Data
Input number: 3
Expected Output :
Wednesday
6. Write a Java program that reads two floating-point numbers and tests whether they are the same up to three decimal places.
Test Data
Input floating-point number: 25.586
Input floating-point another number: 25.589
Expected Output :
They are different
7. Write a Java program to find the number of days in a month.
Test Data
Input a month number: 2
Input a year: 2016
Expected Output :
February 2016 has 29 days
8. Write a Java program that requires the user to enter a single character from the alphabet. Print Vowel or Consonant, depending on user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message.
Test Data
Input an alphabet: p
Expected Output :
Input letter is Consonant
9. Write a Java program that takes a year from the user and prints whether it is a leap year or not.
Test Data
Input the year: 2016
Expected Output :
2016 is a leap year
10. Write a Java program to display the first 10 natural numbers.
The first 10 natural numbers are: 1 2 3 4 5 6 7 8 9 10
11. Write a Java program to display n terms of natural numbers and their sum.
Test Data
Input the number: 2
Expected Output :
Input number: 2 The first n natural numbers are : 2 1 2 The Sum of Natural Number upto n terms : 23
12. Write a program in Java to input 5 numbers from the keyboard and find their sum and average.
Test Data
Input the 5 numbers : 1 2 3 4 5
Expected Output :
Input the 5 numbers : 1 2 3 4 5 The sum of 5 no is : 15 The Average is : 3.0
13. Write a Java program to display the cube of the given number up to an integer.
Test Data
Input number of terms : 4
Expected Output :
Number is : 1 and cube of 1 is : 1 Number is : 2 and cube of 2 is : 8 Number is : 3 and cube of 3 is : 27 Number is : 4 and cube of 4 is : 64
14. Write a Java program to display the multiplication table of a given integer.
Test Data
Input the number (Table to be calculated) : Input number of terms : 5
Expected Output :
5 X 0 = 0 5 X 1 = 5 5 X 2 = 10 5 X 3 = 15 5 X 4 = 20 5 X 5 = 25
15. Write a Java program that displays the sum of n odd natural numbers.
Test Data
Input number of terms is: 5
Expected Output :
The odd numbers are : 1 3 5 7 9 The Sum of odd Natural Number upto 5 terms is: 25
16. Write a Java program to display the pattern like a right angle triangle with a number.
Test Data
Input number of rows : 10
Expected Output :
1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910
17. Write a program in Java to make such a pattern like a right angle triangle with a number which repeats a number in a row.
The pattern is as follows :
18. Write a Java program to make such a pattern like a right angle triangle with the number increased by 1.
19. Write a Java program to make such a pattern like a pyramid with a number that repeats in the same row.
20. Write a Java program to print Floyd’s Triangle.
Test Data
Input number of rows : 5
Expected Output :
Input number of rows : 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
21. Write a Java program to display the pattern like a diamond.
Test Data
Input number of rows (half of the diamond) : 7
Expected Output :
22. Write a Java program to display Pascal’s triangle.
Test Data
Input number of rows: 5
Expected Output :
Input number of rows: 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
23. Write a Java program to generate the following * triangles.
Test Data
Input the number: 6
Expected Output :
24. Write a Java program to generate the following @’s triangle.
Test Data
Input the number: 6
Expected Output :
25. Write a Java program to display the number rhombus structure.
Test Data
Input the number: 7
Expected Output :
1 212 32123 4321234 543212345 65432123456 7654321234567 65432123456 543212345 4321234 32123 212 1
26. Write a Java program to display the following character rhombus structure.
Test Data
Input the number: 7
Expected Output :
A ABA ABCBA ABCDCBA ABCDEDCBA ABCDEFEDCBA ABCDEFGFEDCBA ABCDEFEDCBA ABCDEDCBA ABCDCBA ABCBA ABA A
27. Write a Java program that reads an integer and check whether it is negative, zero, or positive.
Test Data
Input a number: 7
Expected Output :
28. Write a Java program that reads a floating-point number. If the number is zero it prints «zero», otherwise, print «positive» or «negative». Add «small» if the absolute value of the number is less than 1, or «large» if it exceeds 1,000,000.
Test Data
Input a number: -2534
Expected Output :
29. Write a Java program that reads an positive integer and count the number of digits the number (less than ten billion) has.
Test Data
Input an integer number less than ten billion: 125463
Expected Output :
Number of digits in the number: 6
30. Write a Java program that accepts three numbers and prints «All numbers are equal» if all three numbers are equal, «All numbers are different» if all three numbers are different and «Neither all are equal or different» otherwise.
Test Data
Input first number: 2564
Input second number: 3526
Input third number: 2456
Expected Output :
All numbers are different
31. Write a program that accepts three numbers from the user and prints «increasing» if the numbers are in increasing order, «decreasing» if the numbers are in decreasing order, and «Neither increasing or decreasing order» otherwise.
Test Data
Input first number: 1524
Input second number: 2345
Input third number: 3321
Expected Output :
32. Write a Java program that accepts two floatingpoint numbers and checks whether they are the same up to two decimal places.
Test Data
Input first floatingpoint number: 1235
Input second floatingpoint number: 2534
Expected Output :
These numbers are different.
Java Code Editor:
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
Follow us on Facebook and Twitter for latest update.
Java: Tips of the Day
What is the difference between a static and a non-static initialization code block
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it’s resolved, but that’s a technicality).
Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.
If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error «non-static variable a cannot be referenced from a static context».
If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
Java if интересные задачи
Напишите консольную программу, в которой пользователь с клавиатуры вводит два числа. А программа сранивает два введенных числа и выводит на консоль результат сравнения (два числа равны, первое число больше второго или первое число меньше второго).
import java.util.Scanner; public class Program < public static void main(String[] args) < Scanner in = new Scanner(System.in); System.out.print("Введите первое число: "); int num1 = in.nextInt(); System.out.print("Введите второе число: "); int num2 = in.nextInt(); if(num1 >num2) < System.out.println("Первое число больше второго"); >else if (num1 < num2)< System.out.println("Первое число меньше второго"); >else < System.out.println("Оба числа равны"); >in.close(); > >
Напишите консольную программу, в которой пользователь вводит с клавиатуры число. Если число одновременно меньше 9 и больше 2, то программа выводит «Число больше 5 и меньше 10». Иначе программа выводит сообщение «Неизвестное число».
import java.util.Scanner; public class Program < public static void main(String[] args) < Scanner in = new Scanner(System.in); System.out.print("Введите число: "); int num = in.nextInt(); if(num >2 && num < 9)< System.out.println("Число больше 2 и меньше 9"); >else < System.out.println("Неизвестное число"); >in.close(); > >
В банке в зависимости от суммы вклада начисляемый процент по вкладу может отличаться. Напишите консольную программу, в которую пользователь вводит сумму вклада. Если сумма вклада меньше 100, то начисляется 5%. Если сумма вклада от 100 до 200, то начисляется 7%. Если сумма вклада больше 200, то начисляется 10%. В конце программа должна выводить сумму вклада с начисленными процентами.
import java.util.Scanner; public class Main < public static void main(String[] args) < Scanner in = new Scanner(System.in); System.out.print("Введите сумму вклада: "); float sum = in.nextFloat(); if (sum < 100)< sum += sum * 0.05; >else if (sum >= 100 && sum else < sum += sum * 0.1; >System.out.printf("Сумму вклада после начисления процентов: %f", sum); in.close(); > >
Напишите консольную программу, которая выводит пользователю сообщение «Введите номер операции: 1.Сложение 2.Вычитание 3.Умножение». Рядом с названием каждой операции указан ее номер, например, операция вычитания имеет номер 2. Пусть пользователь вводит в программе номер операции, и в зависимости от этого номера программа выводит название операции.
Для определения операции по введенному номеру используйте конструкцию switch. case.
Если введенное пользователем число не соответствует никакой операции (например, число 120), то выведите пользователю сообщение о том, что операция неопределена.
Введите номер операции: 1.Сложение 2.Вычитание 3.Умножение 1 Сложение
import java.util.Scanner; public class Program < public static void main(String[] args) < Scanner in = new Scanner(System.in); System.out.println("Введите номер операции: 1.Сложение 2.Вычитание 3.Умножение"); int operation = in.nextInt(); switch (operation) < case 1: System.out.println("Сложение"); break; case 2: System.out.println("Вычитание"); break; case 3: System.out.println("Умножение"); break; default: System.out.println("Неизвестная операция"); break; >in.close(); > >
Измените предыдущую программу. Пусть пользователь кроме номера операции вводит два числа, и в зависимости от номера операции с введенными числами выполняются определенные действия (например, при вводе числа 3 числа умножаются). Результат операции выводиться на консоль.
Введите первое число: 5 Введите второе число: 2 Введите номер операции: 1.Сложение 2.Вычитание 3.Умножение 1 Результат операции: 7
import java.util.Scanner; public class Program < public static void main(String[] args) < Scanner in = new Scanner(System.in); System.out.print("Введите первое число: "); int num1 = in.nextInt(); System.out.print("Введите второе число: "); int num2 = in.nextInt(); System.out.println("Введите номер операции: 1.Сложение 2.Вычитание 3.Умножение"); int operation = in.nextInt(); int result = 0; switch (operation) < case 1: result = num1 + num2; break; case 2: result = num1 - num2; break; case 3: result = num1 * num2; break; default: System.out.println("Неизвестная операция"); >if(operation >=1 && operation in.close(); > >