Java homework part 4.

Java homework part 4.

Java

Won't be splitting these into two parts. I'll just write some shorter descriptions on what each program does. This week the first five exercises are about arrays and the next five are about methods. Had no difficulty doing the first five I found arrays quite simple. I ended up struggling with the method exercises. I was stuck on the second to last one for a while and had to ask a friend for some help. The solution ended up being really simple. I'll go in to more detail before the exercise.

1/10

The program feeds user input into an array until the input is -999 and then prints the array out.

 

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

public class Lampotilat {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final int MAX = 100;
        int temperature = 0;
        int[] temperatures = new int[MAX];
        int amount = 0;
        
        Scanner input = new Scanner(System.in);
        System.out.print("Anna lämpötila: ");
        temperature = input.nextInt();
        
        while(temperature != -999) {
            if(amount < MAX) {
            temperatures[amount] = temperature;

            System.out.print("Anna lämpötila: ");
            temperature = input.nextInt();
            amount++;
            }
        }
        System.out.print("Annoit lämpötilat: ");
        Arrays.sort(temperatures, 0, amount);
        for (int i = 0; i < amount; i++){
            System.out.print(temperatures[i] + " ");
        }
        
    }

}

2/10

Reads license plates from user input. The twist here was usin a string input and making the first three letters upper case.


public class Rekisterinumerot {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final int MAX = 10;
        String[] licenses = new String[MAX];
        String licensePlate = "";
        int amount = 0;
        Scanner input = new Scanner(System.in);

        while(!licensePlate.equals("-")){
        String CapLetters = licensePlate.substring(0).toUpperCase();

        licenses[amount] = CapLetters;
        if(amount < MAX) {
            
            System.out.print("Anna rekisterinumero (-lopettaa): ");
            licensePlate = input.nextLine().trim();
            amount++;
            }
        else {
            System.out.print("Ei enää rekisterinumeroita");
        }
        }
        System.out.print("Rekisterinumerot ovat: ");
            for(int i = 0; i < amount; i++) {
                System.out.println(licenses[i] + " ");
            }

    }

}

3/10

Again user input into an array and then counts all numbers input together and counts a salary based off the amount of hours worked per day and days the user said they worked.

 

import java.util.Scanner;
import java.text.DecimalFormat;

public class Palkkalaskuri {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        DecimalFormat f = new DecimalFormat("0.00");
        
        final int MAX = 100;
        double HourlySalary = 0;
        int DayAmount = 0;
        int[] hours = new int[MAX];
        int hour = 0;
        int amount = 0;
        int fullHours = 0;
        
        System.out.print("Anna tuntipalkkasi: ");
        HourlySalary = input.nextDouble();
        System.out.print("Monenko päivän tuntimäärät annat: ");
        DayAmount = input.nextInt();
        for (int i = 0; i < DayAmount; i++) {
            System.out.print("Anna tuntien määrä päivässä: ");
            hour = input.nextInt();
            hours[amount] = hour;
            fullHours = fullHours + hour;
            amount++;
        }
        
        System.out.println("Tunteja yhteensä: " + fullHours);
        System.out.println("Bruttopalkkasi: " + f.format(fullHours*HourlySalary));
        System.out.print("Annoit tunnit: ");
        for (int b = 0; b < DayAmount; b++ ) {
            System.out.print(hours[b] + " ");
              }
    }

}

4/10

The user puts in information about their water usage and then the program calculates the amount of water used per month. I made a mistake on the print portion of the exercise. Couldn't figure out how to make the program print the divisions in a loop. So I made this my solution.

 

import java.util.Scanner;
public class Vedenkulutus {

    public static void main(String[] args) {
    
        int StartPoint = 0;
        int months = 6;
        int[] Waterusage = new int[months];
        int UsedWater = 0;
        int amount = 0;
        int fullamount = 0;
        
        Scanner input = new Scanner(System.in);
        
        System.out.print("Anna vesimittarin alkulukema: ");
        StartPoint = input.nextInt();
        
        for(int i = 0; i < months; i++) {
            System.out.print("Anna " +(i+1) +  ". vesimittarin " + "lukema: ");
            UsedWater = input.nextInt();

            Waterusage[amount] = UsedWater;
            fullamount = fullamount + UsedWater;
            amount++;
        }
        

            System.out.println("Kuukauden 1 kulutus oli " + (Waterusage[0]-StartPoint));
            System.out.println("Kuukauden 2 kulutus oli " + (Waterusage[1]-Waterusage[0]));
            System.out.println("Kuukauden 3 kulutus oli " + (Waterusage[2]-Waterusage[1]));
            System.out.println("Kuukauden 4 kulutus oli " + (Waterusage[3]-Waterusage[2]));
            System.out.println("Kuukauden 5 kulutus oli " + (Waterusage[4]-Waterusage[3]));
            System.out.println("Kuukauden 6 kulutus oli " + (Waterusage[5]-Waterusage[4]));
        


    }
}

5/10

The program counts stuff off a minigolf game. It calculates an average score from the inputs, it figures out the smallest score and the largest score that there were and then it counts how many scores were below and above the average score.

 

import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;

public class MinigolfTilasto {

    public static void main(String[] args) {
        // TODO Auto-generated method stubi
        int round = 0;
        final int MAX = 100;
        Scanner input = new Scanner(System.in);
        DecimalFormat f = new DecimalFormat("0.00");
        int[] UserScores = new int[MAX];
        int UserScore = 0;
        int amount = 0;
        double AllPoints = 0;
        double averagePoints = 0;
        int SmallerAverage = 0;
        int LargerAverage = 0;
        
        System.out.print("Anna pelaajien lukumäärä: ");
        round = input.nextInt();
        for(int i = 0; i < round; i++) {
            System.out.print("Anna pelaajan " + (i+1) + ". tulos: ");
            UserScore = input.nextInt();
            UserScores[amount] = UserScore;
            AllPoints = AllPoints + UserScore;
            amount++;
        }
        Arrays.sort(UserScores,0, amount);
        averagePoints = AllPoints/round;
        System.out.println("Pelien keskiarvo oli " + f.format(averagePoints));
        for(int b = 0; b < amount; b++) {
            if(UserScores[b] < averagePoints) {
                SmallerAverage++;
            }
            else if(UserScores[b] > averagePoints){
                LargerAverage++;
            }
            }
        
        System.out.println("Pienin peli oli " + UserScores[0] + "\nSuurin peli oli " + UserScores[(round-1)]);
        System.out.print(SmallerAverage +  " pelaajalla oli keskiarvoa pienempi tulos");
    }

}

Methods

Method names and some variables were defined on the instructions so they will be in Finnish and some solutions will sometimes a little silly.

6/10

The program counts a governmental compensation on medical bills based off the time the user spent in the doctors office.

laakarikorvaus

 

import java.util.Scanner;
import java.text.DecimalFormat;

public class Laakarikorvaus {
    
    public static double laskeKorvaus(int kesto) {
        double compkesto = kesto;
        double compensation = 0;
        if (compkesto < 10) {
            compensation = 8.0;
            return compensation;
        }
        else if(compkesto < 20 && compkesto > 10){
            compensation = 11.0;
            return compensation;
        }
        else if(compkesto > 20 && compkesto < 30){
            compensation = 13.5;
            return compensation;
        }
        return 0;
        
    }
    
    public static void main(String[] args) {
        int kesto = 0;
        
        Scanner input = new Scanner(System.in);
        DecimalFormat f = new DecimalFormat("0.00");
        System.out.print("Anna käynnin kesto: ");
        kesto = input.nextInt();
        System.out.print("Kestoltaan " + kesto + " minuutin yleislääkärikäynnistä kelakorvaus on " +
        (f.format(laskeKorvaus(kesto)) + " euroa"));
        

    }

}

7/10

Counts gasoline spent per 100 kilometers. The exercise had us use four methods. One asks the kilometers driven, one ask how much gas the user put in, one counts the gas used per 100 km and one has the print method in it.

 

import java.util.Scanner;
import java.text.DecimalFormat;

public class Kulutus {
    
    public static int kysyKilometrit() {
        
        int AmountDriven = 0;
        
        Scanner klms = new Scanner(System.in);
        
        System.out.print("Anna ajetut kilometrit: ");
        AmountDriven = klms.nextInt();
        return AmountDriven;
    //    return AmountDriven;
        
    }
    public static int kysyTankkaus() {
        int GasAmount = 0;
        Scanner gas = new Scanner(System.in);
        System.out.print("Anna tankattu määrä: ");
        GasAmount = gas.nextInt();
        return GasAmount;
    }
    public static double laskeKulutus(int kilometrit, int tankattu) {
        if (kilometrit != 0 && tankattu != 0){
        double CountGas =  tankattu;
        double CountKlm =  kilometrit;
        double lopputulos = (CountGas / CountKlm) *100;
        return lopputulos;
        }
        return 666;
    }
    public static void naytaKulutus(double lopputulos){
        DecimalFormat f = new DecimalFormat("0.00");

        System.out.print("Kulutus/100km on " +  (f.format(lopputulos)) + " litraa");
    }

    public static void main(String[] args) {
        int kilometrit = kysyKilometrit();
        int tankattu = kysyTankkaus();
        DecimalFormat f = new DecimalFormat("0.00");
        double lopputulos = laskeKulutus(kilometrit, tankattu);
        naytaKulutus(lopputulos);
    }

}

8/10

The program counts how much the user gets paid while sick. The result is based off user input once again.

sairaspaiva

 

import java.util.Scanner;
import java.text.DecimalFormat;

public class Sairaspaivaraha {
    
    //kaksi oma metodia
    
    //laskuri + tarkistus

    public static double askPay() {
        double UserPay = 0;
        
        Scanner pay = new Scanner(System.in);
        System.out.print("Anna vuositulosi: ");
        UserPay = pay.nextDouble();
        return UserPay;
    }
    
    public static double calculatePay(double UserSalary) {
        double CompensationAmount = 0;
        
            if(UserSalary >= 1399 && UserSalary <= 36419) {
            CompensationAmount = (0.7 * UserSalary)/300;
                return CompensationAmount;
                }
            else if(UserSalary >= 36420 && UserSalary <= 56032){
                CompensationAmount = 84.98 + (0.4 * (UserSalary - 36419))/300;
                return CompensationAmount;
            }
            else if (UserSalary > 56032) {
                CompensationAmount = 111.13 + (0.25 *(UserSalary - 56032))/300;
                return CompensationAmount;
            }
    
            else {
                return 0;
            }
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DecimalFormat f = new DecimalFormat("0.00");
        double UserSalary = askPay();
        System.out.print("Vuosituloilla " +(f.format(UserSalary)) + " sairaspäiväraha on " +  (f.format(calculatePay(UserSalary))) + "euroa/päivä.");
        
    }

}

9/10

This is the one I mentioned before where I ended up needing some help. I got stuck on the idea that while calling the method that I should be returning the array that was asked in one of the methods. Rather than returning the array I should have been returning the amount my loop "looped around" to get the number I needed for a variable. A simple fix but I guess I got sort of "codeblind". The program itself just expands on one of the previous exercises. It asks for temperatures. Puts them in an array, sorts them and then prints them out.

lämpötila99

 

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

public class Lampotilat {
    
    public static int kysyLampotilat(int[] lampotilat, final int MAX) {
        Scanner input = new Scanner(System.in);
          int temp, count = 0;
            for(int i = 0; i < MAX; i++) {
                System.out.print("Anna lämpötila: ");
                temp = Integer.parseInt(input.nextLine());
                if(temp != -999) {
                    lampotilat[i] = temp;
                    count++;
                } else {
                    break;
                }
            }
            int[] tempArray = new int[count];
            lampotilat = tempArray;
            return count;
    }
    
    public static void naytaLampotilat(int[]lampotilat, int lkm) {
         Arrays.sort(lampotilat, 0, lkm);
        System.out.print("Annoit lämpötilat: ");
        for (int i = 0; i < lkm; i++){
            System.out.print(lampotilat[i] + " ");
        }
        
    }
    

    public static void main(String[] args) {
        final int MAX = 100;
        int[] lampotilat = new int[MAX];
        
        
        int lkm = kysyLampotilat(lampotilat, MAX);
        
        naytaLampotilat(lampotilat, lkm);
         
    }

}

10/10

This one asks for some blood types, puts them in an array, counts how many types the user put in. The program also asks for a blood type from the user and figures out how many of that type is in the array.

bloodtype

 

import java.util.Scanner;

public class Veriryhma {
    public static int askBloodType(String[] allBloodtypes) {
        final int MAX = 100;
        String[] bloodtype = new String[MAX];
        String myBlood = "";
        int amount = 0;
        
        Scanner blood = new Scanner(System.in);
            
            while (!myBlood.equals("-")){
                String CapLetters = myBlood.substring(0).toUpperCase();
                allBloodtypes[amount] = CapLetters;
                System.out.print("Anna veriryhmä (- lopettaa): ");
                myBlood = blood.nextLine().trim();    
                amount++;
                
            }
            allBloodtypes = bloodtype;
            return amount;
            
    }
        
    public static int sortThrough(int lkm, String[] allBloodtypes, String whichBlood) {
        Scanner input = new Scanner(System.in);
        String UserBlood;
        int round = lkm;
        int userAmount = 0;
        UserBlood = whichBlood;
        
        for(int i = 0; i < round; i++) {
            if(UserBlood.equals(allBloodtypes[i])){
                userAmount++;
            }
        }
        return userAmount;
    }
        
    
    public static void main(String[] args) {
        final int tempMax = 100;
        int lkm = 0;
        int searchResult = 0;
        String whichBlood;
        String[] allBloodtypes = new String[tempMax];
        
        Scanner blut = new Scanner(System.in);
        
        lkm = askBloodType(allBloodtypes);
        
        System.out.println("Luovutuksia oli yhteensä " + (lkm-1));
        System.out.print("Minkä veriryhmän luovutusten määrän haluat tietää: ");
        whichBlood = blut.nextLine();
        searchResult = sortThrough(lkm, allBloodtypes, whichBlood);
        System.out.print("Veriryhmän " + whichBlood + " luovutuksia oli "  + searchResult);

    }
    
}

Sources:

  • image from: https://svgsilh.com/image/311945.html