java使用System.out来表示标准输出设备,使用System.in来表示标准输入设备。java并不直接支持控制台输入,但是可以使用Scanner类创建它的对象,以读取来自System.in的输入。
Scanner input = new Scanner(System.in);
Scanner对象的方法:
方法 | 描述 |
nextByte() | 读取一个byte类型的整数 |
nextShort | 读取一个short类型的整数 |
nextInt() | 读取一个int类型的整数 |
nextLong() | 读取一个long类型的整数 |
nextFloat() | 读取一个float类型的数 |
nextDouble() | 读取一个double类型的数 |
next() | 读取一个字符串,该字符串在一个空白符之前结束 |
nextLine() | 读取一行文本,以回车键结束 |
代码1(求圆的面积):
public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print("Enter a number for radius: "); double radius = input.nextDouble(); double area = radius * radius * 3.1415926; System.out.println("The area for the circle of radius " + radius + " is " + area); } } /* Enter a number for radius: 23.45 The area for the circle of radius 23.45 is 1727.5696247214998 */
代码2(求输入三个数的平均值):
public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print("Enter three numbers: "); double num1, num2, num3, average; num1 = input.nextDouble(); num2 = input.nextDouble(); num3 = input.nextDouble(); average = (num1 + num2 + num3) / 3; System.out.println("The average of" + num1 + " " + num2 + " " + num3 + " is " + average); } }
java中使用final关键字表示一个变量是常量
String类型不是基本类型,而是引用类型。
可以进行字符串连接,使用“+”连接符,如果操作数之一不是字符串,非字符串值先转换为字符串,再与另一个字符串连接起来
“+=”也可以用于字符串
public class Main { public static void main(String args[]) { String message = "Welcome " + "to " + "java"; int i = 1, j = 2; String s = "Chapter" + 2; String s1 = "Supplement" + 'B'; System.out.println(message); //Welcome to java System.out.println(s); //Chapter2 System.out.println(s1); //SupplementB message += "and java is fun!"; System.out.println("i + j is " + i + j); //i + j is 12 System.out.println("i + j is " + (i + j)); //i + j is 3 } }
为从控制台读取字符串,调用Scanner对象上的next()方法:
public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.println("Enter three strings: "); String s1 = input.next(); String s2 = input.next(); String s3 = input.next(); System.out.println("s1 is " + s1); System.out.println("s2 is " + s2); System.out.println("s3 is " + s3); } }
next()方法读取以空白字符结束的字符串(' '、'\t'、'\f'、'\r'、'\n')
可以使用nextLine()方法读取一整行文本。nextLine()方法读取以按下回车键为结束标志的字符串:
public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.println("Enter a string: "); String s = input.nextLine(); System.out.println("The string entered is " + s); } }