Java入门学习笔记(三)

用户交互Scanner

import java.util.Scanner; JDK5的特性

Scanner s = new Scanner(System.in);

使用next()和nextLine()方法读取输入内容的区别:

import java.util.Scanner; 

public class Demo01 {
    public static void main(String[] args) {
      //创建一个scanner对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);
        System.out.print("用next方式输入:");

        //判断用户有没有输入字符串
        if(scanner.hasNext()){
            String str= scanner.next();
            System.out.println("输入的内容为:"+str);
        }
        scanner.close(); //注意:每次使用完IO接口后都要关闭,防止一直占用。
    }
}
用next方式输入:Hello World!
输入的内容为:Hello

next()方法遇到空字符值时停止读取,故只读取了Hello就停止读取了

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        //创建一个scanner对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);
        System.out.print("用nextline方式输入:");

        //判断用户有没有输入字符串
        if (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            System.out.println("输入的内容为:" + str);
        }
        scanner.close();
    }
}
用nextline方式输入:Hello World!
输入的内容为:Hello World!

nextLine()方法遇到回车符值时才停止读取,故读取到!后的回车键时才停止读取。
nextLine()用的还是比较多。

scanner.hasNextInt():判读输入的内容是否是int类型,判断其他数据类型,将Int替换即可。

顺序结构、选择结构、循环结构

if选择结构
if(){

}else if(){

}else{

}
switch选择结构

switch支持String类型了
case标签必须为字符串常量或字面量

switch(){
    case 'A':
        System.out.printLn('A');
        break;  //不加break则把后面结果都输出(case穿透现象)
    case 'B':
        System.out.printLn('B');
    default:
        System.out.printLn('default');
    
}
while和doWhile

while()是不满足条件时,就不执行。
doWhile()是即使不满足条件,也会至少执行一次。

do{
}while();
增强for循环

JDK5引入,主要用于数组或集合的增强型for循环。

for(声明语句:表达式){
 //代码句子
}
//例子
int[] nums = {1,2,3,4};

for(int x:nums){
    System.out.println(x);
}
break和continue

break:强行退出循环,不执行循环中剩余的语句
continue:终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定

利用for循环打印三角形

public class Demo03 {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 5; j >= i; j--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            for (int j = 1; j < i; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值