Programming Fundamentals/Arrays/Java: Difference between revisions

From Wikiversity
Jump to navigation Jump to search
Content deleted Content added
Creating
(No difference)

Revision as of 14:44, 18 February 2017

arrays.java

// This program uses arrays to display temperature conversion tables 
// and temperature as an array subscript to find a given conversion.

import java.util.*;

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

    private static void buildC(double[] c) 
    {
        int index;
        
        for (index = 0 ; index <= c.length - 1 ; index += 1) 
        {
            c[index] = (double) index * 9 / 5 + 32;
        }
    }

    private static void buildF(double[] f) 
    {
        int index;
        
        for (index = 0 ; index <= f.length - 1 ; index += 1) 
        {
            f[index] = (double) (index - 32) * 5 / 9;
        }
    }

    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 = getMinimumSize(c, f);
        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 getMinimumSize(double[] c, double[] f) 
    {
        int size;
        
        size = c.length;
        if (size > f.length) 
        {
            size = f.length;
        }
        
        return size;
    }
}

Try It

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