Question

In: Computer Science

package edu.depaul.triangle; import java.util.Scanner; /** * A class to classify a set of side lengths as...

package edu.depaul.triangle;

import java.util.Scanner;

/**

* A class to classify a set of side lengths as one of the 3 types

* of triangle: equilateral, isosceles, or scalene.

* If classification is not possible it emits an error message

*/

public class Triangle {

/**

* Define as private so that it is not a valid

* choice.

*/

private Triangle() {}

public Triangle(String[] args) {

//

// TODO: keep this simple. Constructors should not do a lot of work

//

}

// TODO: Add methods to validate input, and classify the triangle (if possible) here

private static String[] getArgs(Scanner s) {

System.out.println("press Enter by itself to quit");

System.out.println("enter 3 integers separated by space.");

String args = s.nextLine();

return args.split(" ");

}

public static void main(String[] a) {

try (Scanner scanner = new Scanner(System.in)) {

String[] args = getArgs(scanner);

// Loop until the user enters an empty line

while(args[0].length() !=0) {

//

// TODO: create a new Triangle here and call it

//

args = getArgs(scanner);

}

System.out.println("Done");

}

}

Write a Java program to determine types of triangles. The program reads 3 values from the standard input. The values represent the lengths of the sides of a triangle. The program prints a message to the standard output that indicates whether the triangle represented by the input is • an equilateral (all 3 sides are equal), or • an isosceles (exactly 2 of the 3 sides are equal), or • a scalene (all 3 sides are of different lengths) Expected behavior: a. The user enters 3 values at a prompt and presses return b. The values must be converted to integers. If they cannot be converted, the system displays an error. c. The valid values for these integers are values from 1 to and including 300. Any other integers should cause an error to be shown to the user. d. The values are delimited with spaces e. The system evaluates the results, shows either a triangle type or an error, then prompts for input again. f. When the user enters a blank line followed by return, the program ends. g. An error is shown whenever the user’s input cannot be interpreted as a triangle or when the handling of the input results in exception.

Solutions

Expert Solution

//program to classify the triangle based on entered side lengths with exception handling

import java.io.*;
import java.util.Scanner;


public class Triangle {

private Triangle() {}
  
public Triangle(String[] args) {
  
}

//function to classify the type of triangle
private static void classify(int a,int b,int c){
if(a==b && b==c)
System.out.println("Equilateral\n");
else if(a==b || b==c || a==c)
System.out.println("Isosceles\n");
else
System.out.println("Scalene\n");
}

//get the user input and split on space
private static String[] getArgs(Scanner s) {
  
       System.out.println("press Enter by itself to quit");
      
       System.out.println("enter 3 integers separated by space.");
      
       String args = s.nextLine();
      
       return args.split(" ");
  
}

//main function (program control starts from here)
public static void main(String[] arg)
   {
  
       try (Scanner scanner = new Scanner(System.in))
       {
      
           String[] args = getArgs(scanner);
          

           // Loop until the user enters an empty line
           int num1=0,num2=0,num3=0;
           while(args[0].length() !=0)
           {

//using try catch to handle exception on parseInt
               try
               {
                   num1 = Integer.parseInt(args[0]);
                   num2 = Integer.parseInt(args[1]);
                   num3 = Integer.parseInt(args[2]);
                   if(num1>0 && num1<=300 && num2>0 && num2<=300 && num3>0 && num3<=300)
                   {
                       // System.out.println(num1+"---"+num2+"---"+num3+"---");
                       classify(num1,num2,num3);
//calling classification function
                   }

else

{
System.out.println("Enter value between 1 and 300");
}
              
               }
               catch (NumberFormatException nfe)
               {

                   // nfe.printStackTrace();
                   System.out.println("ERROR!! Enter correct arguments(in digits only)");
               }

               args = getArgs(scanner);
           }
          
           System.out.println("Done");
  
       }
  
}
}


Related Solutions

Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner;...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner; public class Booolean0p {        public class BooleanOp {            public static void main(String[] args) {                int a = 0, b = 0 , c = 0;                Scanner kbd = new Scanner(System.in);                System.out.print("Input the first number: ");                a = kbd.nextInt();                System.out.print("Input...
I can't figure out why this won't run. //CryptographyTest.java //package cryptography; import java.util.Scanner; public class CryptographyTest...
I can't figure out why this won't run. //CryptographyTest.java //package cryptography; import java.util.Scanner; public class CryptographyTest {    public static void main(String[] args) { // create a scanner object to read from user Scanner s = new Scanner(System.in); // prompt user for input option while(true) { // loop till user say exit System.out.println("Select Option:"); System.out.println("1. Encrypt"); System.out.println("2. Decrypt"); System.out.println("3. Exit"); String input = s.nextLine(); // get user input int option = 0; try { // check for valid input option...
create code for deletestudentbyID Number for choice == 4 package courseecom616; import java.util.Scanner; import java.util.ArrayList; public...
create code for deletestudentbyID Number for choice == 4 package courseecom616; import java.util.Scanner; import java.util.ArrayList; public class CourseeCOM616 {        private String courseName;     private String[] studentsName = new String[1];     private String studentId;        private int numberOfStudents;        public CourseeCOM616(String courseName) {         this.courseName = courseName;     }     public String[] getStudentsName() {         return studentsName;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public String getStudentId() {         return studentId;    ...
TASK: Based upon the following code: import java.util.Scanner; // Import the Scanner class public class Main...
TASK: Based upon the following code: import java.util.Scanner; // Import the Scanner class public class Main {   public static void main( String[] args ) {     Scanner myInput = new Scanner(System.in); // Create a Scanner object     System.out.println("Enter (3) digits: ");     int W = myInput.nextInt();     int X = myInput.nextInt();     int Y = myInput.nextInt();      } } Use the tools described thus far to create additional code that will sort the integers in either monotonic ascending or descending order. Copy your code and...
import java.util.Random; import java.util.Scanner; public class Compass { // You will need to do the following:...
import java.util.Random; import java.util.Scanner; public class Compass { // You will need to do the following: // // 1.) Define a private instance variable which can // hold a reference to a Random object. // // 2.) Define a constructor which takes a seed value. // This seed will be used to initialize the // aforementioned Random instance variable. // // 3.) Define a static method named numberToDirection // which takes a direction number and returns a String // representing...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME =...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME = "bowler.txt"; public static void main(String[] args) throws FileNotFoundException { System.out.println("Reading Data from file"); Scanner fileReader = new Scanner(new File(FILE_NAME)); System.out.printf("%-20s%-10s%-10s%-10s%-10s\n", "Sample Data", "Game 1", "Game 2", "Game 3", "Average"); int bowler = 1; while (fileReader.hasNext()) { String scores[] = fileReader.nextLine().split("\\s+"); double average = Integer.parseInt(scores[0]) + Integer.parseInt(scores[1]) + Integer.parseInt(scores[2]); average /= 3; System.out.printf("%-20s%-10s%-10s%-10s%-10.2f\n", "Bowler " + bowler, scores[0], scores[1], scores[2], average); bowler += 1; }...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        } System.out.println(""+getAvg(new_stack));    }     public static int getAvg(Stack s) {        //TODO: Find the average of the elements in the...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
import java.util.Stack; import java.util.ArrayList; import java.util.Scanner; class TreeNode{ int data; ArrayList<TreeNode> children = new ArrayList<>(); TreeNode...
import java.util.Stack; import java.util.ArrayList; import java.util.Scanner; class TreeNode{ int data; ArrayList<TreeNode> children = new ArrayList<>(); TreeNode parent = null;    public TreeNode(int d){ data = d; }    public TreeNode addChild(int d){ TreeNode n = new TreeNode(d); n.setParent(this); children.add(n); return n; }    public ArrayList<TreeNode> getChildren(){ return children; }    public void setParent(TreeNode p){ parent = p; }    public TreeNode getParent(){ return parent; } } class Main { public static void main(String[] args)    {        Scanner scan...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT