Jump to content

Programming Fundamentals/Arrays/Java

From Wikiversity

arrays.java

[edit | edit source]
// This program uses arrays to display temperature conversion tables 
// and temperature as an array subscript to find a given conversion.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/Java_Programming

import java.util.*;

class arrays 
{
    private static Scanner input = new Scanner(System.in);
    
    public static void main(String[] args) 
    {
        double[] c;
        double[] f;
        
        c = buildC(100);
        f = buildF(212);
        displayArray("C", c);
        displayArray("F", f);
        findTemperature(c, f);
    }

    private static double[] buildC(int size) 
    {
        double[] c = new double[size + 1];
        int index;
        double value;
        
        for (index = 0; index <= size; index += 1) 
        {
            value = (double) index * 9 / 5 + 32;
            c[index] = value;
        }
        
        return c;
    }

    private static double[] buildF(int size) 
    {
        double[] f = new double[size + 1];
        int index;
        double value;
        
        for (index = 0; index <= size; index += 1) 
        {
            value = (double) (index - 32) * 5 / 9;
            f[index] = value;
        }
        
        return f;
    }

    private static void displayArray(String name, double[] array) 
    {
        int index;
        
        for (index = 0 ; index <= array.length - 1 ; index += 1) 
        {
            System.out.println(name + "[" + index + "] = " + array[index]);
        }
    }

    private static void findTemperature(double[] c, double[] f) 
    {
        int temp;
        int size;
        
        size = minimum(c.length, f.length);
        do 
        {
            System.out.println("Enter a temperature between 0 and " + 
                Integer.toString(size - 1));
            temp = input.nextInt();
        } while (temp < 0 || temp > size - 1);
        System.out.println(Integer.toString(temp) + 
            "° Celsius is " + c[temp] + "° Fahrenheit");
        System.out.println(Integer.toString(temp) + 
            "° Fahrenheit is " + f[temp] + "° Celsius");
    }

    private static int minimum(int value1, int value2) 
    {
        int result;
        
        if (value1 < value2)
        {
            result = value1;
        }        
        else
        {
            result = value2;
        }

        return result;
    }
}

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Java compiler / interpreter / IDE.

See Also

[edit | edit source]