Skip to content

Instantly share code, notes, and snippets.

@jaohaohsuan
Created February 28, 2019 20:51
Show Gist options
  • Save jaohaohsuan/ab94d230df8c787168a8d9647a03ae17 to your computer and use it in GitHub Desktop.
Save jaohaohsuan/ab94d230df8c787168a8d9647a03ae17 to your computer and use it in GitHub Desktop.
week 3 lab
package assignment1;
import static java.lang.System.out;
import java.util.*;
public class Main {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
//question2();
question3();
}
public static String dash(int len) {
if(len > 0) {
return new String(new char[len]).replace('\0', '-');
} else {
return "";
}
}
// questions
// week 2 lab
public static void question2() {
out.print("Enter circle radius: ");
Double radius = 0.0;
try {
// read radius value from user input
radius = input.nextDouble();
} catch (Exception ex) {
out.println("invalid radius input");
out.printf("Exception type: %s\n",ex.getClass());
return;
}
Double diameter = radius * 2;
Double perimeter = diameter * Math.PI;
Double circleArea = Math.PI * radius * radius;
String columns = String.format("%-12s%-12s%12s", "Radius", "Perimeter", "Area");
String results = String.format("%-12s%-12.2f%12.2f", radius, perimeter, circleArea);
out.println(columns);
out.println(dash(columns.length()));
out.println(results);
}
// week 3 lab
public static void question3() {
Double score = 0.0;
while(true) {
out.print("Enter a score: ");
String userInput = input.nextLine().trim();
Boolean validNumber = userInput.matches("\\d*(.)?\\d*");
if(validNumber) {
score = Double.parseDouble(userInput);
String result = scoreRange(score);
if( result == "") {
out.println("Invalid score");
} else {
out.printf("The grade is %s.", result);
break;
}
} else {
out.println("Invalid score input");
}
}
}
private static String scoreRange(Double value) {
if(value >=0 && value < 50) {
return "D";
}
else if(value >= 50 && value < 70) {
return "C";
}
else if(value >= 70 && value < 80) {
return "B";
}
else if(value >= 80 && value <= 100) {
return "A";
}
else {
return "";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment