Search code examples
javaloopscounterminimum

Mind helping a newcomer who hit their first speed bump?


I just started learning how to program in Java. Everything was going well so far.. That was until I came across this "bonus" question/problem our teacher gave us to solve as an additional "challenge".

Please click here to view the Question and the Sample input/output (it's an image file)

Note that I'm not allowed to use anything that wasn't taught or discussed in class. So, things like arrays, method overloading, parsing arrays to methods, parseInt, etc. gets ruled out.

Here's what I was able to come up with, so far:

import java.util.Scanner;
public class Test 
{
    public static void main(String[] args) 
    {
         int N; // number of lines of input
         double length1, length2, length3; // the 3 lengths
         double perimeter; // you get this by adding the 3 lengths
         double minperimeter=0; // dummy value

         Scanner input = new Scanner(System.in);
         System.out.println("Enter the number of triangles you have:");
         N = input.nextInt();

         System.out.println("Insert the lengths of the sides of these " +  
                            "triangles (3 real numbers per line):");

         for (int counter=0; counter<N; counter++)
         {
             length1 = input.nextDouble();
             length2 = input.nextDouble();
             length3 = input.nextDouble();

             perimeter = (length1 + length2 + length3);
             minperimeter = Math.min(perimeter,Math.min(perimeter,perimeter));
         }

         System.out.printf("The minimum perimeter is %.1f%n", minperimeter); 
    }
}

My 2 main problems are:

1) The program only stores and works with the 'last' input. The ones before it get replaced with this one. [update: solved this problem]

2) How do I print the "triangle number" in the final output? [update: solved this problem, too]

So, can anyone please help me come up with a solution that requires only the very basic learnings of Java? If it helps, this is the book we're using. Currently at Chapter 4. But we did learn about Math Class (which is in Chapter 5).

Update: Thank you so much for your replies, everyone! I was able to come up with a solution that does exactly what was asked in my question.


Solution

  • Math.min(perimeter,perimeter) will always give you perimeter. You probably wanted to do Math.min(perimeter,minPerimeter)

    Since it's a programming assignment is best if I don't give you the full solution to your second question, but your hint is, in the counter parameter of your for loop. Save that when you update minperimeter, so that you know in which iteration of the loop you found the minimum.

    Also, initialise your minPerimeter to 10000 or higher. If you start at 0, Math.Min will never be lower than that.