CraZieR CraZieR - 2 months ago 17
Java Question

Getting double input from java.util.Scanner

How do I get this program to work? When I try to type in the same three numbers such as 3 3 3, the program doesn't run.

import java.util.Scanner;

public class Triangles
{

//Variables
double a = 0;
double b = 0;
double c = 0;

public static void main(String[] args)
{
String choice;
Scanner a = new Scanner(System.in);
Scanner b = new Scanner(System.in);
Scanner c = new Scanner(System.in);

//1.User inputs the sides of a triangle
System.out.println("Please enter the sides of the triangle:");
choice = a.nextLine();
choice = b.nextLine();
choice = c.nextLine();
if(choice.equals(a==b&&b==c&&c==a))
{
System.out.println("The triangle is a equilateral triangle");
}
}
}

Answer Source

you only need to use one scanner, and call Scanner.nextDouble() 3 times. This way the data type you get from the Scanner will match the type of a, b, and c (i.e. double)

public static void main(String[] args) 
{
  double a, b, c;
  Scanner s = new Scanner(System.in);

  //1.User inputs the sides of a triangle
  System.out.println("Please enter the sides of the triangle:");
  a = s.nextDouble();
  b = s.nextDouble();
  c = s.nextDouble();
  if(a==b && b == c)
  {
    System.out.println("The triangle is a equalateral triangle");
  }

}

if you declare a, b, and c as int's instead of double (i.e. if you don't need decimal values) you can use nextInt() instead of nextDouble(). You will need to either declare a, b, and c as static, or declare them within the main() method.


Even better would be to abstract that logic into a method like boolean isEqualateral(double a, double b, double c), or boolean isEqualateral(Triangle t).. then just instantiate a Triangle object from within main and call the tests appropriately:

class Triangle{
double a, b, c;

public Triangle(double a, b, c)
{
   this.a = a; this.b = b; this.c = c;
}

public boolean isEqualateral()
{
   if (this.a == this.b && this.b == this.c)
      return true;
   return false;
}

public static void main(String[] args) 
{
  Scanner s = new Scanner(System.in);

  //1.User inputs the sides of a triangle
  System.out.println("Please enter the sides of the triangle:");
  a = s.nextDouble();
  b = s.nextDouble();
  c = s.nextDouble();

  Triangle t = new Triangle(a, b, c);
  if (t.isEqualateral())
    System.out.println("The triangle is a equalateral triangle");
}

}

now we're doing object oriented programming. :-)