首页 课程 师资 教程 报名

Java控制台输出语句

  • 2022-12-12 12:28:22
  • 1161次 动力节点

1.控制台输出

System.out.println("哪吒javase讲的真好");

println源码:

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
} 
public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
} 
private void write(String s) {
	try {
		synchronized (this) {
			ensureOpen();
			textOut.write(s);
			textOut.flushBuffer();
			charOut.flushBuffer();
			if (autoFlush && (s.indexOf('
') >= 0))
				out.flush();
		}
	}
	catch (InterruptedIOException x) {
		Thread.currentThread().interrupt();
	}
	catch (IOException x) {
		trouble = true;
	}
}
private void newLine() {
	try {
		synchronized (this) {
			ensureOpen();
			textOut.newLine();
			textOut.flushBuffer();
			charOut.flushBuffer();
			if (autoFlush)
				out.flush();
		}
	}
	catch (InterruptedIOException x) {
		Thread.currentThread().interrupt();
	}
	catch (IOException x) {
		trouble = true;
	}
}

2.读取输入

package com.nezha.javase;
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        System.out.println("你是谁?");
        Scanner in = new Scanner(System.in);
        String name = in.nextLine();
        System.out.println("你几岁了?");
        int age = in.nextInt();
        System.out.println("我是"+name + ",我今年"+age+"岁啦!");
    }
}

3.格式化输出

(1)类型转换字符

b Boolean值 h 散列码(16进制)
c Unicode字符 s String
d 整数型(10进制) x 整数(16进制)
e 浮点数(科学计数) % 字符“%”
f 浮点数(10进制)    

(2)代码实例

package com.nezha.javase; 
public class Test {
    public static void main(String[] args) {
        int age = 29;
        String name = "哪吒"; 
        String info = String.format("My name is %s and my age is %d", name, age);
        System.out.println(info);
    }
}

(3)控制台输出

4.包

(1)什么是包

为了更好地组织类,Java 提供了包机制,用于区别类名的命名空间。

(2)包的作用

把功能相似或相关的类或接口组织在同一个包中,方便类的查找和使用。

如同文件夹一样,包也采用了树形目录的存储方式。同一个包中的类名字是不同的,不同的包中的类的名字是可以相同的,当同时调用两个不同包中相同类名的类时,应该加上包名加以区别。因此,包可以避免名字冲突。

包也限定了访问权限,拥有包访问权限的类才能访问某个包中的类。

(3)Java 包作用域

1)public

可以被任何类使用

2)private

只能被定义它的类使用

3)protected

可以被自己、同一包下的其它类、子类使用

4)默认作用域

可以被自己和同一包下的其他类使用

5.import关键字

(1)import

为了能够使用某一个包的成员,我们需要在 Java 程序中明确导入该包,使用 "import" 语句可完成此功能。

如果在一个包中,一个类想要使用本包中的另一个类,那么该包名可以省略。

(2)static import静态导入

jdk1.5里引入了“Static Import”机制,借助这一机制,可以用略掉所在的类或接口名的方式,来使用静态成员。static import和import其中一个不一致的地方就是static import导入的是静态成员,而import导入的是类或接口类型。

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交