Some Points of Class Definition, Variables.,Scanner(用类与对象的思想理解,及其陷阱。通过匿名对象来使用)

 

Class definition

When we type the name of clas:

The name should be started by capital and there is no white-space between words. (unless the word is required to be all capitals)

 

Variables

The declaration of variables is almost the same as C.

except for the constant variables:

we use the keyword: final in java for constat variables.

 

Recall different types of variables:

When declaring the float and long type, we should better add F or L

Just like C, we should notice if there is any difference between the result and factors of operation.

Don't forget the boolean type:

the boolean type only has true or false as value.

In this program, if it is true performance the relevant part:

 

Assignment conversion:

there are three ways to convert:

 

Reading input data(The Scanner class)

 

Ohter  some of the objects we can use in this package:

without the main method, the program cannot be run.

Assume we have created a Address class:


And we invoke it as below:

M
 

 

These manipulating objects in the computer’s heap memory.

Java handles memory using a garbage collector, when there is no variable storing a reference, then the object in
memory is marked for deletion by the garbage collector

 

用类与对象的思想来理解Scanner

在JAVA中 万物皆是类和对象

Scanner是一个引用类型

使用步骤:

1.导包 2.创建 3.使用 (具体可参考API文档)

若想只接收一个char,用如下代码(在next()方法之后加charAt(0)方法)

 

 Scanner里有许多方法用于接受不同类型的输入:

如next()接收字符串,但遇到空格或回车就停止接收(同时不会接收空格或回车)

nextLine()也接受字符串,同样遇到空格或回车就停止接收,但会接收空格或回车。

其他方法(如nextInt()等)与nextLine()一样,遇到空格或回车就停止接收,会接收空格或回车。

 

因此当next()等方法与nextLine()方法连用时,因为其它Scanner方法不取走空格或回车,导致空格或回车继续留在内存里。

此后当nextLine()方法被调用时,该方法会直接读取识别之前留下的空格或回车,导致其停止读取并运行下一行命令。

看起来的效果就好像Scanner方法没有被调用,编译器直接运行下一行代码一样。

解决方法:

在每个Scanner方法后面加nextLine(),如下(直接用正在使用的Scanner对象即可,不用再重写实例化一个Scanner)

 

通过匿名对象来使用Scanner:

匿名对象只有 new Xxxx 没有左边等号的部分,匿名对象只能用于只需要使用一次的对象里。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值