Java的键盘输入+几种循环
特别强调:如果不用编译器编译,用cmd编译时,cmd是不支持中文的,所以就算是字符串,用中文也会报错。最好用英文。
强调:在线编译器不能实现输入,请安装JDK完成。
//如何从键盘获取不同类型值的变量输入Scanner//
//重点:导包:import java.util.Scanner;//
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);//实例化格式//
int num = scan.nextInt();
System.out.println(num);
}
}
while循环
为什么输出位置是+ x ;因为前面是字符串,起连接作用
class TestWhile {
public static void main(String args[]) {
int x = 1;
while( x < 7 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
do-while循环
class TestDowhile {
public static void main(String args[]){
int x = 1;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 7 );
}
}
for循环
class TestFor {
public static void main(String args[]) {
for(int x = 1; x < 7; x++) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
for增强forbuff
class TestForbuff {
public static void main(String args[]){
int [] numbers = {6, 7, 8, 9, 10};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"安其拉", "亚瑟", "牛魔", "高渐离"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
break
class TestBreak {
public static void main(String args[]) {
int [] numbers = {6, 7, 8, 9, 10};
for(int x : numbers ) {
if( x == 9) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
countinue
class TestCountinue {
public static void main(String args[]) {
int [] numbers = {6, 7, 8, 9, 10};
for(int x : numbers ) {
if( x == 9 ) {
continue;//在 for 循环中,continue 语句使程序立即跳转到更新语句。
//在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句。
}
System.out.print( x );
System.out.print("\n");
}
}
}