Java流程控制

Java流程控制

  • 用户交互Scanner
  • 顺序结构、选择结构、循环结构
  • break&continue

Scanner对象

java.util.Scanner包用来获取用户的输入

基本语法:

Scanner s=new Scanner(System.in)
//判断用户有没有输入字符串
Scnaner sc=new Scanner(System.in);
//使用next方法接收
if(sc.hasnext()){
String str=sc.next();//程序会等待用户输入完毕
System.out.println("输出的内容为:"+str);
}
sc.close();//凡是IO流的类不关闭会一直占用资源,用完就关掉

//判断用户有没有输入字符串
Scnaner sc=new Scanner(System.in);
//使用next方法接收
if(sc.hasnextLine()){
String str=sc.nextLine();//程序会等待用户输入完毕
System.out.println("输出的内容为:"+str);
}
sc.close();//凡是IO流的类不关闭会一直占用资源,用完就关掉

输入“hello world!"

**next():返回空格前的有效字符 ** 输出"hello"

nextLine():返回Enter之前的所有字符 输出"hello world!"

Scanner进阶

scanner文档:https://www.runoob.com/manual/jdk11api/java.base/java/util/Scanner.html

常用方法

方法 描述
构造方法
Scanner(File source) 从文件创建 Scanner
Scanner(InputStream source) 从输入流创建 Scanner
Scanner(String source) 从字符串创建 Scanner
基本输入方法
boolean hasNext() 检查是否有下一个标记(以空格分隔)
String next() 读取下一个标记(字符串)
boolean hasNextLine() 检查是否有下一行
String nextLine() 读取下一行内容
类型检查方法
boolean hasNextInt() 检查下一个标记是否为整数
boolean hasNextDouble() 检查下一个标记是否为双精度浮点数
boolean hasNextBoolean() 检查下一个标记是否为布尔值
类型读取方法
int nextInt() 读取下一个整数
double nextDouble() 读取下一个双精度浮点数
boolean nextBoolean() 读取下一个布尔值
long nextLong() 读取下一个长整数
float nextFloat() 读取下一个单精度浮点数
short nextShort() 读取下一个短整数
byte nextByte() 读取下一个字节

Switch语句

语法:switch(condition)

{

case '条件1':

case'条件2':

............

default:

}

posted @ 2025-11-14 16:23  兮夜尹  阅读(6)  评论(0)    收藏  举报