Java核心技术【卷一】——学习笔记(二)

要想通过控制台进行输人,首先需要构造一个 Scanner 对象,并与“ 标准输人流” System.in 关联。

Scanner in = new Scanner(System.in);

nextLine 方法将输入一行。

System.out.print("What is your name? ");
String name = in.nextLine();

要想读取一个单词(以空白符作为分隔符,) 就调用

String firstName = in.next();

要想读取一个整数, 就调用 nextlnt 方法

System.out.print("How old are you? ");
int age = in.nextInt();

在 printf 中,可以使用多个参数, 例如:

另外,还可以给出控制格式化输出的各种标志

"%,( .2f"使用分组的分隔符并将负数括在括号内

文件输入与输出
要想对文件进行读取, 就需要一个用 File 对象构造一个 Scanner 对象, 如下所示:

Scanner in = new Scanner(Paths.get("niyflle.txt") , "UTF-8") ;

如果文件名中包含反斜杠符号,就要记住在每个反斜杠之前再加一个额外的反斜杠:

“ c:\\mydirectory\\myfile.txt” 

读取一个文本文件时,要知道它的字符编码。如果省略字符编码, 则会使用运行这个 Java 程序的机器的“ 默认编码”。 这不是一个好主意,如果在不同的机器上运行这个程序, 可能会有不同的表现。

要想写入文件, 就需要构造一个 PrintWriter 对象。在构造器中,只需要提供文件名:

PrintWriter out = new PrintWriter('myfile.txt", "UTF-8") ;

如果文件不存在,创建该文件

若不指明文件的绝对位置,则默认为文件位于 Java 虚拟机启动路径的相对位置

String dir = System.getProperty("user.dir")

一个块可以嵌套在另一个块中

public static void main(String口 args)
{
int n;
{
int k;
int n; // Error can't redefine n in inner block
} // k is only defined up to here
}

break

带标签的 break语句, 用于跳出多重嵌套的循环语句

例:

Scanner in = new Scanner(System.in);
int n;
read_data:
while (. . .) // this loop statement is tagged with the label
for (. . .) // this inner loop is not labeled
{
    Systen.out.print("Enter a number >= 0: ");
    n = in.nextlntO;
    if (n < 0) // should never happen-can’t go on
        break read_data;
    // break out of readjata loop
    }// this statement is executed immediately after the labeled break
if (n < 0) // check for bad situation
{
    // deal with bad situation
}
else
{
    // carry out normal processing
}

Continue:

continue语句将控制转移到最内层循环的首部

 

for each 循环

for (variable : collection) statement

collection 这一集合表达式必须是一个数组或者是一个实现了 Iterable 接口的类对象(例如
ArrayList )

多维数组

另外, 如果知道数组元素, 就可以不调用 new, 而直接使用简化的书写形式对多维数组
进行初始化。例如:
int[][] magicSquare =
{
{16, 3, 2, 13},
{5, 10, 11, 8},
(9, 6, 7, 12},
{4, 15, 14, 1}
};
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值