一、scanner对象
scanner类:获取用户输入
// hasNext 输入:hello world 输出:hello
public static void main( String[] args )
{
//创建扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println( "使用next()方法接收:" );
//判断用户有没有字符串
if(scanner.hasNext()){
String str =scanner.next();
System.out.println("输出内容为:"+str);
}
scanner.close();//io流的类要及时关掉
}
// hasNextLine() 输入:hello world 输出:hello world
public static void main( String[] args )
{
//创建扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println( "使用nextLine()方法接收:" );
//判断用户有没有字符串
if(scanner.hasNextLine()){
String str =scanner.nextLine();
System.out.println("输出内容为:"+str);
}
scanner.close();//io流的类要及时关掉
}
总结:1.next()以空格作为结束,不能有空格;
2.nextLine()以回车作为结束,可以获得空白;
(跳过顺序结构)
二、选择结构
2.1 if单选结构
public static void main( String[] args )
{
//创建扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println( "请输入内容:" );
String str =scanner.nextLine();
if(str.equals("hello")){ //equals用于判断字符串是否相等,字符串判断别用==
System.out.println(str);
}
System.out.println("end");
scanner.close();//io流的类要及时关掉
}
2.2 if双选结构
2.3 if多选结构
2.4 switch多选结构
case穿透,必须加break; char grade = 'F'; switch (grade){ case 'A': System.out.println("优秀"); break; case 'B': System.out.println("良好"); break; case 'C': System.out.println("还行"); break; default: System.out.println("白瞎"); }
2.5 while循环结构
2.5.1while循环
2.5.2do while循环
输出:
2.5.3for循环(循环次数在执行前就决定了 )
for三个参数都可以没有 for(;;),这是死循环。
{ //输出1-1000被5整除的数字,每3个换一行 public static void main(String[] args) { for (int i = 1; i <= 1000; i++) { println:输出玩换行 print:输出完不换行 if(i%5==0) { System.out.print(i+"\t"); "\t":table } if (i%(5*3)==0){ System.out.println('\n'); } } } }
九九乘法表;
public class App { //输出1-1000被5整除的数字,每3个换一行 一行一行的输出 public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j<= i; j++) { System.out.print(i+"*"+j+"="+(i*j)+"\t"); } System.out.println(); } } }
增强for循环:
(int x:numbers):将numbers数组中的值赋值给x;
break continue:
break:强制退出循环 continue:终止某次循环