java实现了trim()和IsEmpty()来编写代码
我有这个密码:
package rr.fr.oo.lab.proc1;
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
if(args.length != 2 && args.length != 0){
System.err.println("Invalid number of arguments was provided.");
System.exit(1);
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
double area = area(a,b);
double perimeter = perimeter(a,b);
System.out.println("You have specified a rectangle of width " + a + " and height "
+ b + ". Its area is " + area + " and its perimeter is " + perimeter);
}
double x,y;
if(args.length == 0){
Scanner sc = new Scanner(System.in);
System.out.printf("Please provide width: ");
x = scanner(sc);
while(x < 0){
System.out.printf("The width must not be negative.\n");
System.out.printf("Please provide width: ");
x = scanner(sc);
}
System.out.printf("Please provide height: ");
y = scanner(sc);
while(y < 0){
System.out.printf("The width must not be negative.\n");
System.out.printf("Please provide height: ");
y = scanner(sc);
}
sc.close();
double area = area(x,y);
double perimeter = perimeter(x,y);
System.out.println("You have specified a rectangle of width " + x + " and height "
+ y + ". Its area is " + area + " and its perimeter is " + perimeter);
}
}
private static double area(double a, double b){
return a*b;
}
private static double perimeter(double a, double b){
return 2*(a+b);
}
private static double scanner(Scanner sc){
double number = sc.nextDouble();
return number;
}
}
我想知道如何使用trim和isEmpty方法来提高从系统输入读取的结果。 读完一行后,我想用trim清除所有空白。如果行是空的,我想打印这样的消息:“输入不能为空”
# 1 楼答案
你可以自己全力以赴,比如:
但使用扫描仪要方便得多。捕捉一些输入事件,比如空行或ctrl-D(EOF),通常不值得这么麻烦