通过一个例题:
输入说明:
输入double,然后输入3个浮点数。**输出:**从左到右依次输出3个double(均保留2位小数输出,宽度为5),三个格式依次为:右侧填充空格,左侧填充空格,直接输出
输入int,然后输入3个整数(以1个或多个空格分隔)。**输出:**将3个整数相加后输出。
输入str,然后输入3个字符串。**输出:**去除空格,然后倒序输出3个字符。
输入line,然后输入一行字符串。**输出:**转换成大写后输出。 如果输入不是上面几个关键词,输出:输出other。
输出说明
choice=你输入选项 该选项对应的输出内容
输入样例:
double
1.578 3.0 3.14259
line
aaaaaaaaaa
int
1 2 3
str
321 654 987
line
dddddddddd
end
输出样例:
choice=double
1.58 , 3.00,3.14
choice=line
AAAAAAAAAA
choice=int
6
choice=str
987654321
choice=line
DDDDDDDDDD
choice=end
other
AC
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String choice = scanner.next();
System.out.println("choice=" + choice);
if (choice.equals("double")) {
double a, b, c;
a = scanner.nextDouble();
b = scanner.nextDouble();
c = scanner.nextDouble();
System.out.printf("%-5.2f,%5.2f,%.2f\n", a, b, c);
} else if (choice.equals("int")) {
int a, b, c;
a = scanner.nextInt();
b = scanner.nextInt();
c = scanner.nextInt();
System.out.println(a + b + c);
} else if (choice.equals("str")) {
scanner.nextLine();
String str = scanner.nextLine();
String[] arr = str.split("\\s+");
//用str.split(" ")也行
for (int i = 2; i >= 0; i--) {
System.out.print(arr[i]);
}
System.out.println();
} else if (choice.equals("line")) {
scanner.nextLine();
String str = scanner.nextLine();
System.out.println(str.toUpperCase());
} else {
System.out.println("other");
}
}
}
}
一、小数四舍五入成整数的方法:
java中Math类提供的四舍五入方法:Math.ceil()、Math.floor()和Math.round().
下面来介绍将小数值舍入为整数的几个方法:Math.ceil()、Math.floor()和Math.round()。 这三个方法分别遵循下列舍入规则:
(1)Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
(2)Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
(3)Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数(这也是我们在数学课上学到的舍入规则)。
下面来看几个例子:
(向上舍入):
Math.ceil(25.9) //26
Math.ceil(25.5) //26
Math.ceil(25.1) //26
Math.ceil(25.0)//25
(标准舍入):
Math.round(25.9) //26
Math.round(25.5) //26
Math.round(25.1) //25
(向下舍入):
Math.floor(25.9) //25
Math.floor(25.5) //25
Math.floor(25.1) //25
用0补位
System.out.printf("%04d",12); //0012
System.out.println(String.format("%.2f", ans[i]));
System.out.printf("%-5.2f,%5.2f,%.2f\n", a, b, c);