Skip to content
Advertisement

Subtraction loops in java

I am new to java and am stuck on this challenge. I am to calculate the state of water depending on the inputed temp and altitude. However, for every 300 metres (for altitude) the boiling point is to drop by 1 degree. I am confused as to how to make it a loop that will take one off for every three hundred rather than just removing one when it hits three hundred. This is what I have so far. EDIT: Thank you so much for the help! Didn’t even know if people used this website anymore but now I will use it all the time lol 😀

import java.util.Scanner;
public class WaterState
{
    public static void main(String[]args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the temperature then the altitude separated by one or more spaces");
        double temperature = scan.nextDouble();
        double altitude = scan.nextDouble();
        double bp = 100;
        if (temperature <= 0)
        {
            System.out.println ("Water is solid at the given conditions");
        }
        if (temperature >= 1 && temperature < 100)
        {
            System.out.println ("Water is liquid at the given conditions");
        }
        if (temperature >= 100)
        {
            System.out.println ("Water is gas at the given conditions");
        }
    }
}

Advertisement

Answer

Why do you think a loop is needed to calculate the boiling point? Think about it: given an altitude, return the boiling point of water. You can actually calculate the melting and boiling points with this info and then just check in which range you fall in.

import java.util.Scanner;
public class WaterState
{
    public static void main(String[]args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the temperature then the altitude separated by one or more spaces");
        double temperature = scan.nextDouble();
        double altitude = scan.nextDouble();

        double offset = (int)altitude / 300.0;
        double boilingPoint = 100 - offset;
        double freezePoint = 0 - offset;
        if (temperature <= freezePoint)
        {
            System.out.println ("Water is solid at the given conditions");
        }
        if (temperature > freezePoint  && temperature < boilingPoint)
        {
            System.out.println ("Water is liquid at the given conditions");
        }
        if (temperature >= boilingPoint)
        {
            System.out.println ("Water is gas at the given conditions");
        }
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement