viernes, 29 de septiembre de 2023

Domina Java: 20 Ejercicios Resueltos para Impulsar tus Habilidades de Programación. Universidad. (Parte 2)

 Como continuación del artículo "Domina Java: 20 Ejercicios Resueltos para Impulsar tus Habilidades de Programación. Universidad. (Parte 1)", aqui publico la Parte 2 del artículo que no es más que una continuación con otros 20 ejercicios prácticos para que pongais en juego lo aprendido en la universidad o vuestros cursos de programación de Java.


Ejercicio 21: Programa Java de búsqueda lineal

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    int[] numbers = {4,2,7,1,8,3,6};
    int flag = 0;
    
    System.out.println("Enter the number to be found out: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());
    
    for(int i=0;i<numbers.length;i++){
      if (x==numbers[i]){
        System.out.println("Successful search, the element is found at position "+ i);
        flag = 1;
        break;
      }
    }

    if(flag==0){
      System.out.println("Oops! Search unsuccessful");
    }
    
  }
}


Ejercicio 22: Programa Java de búsqueda binaria

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    int[] numbers = {1,4,6,7,12,17,25}; //binary search requires sorted numbers
    System.out.println("Enter the number to be found out: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    int result = binarySearch(numbers, 0, numbers.length-1, x);
    if (result != -1)
      System.out.println("Search successful, element found at position "+result);
    else
      System.out.println("The given element is not present in the array");
    
  }

  public static int binarySearch(int[] numbers,int low,int high,int x){
    if (high >= low){
      int mid = low + (high - low)/2;
      if (numbers[mid] == x)
        return mid;
      else if (numbers[mid] > x)
        return binarySearch(numbers, low, mid-1, x);
      else
        return binarySearch(numbers, mid+1, high, x);
    }else{
      return -1;
    }
        
        
  }
}


Ejercicio 23: Programa Java para encontrar el número de números impares en una matriz

class Main {
  public static void main(String[] args) {

    int[] numbers = {8,3,1,6,2,4,5,9};
    int count = 0;

    for(int i=0;i<numbers.length;i++){
      if(numbers[i]%2!=0)
        count++;
    }
   System.out.println("The number of odd numbers in the list are: "+count);      
        
  }
}


Ejercicio 24: Programa Java para encontrar el mayor número de una matriz sin utilizar funciones incorporadas

class Main {
  public static void main(String[] args) {

    int[] numbers = {3,8,1,7,2,9,5,4};
    int largest = numbers[0];
    int position = 0;

    for(int i=0;i<numbers.length;i++){
      if(numbers[i]>largest){
        largest = numbers[i];
        position = i;
      }
    }

   System.out.println("The largest element is "+largest+" which is found at position "+position);      
        
  }
}


Ejercicio 25: Programa Java para insertar un número en cualquier posición de una matriz

import java.util.Scanner;
import java.util.Arrays;

class Main {
  public static void main(String[] args) {

    int[] numbers = {3,4,1,9,6,2,8};
    System.out.println(Arrays.toString(numbers));

    System.out.println("Enter the number to be inserted: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the position: ");
    int y = Integer.parseInt(sc.nextLine());

    for(int i=numbers.length-1;i>y;i--){
        numbers[i] = numbers[i-1];
    }
    numbers[y] = x;

   System.out.println(Arrays.toString(numbers));   
        
  }
}


Ejercicio 26: Programa Java para borrar un elemento de un array por índice

import java.util.Scanner;
import java.util.Arrays;

import java.util.ArrayList; 

class Main {
  public static void main(String[] args) {

    ArrayList<Integer> numbers = new ArrayList<Integer>(5); 
    numbers.add(3);
    numbers.add(7);
    numbers.add(1);
    numbers.add(4);
    
    System.out.println(numbers);

    System.out.println("Enter the position of the element to be deleted: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    numbers.remove(x);

   System.out.println(numbers);   
        
  }
}


Ejercicio 27: Programa Java para comprobar si una cadena es un palíndromo o no

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

    String a, b = "";
    Scanner s = new Scanner(System.in);
    System.out.print("Enter the string you want to check: ");
    a = s.nextLine();
    
    int n = a.length();
    for(int i = n - 1; i >= 0; i--){
        b = b + a.charAt(i);
    }
    
    if(a.equalsIgnoreCase(b)){
      System.out.println("The string is a palindrome.");
    }else{
      System.out.println("The string is not a palindrome.");
    }
    
  }
}


Ejercicio 28: Programa Java para la suma de matrices

class Main {
  public static void main(String[] args) {

    //creating two matrices    
    int a[][]={{8,5,1},{9,3,2},{4,6,3}};    
    int b[][]={{8,5,3},{9,5,7},{9,4,1}};    
    
    //matrix to store the sum of two matrices    
    int c[][]=new int[3][3];  //3 rows and 3 columns  
    
    //adding 2 matrices    
    for(int i=0;i<3;i++){    
      for(int j=0;j<3;j++){    
        c[i][j]=a[i][j]+b[i][j];
        System.out.print(c[i][j]+" ");    
      }
      System.out.print("\n"); 
    }    
    
  }
}


Ejercicio 29: Programa Java para la multiplicación de matrices

class Main {
  public static void main(String[] args) {

    //creating two matrices    
    int a[][]={{8,5,1},{9,3,2},{4,6,3}};    
    int b[][]={{8,5,3},{9,5,7},{9,4,1}};    
    
    //matrix to store the product of two matrices    
    int c[][]=new int[3][3];
    
    //multiplying 2 matrices
    for(int i=0;i<3;i++){    
      for(int j=0;j<3;j++){    
        c[i][j]=0;      
        for(int k=0;k<3;k++){      
          c[i][j]+=a[i][k]*b[k][j];      
        }
        System.out.print(c[i][j]+" ");
      }
      System.out.print("\n"); 
    }    
    
  }
}


Ejercicio 30: Programa Java para comprobar el año bisiesto

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the year you want to check: ");
    int year = Integer.parseInt(sc.nextLine()); 
    boolean leap = false;
    
    // if the year is divided by 4
    if (year % 4 == 0) {
      // if the year is century
      if (year % 100 == 0) {
        // if year is divided by 400, then it is a leap year
        if (year % 400 == 0)
          leap = true;
        else
          leap = false;
      }
      // if the year is not century
      else
        leap = true;
    }
    else
      leap = false;

    if (leap)
      System.out.println(year + " is a leap year.");
    else
      System.out.println(year + " is not a leap year.");
    
  }
}


Ejercicio 31: Programa Java para hallar el enésimo término de una serie de Fibonacci mediante recursión

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {
    Scanner cs=new Scanner(System.in);
    int n;
		System.out.print("Enter the position(N): ");
		n=cs.nextInt();
		System.out.print("Nth Fibonacci Number is: "+NthFibonacciNumber(n));
  }

  static int NthFibonacciNumber(int n){
	    if(n==1)
	        return 0;
	    else if(n==2)
	        return 1;
	    else
	        return NthFibonacciNumber(n-1)+NthFibonacciNumber(n-2);
	}
  
}


Ejercicio 32: Programa Java para imprimir series Fibonacci usando iteración

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int n1=0,n2=1;
    Scanner cs=new Scanner(System.in);
		System.out.print("Enter the number of terms in the sequence: ");
		int count = cs.nextInt(); 
    int n3,i;
    
    System.out.print(n1+" "+n2);//printing 0 and 1
    //printing from 2 because 0 and 1 are already printed  
    for(i=2;i<count;++i){
      n3=n1+n2;    
      System.out.print(" "+n3);    
      n1=n2;    
      n2=n3;
      }    
	
    }
}


Ejercicio 33: Programa Java para implementar una calculadora que realice operaciones básicas

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
      int firstNumber, secondNumber, opt, add, sub, mul;
      double div;
      Scanner s = new Scanner(System.in);
      System.out.print("Enter first number: ");
      firstNumber = s.nextInt();
      System.out.print("Enter second number: ");
      secondNumber = s.nextInt();
      
      while(true){
        System.out.println("Enter 1 for addition");
        System.out.println("Enter 2 for subtraction");
        System.out.println("Enter 3 for multiplication");
        System.out.println("Enter 4 for division");
        System.out.println("Enter 5 to Exit");
        int option = s.nextInt();
        switch(option){
          case 1:
            add = firstNumber + secondNumber;
            System.out.println("Result:"+add);
            break;
 
          case 2:
            sub = firstNumber - secondNumber;
            System.out.println("Result:"+sub);
            break;
 
          case 3:
            mul = firstNumber * secondNumber;
            System.out.println("Result:"+mul);
            break;
 
          case 4:
            div = (double)firstNumber / secondNumber;
            System.out.println("Result:"+div);
            break;    
 
          case 5:
            System.exit(0);
            
            }
        }
	
    }
}


Ejercicio 34: Programa Java para encontrar tu peso en Marte

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  System.out.print("How many pounds (lbs) do you weigh? ") ;
  float weight = input.nextFloat();

  // computing the weight on mars
  double weightOnMars = (weight * .38);

  // displaying results with 4 decimal places
  System.out.println("Your weight is "+String.format("%.4f",weightOnMars)+" lbs on Mars");

    System.out.println("Converting the variable into integer");
    int weightOnMarsInt = (int)weightOnMars;
    System.out.println(weightOnMarsInt);

    System.out.println("Converting the variable into char");
    char weightOnMarsChar = (char)weightOnMars;
    System.out.println(weightOnMarsChar);

    System.out.println("Converting the variable into Int and doing an operation on it");
    int newIntVariable = weightOnMarsChar * 2;
    System.out.println(newIntVariable);
    
  }
}


Ejercicio 35: Programa Java para comprobar si el número aleatorio generado es par o impar

import java.util.Random;

class Main {
  public static void main(String[] args) {

    int min = 1;
    int max = 100;

    //Generating a random number
    Random r = new Random();
    int randomNumber = min + r.nextInt(max);
    System.out.println("Generated random number is: "+randomNumber);

    //Checking whether the number is odd or even

    if(randomNumber%2==0){
      System.out.println("The generated random number is even.");
    }else{
      System.out.println("The generated random number is odd.");
    }
        
  }
}


Ejercicio 36: Programa Java para calcular el número de contenedores necesarios

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("How many Lego bricks do we have? Choose an odd number between 50 and 100: ");
    int amountOfBricks = Integer.parseInt(sc.nextLine());

    System.out.println("How many Lego blocks fit in one container? Choose an even number between 5 and 10: ");
    int containerCapacity = Integer.parseInt(sc.nextLine());

    int noOfFullContainers = amountOfBricks/containerCapacity;
    int noOfTotalContainers;

    int noOfBlocksInNotFullContainers = amountOfBricks%containerCapacity;

    if(noOfBlocksInNotFullContainers!=0){
      noOfTotalContainers = noOfFullContainers + 1;
    }else{
      noOfTotalContainers = noOfFullContainers;
    }
    
    System.out.println("No of full containers we have: "+noOfFullContainers);
    System.out.println("No of total containers we have: "+noOfTotalContainers);
    System.out.println("No of blocks in the container that is not completely full: "+noOfBlocksInNotFullContainers);
        
  }
}


Ejercicio 37: Programa Java para calcular impuestos

import java.math.BigDecimal;    

class Main {
  public static void main(String[] args) {

    double netValue = 9.99;
    double VAT = 23.0;

    //calculating grossValue
    double grossValue = netValue + (VAT*netValue/100);
    System.out.println("The gross value is: "+grossValue);

    // multiplying the value by 10000
    double grossValue10000 = grossValue * 10000;
    System.out.println("The gross value for 10000 units is: "+grossValue10000);

    // calculating price excluding VAT 23%
    double excludingVAT = grossValue10000 - (VAT*grossValue10000/100);
    System.out.println("The value for 10000 units excluding VAT is: "+excludingVAT);

    // doing the same operations using BigDecimal instead of double
     System.out.println("\n----Using BigDecimal instead of double----\n");
       
    BigDecimal netValue_big = new BigDecimal("9.99");
    BigDecimal VAT_big = new BigDecimal("23.0");
    BigDecimal HUNDRED = new BigDecimal("100");
    BigDecimal TenThousand = new BigDecimal("10000");

    //calculating grossValue
    BigDecimal grossValue_big = netValue_big.add(VAT_big.multiply(netValue_big.divide(HUNDRED)));
    System.out.println("The gross value is: "+grossValue_big);
    
    // multiplying the value by 10000
    BigDecimal grossValue10000_big = grossValue_big.multiply(TenThousand);
    System.out.println("The gross value for 10000 units is: "+grossValue10000_big);
    
    // calculating price excluding VAT 23%
    BigDecimal excludingVAT_big = grossValue10000_big.subtract(VAT_big.multiply(grossValue10000_big.divide(HUNDRED)));
    System.out.println("The value for 10000 units excluding VAT is: "+excludingVAT_big);


  System.out.println("\nThe accuracy is higher when we use BigDecimal instead of double");
    
  }
}


Ejercicio 38: Calcular el IMC con Java

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    float height, weight, bmi;
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the height (in inches): ");
    height = s.nextFloat();
    System.out.println("Enter the weight (in pounds): ");
    weight = s.nextFloat();
    bmi = (float)(weight / Math.pow(height, 2) * 703);

    System.out.println("The BMI is: "+bmi);

    if(bmi<16.00)
      System.out.println("starvation");
    else if(bmi>=16.00 && bmi <= 16.99)
      System.out.println("emaciation");
    else if(bmi>=17.00 && bmi <= 18.49)
      System.out.println("underweight");
    else if(bmi>=18.50 && bmi<=22.99)
      System.out.println("normal, low range");
    else if(bmi>=23.00 && bmi<=24.99)
      System.out.println("normal, high range");
    else if(bmi>=25.00 && bmi<=27.49)
      System.out.println("overweight, low range");
    else if(bmi>=27.50 && bmi<=29.99)
      System.out.println("overweight, high range");
    else if(bmi>=30.00 && bmi<=34.9)
      System.out.println("1st degree obesity");
    else if(bmi>=35.00 && bmi<=39.90)
      System.out.println("2nd degree obesity");
    else
      System.out.println("3rd degree obesity");
  
    }
}


Ejercicio 39: Programa Java para hallar la suma de números pares

class Main {
  public static void main(String[] args) {
      int sum=0;
    
      for(int i=1;i<=100;i++){
        if(i%2==0){
          sum = sum + i;
        }
      }

      System.out.println("The sum of even numbers from 1-100 is: "+sum);
    
    }
}


Ejercicio 40: Programa Java para encontrar los números más grandes y más pequeños a partir de números aleatorios

import java.util.Random;

class Main {
  public static void main(String[] args) {
    int min = 1, max=100;
    int largest=0;
    int smallest=100;
    int i = 1;
    
    while(i<=10){
      //Generating a random number
      Random r = new Random();
      int randomNumber = min + r.nextInt(max);
      System.out.println("Generated random number is: "+randomNumber);
      if(randomNumber>largest){
        largest = randomNumber;
      }
      if(randomNumber<smallest){
        smallest = randomNumber;
      }
      i++;
    }
    
    System.out.println("\n");
    System.out.println("The smallest number is: "+smallest);
    System.out.println("The largest number is: "+largest);
    
  }
}