The following are the two programming questions from the first exam from this pa
ID: 662803 • Letter: T
Question
The following are the two programming questions from the first exam from this past spring, to give you a good idea of what to expect, programming-wise, on the exam in this class.
1) Write a complete single-class program (that is, a class with main in it and everything that's needed to compile and run the program) that asks the user for an int and a String (of any number of words) to be input from the console and then writes that String to the console as many times as the int the user entered (each time on a separate line).
2) Write a complete class (not an executable program, just the class) called RightTriangle.
Include:
instance variables for the base and height of the triangle.
a zero-parameter constructor that creates a RightTriangle with a base and height of 1
a two-argument constructor that creates a RightTriangle with a base and height specified by the arguments
accessors and mutators for the base and height. Only set the base or height if the value passed in is >0. Take no action otherwise.
a method to get the area of the triangle (base*height/2)
a toString method that returns a string describing the triangle (including base and height).
Explanation / Answer
Answer 1) import.java.util.Scanner;
public class PrintString {
public static void main (String [] args) {
String input ; int numberOfTimes;
int i=0;
Scanner in = new Scanner (System.in);
System.out.println("Enter the number, the times you want to print your string ");
int numberOfTimes = in.nextInt();
System.out.println("Please enter a the string you want to print");
System.out.println("?");
String input = Scan.nextLine();
for (i=0; i<numberOfTimes; i++)
{
System.out.println(input);
System.out.println(" ");
}
}
}
Answer 2) class RightTriangle
{ public double base;
public double height;
public double Area;
public double Area () {
return( (base*height)/2); ;
}
public void toString(String value)
{
value= "Base and height " ;
}
RightTraingle()
{
base=1;
height=1;
}
RightTriangle(double b, double h)
{
base = b; height = h;
}
public static void main()
{ RightTriangle righttriangle1,righttriangle2 ;
String str1= "";
righttriangle1 = new RightTriangle ();
righttriangle1 .toString(str1);
System .out.println("Base of triangle: " + base);
righttriangle2 = new RightTriangle (20.0, 10.0);
righttriangle2 .toString(str1);
System .out.println("Height of triangle: " + height);
System .out.println("Area of triangle: " + righttriangle1. Area );
System .out.println("Area of triangle: " + righttriangle2. Area );
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.