This is an exercise in using the compareTo methods you wrote in your Rectangle a
ID: 3882321 • Letter: T
Question
This is an exercise in using the compareTo methods you wrote in your Rectangle and Circle classes. You will see that we use compareTo for objects in exactly the same way we use > and < for primitives
Get doubles from input file. Output the biggest.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Lab8Num1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
File inFile = new File("lab8.in");
Scanner fileInput = null;
try {
fileInput = new Scanner(inFile);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
//Logger.getLogger(Lab10.class.getName()).log(Level.SEVERE, null, ex);
}
//get first number and make it the biggest;
double biggest;
double a;
biggest=fileInput.nextDouble();
//loop through the file
while(fileInput.hasNextLine())
{
//getting doubles and comparing with current "biggest"
a=fileInput.nextDouble();
if(a>(biggest))
biggest=a;
}
System.out.println("The biggest number was " + biggest);
}
}
Explanation / Answer
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); File inFile = new File("input.txt"); Scanner fileInput = null; try { fileInput = new Scanner(inFile); } catch (FileNotFoundException ex) { System.out.println("File not found"); //Logger.getLogger(Lab10.class.getName()).log(Level.SEVERE, null, ex); } //get first number and make it the biggest; Double biggest; Double a; biggest=fileInput.nextDouble(); //loop through the file while(fileInput.hasNextLine()) { //getting doubles and comparing with current "biggest" a=new Double(fileInput.nextDouble()); if(a.compareTo(new Double(biggest)) > 0) biggest=a; } System.out.println("The biggest number was " + biggest); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.