while循环:
测试代码1:
package testwhile.com;
public class TestWhile {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("当前循环次数: " + i);
i++;
}
}
}
测试代码2:
package testwhile.com;
//每次循环都会输出当前环还是偶数次循环,最后输出循环结束。
public class MainWhile {
public static void main(String[] args) {
int count = 1;
while (count <= 10 ){
System.out.println("循环次数: " + count);
if (count % 2 == 0) {
System.out.println("这是偶数次循环");
} else {
System.out.println("这是奇数次循环");
}
count++;
}
System.out.println("循环结束");
}
}
测试代码3:
package testwhile.com;
//假如我有一张足够大的纸,它的厚度是0.1毫米。
//需要折叠多少次,可以达到10000米的高度?
public class UsingWhileLoop {
public static void main(String[] args) {
double height = 10000 * 1000; // 目标高度,单位为毫米
double thickness = 0.1; // 纸的厚度,单位为毫米
int folds = 0; // 记录折叠次数
while (thickness < height) {
thickness *= 2; // 每次折叠纸的厚度加倍
folds++; // 折叠次数加一
}
System.out.println("需要折叠 " + folds + " 次才能达到10000米的高度。");
}
}
测试代码4:
package testwhile.com;
import java.util.Scanner;
//通过控制台输入数据并使用while循环来处理输入。
//程序循环等待用户输入,直到用户输入"exit"为止。
//每次循环中都会提示用户输入,并将用户输入的内容打印到控制台。
public class ConsoleInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equalsIgnoreCase("exit")) {
System.out.print("Enter some data (or 'exit' to quit): ");
input = scanner.nextLine();
System.out.println("You entered: " + input); // 处理用户输入,并将输入内容输出到控制台。
}
System.out.println("Program exited. Bye!");
scanner.close(); // 关闭Scanner
}
}
运行结果如下:
测试代码5:
package testwhile.com;
import java.util.Scanner;
//输入一个数字,并通过 scanner.hasNextInt() 验证输入的是否为一个整数。
//然后根据用户输入的数字进行奇偶性和正负性的判断,并输出相应的消息。
public class ComplexConsoleInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
System.out.print("Enter a number: ");
while (!scanner.hasNextInt()) {
System.out.print("That's not a valid number. Please enter a number: ");
scanner.next(); // 消耗无效输入
}
number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
scanner.close(); // 关闭Scanner
}
}
运行结果如下:
标签:几千,Java,scanner,System,number,println,上万,public,out From: https://blog.csdn.net/wehpd/article/details/140476159