0% found this document useful (0 votes)
10 views12 pages

Java Programming Exercises and Solutions

The 10 exercises present programming in Java with an emphasis on: 1) Loop and conditional structures to solve problems such as printing even numbers, testing primes, calculating factorials, and the Fibonacci series. 2) Use of arrays and matrices to store and process data such as grades, names, performing operations like average, sorting, and transposition. 3) Creation of classes with attributes and methods to represent objects such as circles, triangles, movies, and execute c.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

Java Programming Exercises and Solutions

The 10 exercises present programming in Java with an emphasis on: 1) Loop and conditional structures to solve problems such as printing even numbers, testing primes, calculating factorials, and the Fibonacci series. 2) Use of arrays and matrices to store and process data such as grades, names, performing operations like average, sorting, and transposition. 3) Creation of classes with attributes and methods to represent objects such as circles, triangles, movies, and execute c.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming Exercises

Exercises done in class:

1. Write an algorithm to print the even numbers from 1 to 50.


public class Pairs {
public static void main(String[] args) {
for(int i = 1; i <= 50; i++)
if(i%2 == 0)
[Link]("I: " + i + " is even");
}
}

2. Write an algorithm to identify if a number is prime or not. The number must be read from the keyboard.

import [Link].*;
public class TestaPrimo {
public static void main(String[] args) {
Scanner N = new Scanner([Link]);
intcontador = 0;
[Link]("Enter the number to be tested:");
intx = [Link]();
for(int i = 2; i <= x; i++)
if(x % i == 0)
counter++;
if(counter == 1)
The tested number is prime
else
[Link]("O número testado não é primo");
}
}

3. Calculate the factorial of the integer entered by the user.

import [Link].*;
public class Fatorial {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);
[Link]("Enter the number to calculate the factorial: ");
intx = [Link]();
intfat = 1;
for(int i = 1; i <= x; i++)
fat = fat * i;
[Link]("The factorial of " + x + " is: " + fat);
}
}

4. Print the Fibonacci series up to its 20th term.

public classFibonnacci {
public static void main(String[] args) {
inta,b,c;
a=1;
b=1;
[Link]("1st Term: " + a);
[Link]("2nd Term: " + b);
for(int i = 2; i < 10; i++) {
c = a + b;
a=b;
b=c;
[Link](i+1 +"º Termo: "+c);
}
}
}
5. Create an array to store grades entered via the keyboard and then calculate the average.

import [Link].*;
public class mediaVetor {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);
[Link]("Enter the number of grades");
doublex [] = new double[[Link]()];
doublesoma = 0;
for(int i = 0; i < [Link]; i++) {
[Link]("Enter the grade: ");
x[i] = [Link]();
soma = soma + x[i];
}
doublemedia = sum/[Link];
[Link]("The average was: " + media);
}
}

6. Create an array to store names of people entered and sorted.

import [Link].*;
public class vetorStrings {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);
[Link]("Enter how many names will fill the array");
String x [] = new String [[Link]()];
[Link]("Enter the names that will fill the array");
for(int i = 0; i < [Link]; i++)
x[i]=[Link]();
[Link](x);
for(int i = 0; i < [Link]; i++)
[Link](x[i]);
}
}

7. Write an algorithm that identifies if vector A is identical to the reverse of vector B.

import [Link].*;
public class VectorComparison {
public static voidmain(String[] args) {
int[] = new int[3];
int[] = new int[3];
Scanner s = new Scanner([Link]);
[Link]("Vector X");
for(int i = 0; i < [Link]; i++)
x[i] = [Link]();
[Link]("Vector Y");
for(int i = 0; i < [Link]; i++)
y[i]= [Link]();
booleaniguais =true;
intj = [Link] - 1;
for(int i = 0; i < [Link]; i++) {
if(x[i] != y[j])
iguais =false;
j--;
}
if(equals)
The vector X is equal to the inverse of the vector Y!
else
The entered vectors are different!
}
}
8. Write an algorithm to calculate the transpose of a matrix.

public class CalculateTranspose {


public static void main(String[] args) {
int[][] x = {{0,1,2},{0,0,6},{1,2,9}};
int[][] Transposed = new int[3][3];
for(int i = 0; i < [Link]; i++) {
for(int j = 0; j < [Link]; j++){
Transposed[i][j] = x[j][i];
[Link](Transposed[i][j]+" ");
}
[Link]();
}
}
}

9. Create the classes as specified below. Then create another class to create 2 of them.
circumferences and 3 triangles and perform the necessary calculations.

Circumference Triangle
- raio: double - base: double
Circumference (r: double) - altura: double
CalculateArea(): double + Triangulo (b: double, a: double)
+ CalculateDiameter(): double CalculateArea(): double
Gets and Sets Gets and Sets

Class circumference:
public class Circle {
private doubleraio;
publicCircle (double radius) {
[Link]= raio;
}
public doubleCalcularDiametro(){
return 2 * radius;
}
public double CalculateArea() {
[Link] * radius * radius;
}
public doubleCalcularPerimetro(){
return2 * [Link]*radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double newRadius) {
ray = newRay;
}
}

Triangle Class:
public class Triangle {
private double base;
private double height;

publicTriangle(double base, double height) {


[Link] = base;
[Link] = height;
}
public double calculateArea() {
base*height/2;
}
public double getBase() {
returnbase;
}
public void setBase(double novaBase) {
base= newBase;
}
public double getHeight() {
return height;
}
public void setAltura(double novaAltura) {
altura= novaAltura;
}
}

Mathematics Class (to perform the operations of the other classes):


import [Link].*;
public class Mathematics {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);

[Link]("Enter the base and height of the triangle:");


TriangleT = new Triangle([Link](), [Link]());
[Link]("Base of the triangle: " + [Link]());
[Link]("Height of the triangle: " + [Link]());
[Link] ("Area of the triangle: " + [Link]());

[Link]("Enter the radius of the Circle:");


Circle C = new Circle([Link]());
[Link]("Radius of the Circumference: " + [Link]());
[Link] ("Area of the Circle: " + [Link]());
[Link]("Diameter of the Circumference: " + [Link]());
[Link]("Circumference Perimeter: " + [Link]());
}
}

10. Crie uma classe chamada Filme e uma classe Oscar para efetuar as operações da primeira.

public classMovie {
privateStringtitulo,genero;
private double nota1, nota2;
private int cont = 0;

publicFilm(String T, String genre){


titulo= T;
[Link]= genero;
}
public doublegetNota1() {
returnnota1;
}
public void setNota1(double nota1) {
this.nota1= nota1;
}
public double getNota2() {
returnnota2;
}
public voidsetNota2(doublenota2) {
this.nota2= nota2;
}
public void vote(double score) {
cont++;
if(cont==1)
note1 = note;
else
nota2 = nota;
}
public double getAssessment() {
return((grade1+grade2)/2);
}
publicString getTitulo(){
return title;
}
public voidsetTitulo (String t){
titulo= t;
}
publicString getGenero(){
return genre;
}
public void setGenero(String g){
genero= g;
}
}

import [Link].*;
public class Oscar {
public static void main (String []args) {
Scanner x = new Scanner([Link]);
[Link]("Enter the title and genre of movie A: ");
Movie a = newMovie([Link](), [Link]());
[Link]("Enter the title and genre of movie B: ");
Movie b = new Movie([Link](), [Link]());
[Link]("Enter the ratings for Movie A: ");
for(int i = 1; i <= 3; i++)
[Link]([Link]());
[Link]();
[Link]("Enter the ratings of movie B: ");
for(int i = 1; i <= 3; i++)
[Link]([Link]());
[Link]();
if([Link]() > [Link]())
[Link]("The Oscar goes to " + [Link]());
else
The oscar goes to
}
}

Exercises Lecture Note No. 04:


11. Implement an algorithm to display the binary representation of an integer entered by the user.
minus 8 bits.

import [Link];
public class BinaryRepresentation {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);
[Link]("Enter the number to be converted to binary: ");
intx = [Link]();
String bin= [Link]( x );
Equivalent in binary is:
}
}
12. Implement an algorithm to print the current system date in the following format: 15th of February
2008 - Friday (5:51:14 PM).

import [Link];
public class Data {
public static voidmain(String[] args) {
String data;
Day of Month de Month Name de Year - Day of Week
hours, minutes and
+"seconds"+"), [Link]());
[Link](data);
}
}
Exercises Class note nº 05:
13. Write an algorithm to print the prime numbers from 2 up to a value entered by the user
public class Primos {
private intn;
public void primeNumbers() {
for(int i = 2; i <= n; i++)
checkingPrime(i);
}
publicPrimos (intn) {
this.n= n;
}
public void checkingPrime(int number) {
inttotal = 0;
for(int i = 2; i <= (number - 1); i++)
if((number % i) == 0)
total++;
if(total == 0)
The number %d is prime.
}
}

import [Link].*;
public class testPrimos {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);
[Link]("Enter the number(s) for the test: ");
intx = [Link]();
Primos object = new Primos(x);
[Link]();
}
}

14. Write an algorithm to print a date entered by the user in another format (use the command
switch).
Entered value: 12/10/1998.
Printed value: October 12, 1998.

import [Link].*;
public classtransformaData {

public static void main(String[] args) {


Scanner a = new Scanner([Link]);
[Link]("enter the day");
intdia = [Link]();
[Link]("enter the month");
intmes = [Link]();
[Link]("enter the year");
intano = [Link]();
User input data:
day/month/year;
String m ="";
switch(month){
case01:
January
break;
case02:
m ="Fevereiro";
break;
case03:
m ="Março";
break;
case04:
m ="Abril";
break;
case05:
May
break;
case06:
m ="Junho";
break;
case07:
July
break;
case8:
m ="Agosto";
break;
case9:
September
break
case10:
m ="Outubro";
break;
case11:
November
break;
case12:
December
break;

default:
[Link]("Enter a valid date");

}
if(mes <= 12 )
Transformed data:
}
}

Exercises Lesson Note No. 06:


15. Write an algorithm to display the average of integer values present in an array, filled by a
user.

import [Link].*;
public classmediaVetor {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);
[Link]("Enter the number of grades");
doublex [] = new double[[Link]()];
doublesoma = 0;
for(int i = 0; i < [Link]; i++) {
[Link]("Enter the grade: ");
x[i] = [Link]();
soma = soma + x[i];
}
doublemedia = sum/[Link];
[Link]("The average was: " + media);
}
}

16. Write an algorithm to fill an array with names of people (via keyboard), sort it, and display it.

[Link].*;
public class vectorStrings {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);
[Link]("Enter how many names will fill the array");
String x[] = new String[[Link]()];
[Link]("Enter the names that will fill the array");
for(int i = 0; i < [Link]; i++)
x[i]=[Link]();
[Link](x);
for(int i = 0; i < [Link]; i++)
[Link](x[i]);
}
}

17. Write an algorithm to display the sum matrix of two others.

public class matrizSoma {


public static void main(String[] args) {
int[][] x = {{0,1,2},{0,0,2},{1,2,9}};
int[][] y = {{1,2,0},{3,4,3},{1,5,6}};
int[][] sum = new int[3][3];
for(int i = 0; i < [Link]; i++){
for(int j = 0; j < [Link]; j++){
sum [i][j] = x [i][j] + y [i][j];
[Link](soma[i][j] +" ");
}
[Link]();
}
}
}

18. Write an algorithm to display the product matrix of two others.

public class MatrixProduct {


public static void main(String[] args) {
int[][] x = {{3,3,3},{6,6,4},{8,10,9}};
int[][] y = {{3,6,11},{5,6,11},{7,8,9}};
int[][] produto =new int[3][3];
for(int lin = 0; lin < [Link]; lin++){
for(int col = 0; col < [Link]; col++) {
product[lin][col] = 0;
for(int k = 0; k < [Link]; k++){
product[lin][col] = product[lin][col] + x[lin][k]*y[k][col];
}
[Link](product[row][col] +" ");
}
[Link]();
}
}
}

Exercises Lesson note No. 07:


19. Create a class called CurrentAccount to test a Bank class.

public class CurrentAccount {


String number;
double balance
publicCurrentAccount (String n, doubles) {
number= n;
saldo= s;
}
public void credit(double value) {
balance = balance + value;
}
public void debit (double value) {
balance=balance- value;
}
public double getBalance() {
return balance
}
}
import [Link].*;
public classBanco {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);
Current Account:
String n = [Link]();
Balance:
doubles = [Link]();
CurrentAccount d = new CurrentAccount(n,s);
[Link]("O seu saldo atual é de "+ [Link]());
How much would you like to deposit?
s = [Link]();
[Link](s);
How much would you like to withdraw?
s = [Link]();
[Link](s);
Your current balance is
}
}

Exercises Lesson note No. 08:


20. Create a class called Time with all its characteristics and perform all operations.

public class Tempo {


private inthora;
private int minute;
private int second;
public static final intTIPO_HORA= 0;
public static final intTIPO_MINUTO= 1;
public static final intTIPO_SEGUNDO=2;
publicTempo(inthora, intminuto, intsegundo) {
[Link] = hour;
[Link] = minute;
[Link] = second;
}
publicString ObterTempoFormatado(){
returnhour+":"+minute+":"+second;
}
public void UpdateTime() {
if(hour>=24)
hour=hour$;
}
public void updateMinute() {
if(minute>=60){
hour+=hour/60;
minute=minute%60;
}
}
public void UpdateSecond() {
if(second>=60){
minute += second / 60;
second=second%60;
}
UpdateMinute();
}
public void NextTime(int value, int field) {
switch(field){
caseTIPO_HORA:
UpdateTime();
break;
caseTIPO_MINUTO:
UpdateMinute();
break;
caseTIPO_SEGUNDO:
second += value;
UpdateSecond();
break;
}

public static void main (String[] args) {


Time t1 = new Time (10, 59, 30);
String a = [Link]();
[Link](a);
[Link](59,Tempo.TIPO_MINUTO);
[Link]([Link]());
[Link](60, Tempo.TIPO_SEGUNDO);
[Link]([Link]());
}
}

Exercises Lesson note no. 09:


21. Create the classes SpecialAccount and SavingsAccount and then modify the bank class to create three types of
accounts and make credits and debits in each of them.

public class Conta Corrente {


protectedStringnumero;
protected double balance;
publicAccountBalance(String n, double s) {
number=n;
saldo=s;
}
public void credit(double value) {
balance += value;
}
public void debit(double value) {
if(balance >= value)
balance -= value;
else
Insufficient balance
}
public String getNumber() {
return number;
}
public void setNumero(String number) {
[Link] = number;
}
public double getBalance() {
balance return
}
public void setBalance(double balance) {
[Link] = balance;
}
}

public class SavingsAccount extends CheckingAccount {


private final double tax = 0.01;
publicContaPoupanca( String numero,doublesaldo){
super(number, balance);
}
public void renderInterest() {
balance = balance + balance * rate;
}
}

public classContaEspecialextendsContaCorrente{
private double creditLimit;
publicSpecialAccount(String number, double balance, double limit) {
super(number, balance);
limiteDeCredito= lim;
}
public void debit(double value) {
if(balance+creditLimit>= value)
balance -= value;
else
Limit exceeded
}
}

import [Link].*;
public class BankBrazile {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);

[Link]("Digite o numero e o saldo da Conta Corrente!");


CheckingAccount CC = new CheckingAccount([Link](), [Link]());
Credit Value:
[Link]([Link]());
[Link]("Debt Amount: ");
[Link]([Link]());
[Link]("Saldo Atual: "+ [Link]());

[Link]("Enter the number and the balance of the Savings Account!");


ContaPoupanca CP =newContaPoupanca ([Link](),[Link]());
Credit Amount:
[Link]([Link]());
[Link]("Value of Debt: ");
[Link]([Link]());
[Link]();
[Link]("Current Balance: " + [Link]());

[Link]("Enter the number, balance, and limit of the account");


Special!
ContaEspecial CE =newContaEspecial
([Link](), [Link](), [Link]());
Credit Value:
[Link]([Link]());
Debit Value:
[Link]([Link]());
[Link]("Saldo Atual: "+ [Link]());
}
}

22. Create a class called GeometricShape, it must provide:

Atributos: base, altura


Métodos: calcularArea, imprimirAtributos
Crie as três classes abaixo, filhas de FormaGeométrica:
Triangle;
Rectangle;
Trapezoid: contains one more attribute: baseMenor.
Create a final class that creates three geometric shapes and prints the attributes and the area of each one.

public class GeometricShape {


private double base;
private double height;
publicGeometricShape(double base, double height) {
[Link]= base;
[Link] = height;
}
public double calculateArea() {
base*height;
}

public doublegetBase(){
returnbase;
}
public doublegetAltura(){
returnheight;
}
}

public class Rectangle extends GeometricShape {


publicRetangulo(doublebase,doublealtura){
super(base, height);
}
}

public class Triangle extends GeometricShape {


publicTriangle(double base, double height) {
super(base, height);
}
public double calculateArea() {
return(getBase()*getHeight())/2;
}
}

public class Trapeze extends GeometricShape {


private double baseMenor;

publicTrapezio(doublebase,doublealtura,doublebaseMenor){
super(base, height);
[Link] = baseMenor;
}
public doublecalcularArea(){
return (baseMenor + getBase()) * getAltura() / 2;
}
public double getBaseMenor() {
returnbaseMenor;
}
}

import [Link].*;
public class AreaCalculations {
public static void main(String[] args) {
Scanner a = new Scanner([Link]);

[Link]("Enter the Base and Height of the rectangle!");


Rectangle R1 = new Rectangle([Link](), [Link]());
[Link]("Base of the rectangle: " + [Link]());
[Link]("Height of the rectangle: " + [Link]());
[Link]("The area of the rectangle is: " + [Link]());

[Link]("Enter the Base and Height of the triangle!");


Triangle T1 = new Triangle([Link](), [Link]());
[Link]("Base of the triangle: " + [Link]());
[Link]("Height of the triangle: " + [Link]());
[Link]("The area of the triangle is: " + [Link]());

[Link]("Enter the Bases and the Height of the trapezoid!");


Trapezium Tra1 = new Trapezium([Link](), [Link](), [Link]());
[Link]("Greater base of the trapezoid: " + [Link]());
[Link]("Smaller base of the trapezoid: " + [Link]());
[Link]("Height of the trapezoid: " + [Link]());
[Link]("The area of the trapezoid is: " + [Link]());
}
}

You might also like