- 1. 在控制台输出你好某某,例如:“Hello David!”。思考如何从控制台输入用户名David,然后再输出“Hello David!”(提示:使用Scanner对象接收控制台数据)
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
/*
* 1.java中叫main方法,c中叫main函数。
* 2.main方法是程序入口。
*/
System.out.println("Hello David!!!");
System.out.println("===============");
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String name=sc.nextLine();
System.out.println("Hello "+name+" !!!");
sc.close();
}
}
- 2. 在控制台输入两个数,然后输出两个数的四则运算(加减乘除)的结果。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入两个数:");
float number1 = sc.nextFloat();
float number2 = sc.nextFloat();
System.out.println("number1 + number2 = " + (number1 + number2));
System.out.println("number1 - number2 = " + (number1 - number2));
System.out.println("number1 * number2 = " + (number1 * number2));
if (number2 == 0.0) {
System.out.println("无法进行除法运算!!!");
}else {
System.out.println("number1 / number2 = " + (number1 / number2));
}
sc.close();
}
}
(欢迎您的意见和建议,感谢支持♥♥♥)