gpt4 book ai didi

java - 实现 trim() 和 IsEmpty() 来编码

转载 作者:太空宇宙 更新时间:2023-11-04 13:20:22 25 4
gpt4 key购买 nike

我有这个代码:

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来改善从系统输入读取的结果。读完一行后,我想用修剪清除所有空白。如果行为空,我想打印如下消息:“输入不能为空”。

最佳答案

你可以全力以赴自己完成这一切,就像这样:

private static double readDouble( BufferedReader kbd, String prompt ){
String line = null;
double res = 0;
while( true ){
System.out.print( prompt + " " );
try {
line = kbd.readLine();
} catch( IOException ioe ){
System.out.println( ioe.getMessage() );
throw new IllegalStateException();
}
if( line == null ){
System.out.println( "input terminated" );
continue;
}
line = line.trim();
if( line.length() == 0 ){
System.out.println( "input line can't be blank" );
continue;
}
try {
res = Double.parseDouble( line );
} catch( NumberFormatException nfe ){
System.out.println( "error in number" );
continue;
}
if( res < 0 ){
System.out.println( "input must not be negative" );
continue;
}
return res;
}
}

但是使用扫描仪要方便得多。捕获一些输入事件(例如空行或 ctrl-D (EOF))通常不值得这么麻烦。

关于java - 实现 trim() 和 IsEmpty() 来编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33119747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com