我应该编写一个要求输入名称的代码,要求输入1到10之间的数字,然后将数字从1打印到用户输入的数字,除了每三个数字应该是输入的用户名在计划的开头。我的代码实现了这个目的。下一步是使用一个循环,将所有偶数从2打印到用户的数字。我不知道如何在我的代码中包含这个,甚至不应该使用什么样的循环。有人可以解释如何正确包含这个吗?这是迄今为止的代码。
import java.util.Scanner;
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print("No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
}
}
答案 0 :(得分:2)
运行一个在每个偶数上打印的循环与运行在每三个数字上打印的循环没有什么不同。只需使用% 2
代替% 3
:
for (int i = 2; i <= number; i++) {
if (i % 2 = 0) {
System.out.print(i + " ");
}
}
可以在不使用%
的情况下重写:
for (int i = 2; i <= number; i += 2) {
System.out.print(i + " ");
}
答案 1 :(得分:0)
public static void main(String[]p){
int limit=20;
for(int i=2; i<=limit; i+=2)
{
System.out.println(i);
}
}
答案 2 :(得分:0)
以下代码供您参考:
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print("No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
}else {
System.out.print(i + " ");
}
}
System.out.println();
for(int i =2; i<=number; i+=2)
System.out.print(i + " ");
}
}
答案 3 :(得分:0)
for (int i = 2; i <= number; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
答案 4 :(得分:-1)
这是一个偶数数字的循环。
for(int i=2;i<number;i+=2)
{
System.out.println(i);
}
答案 5 :(得分:-1)
这是一个可以打印最多100个偶数的例子。
int number = 0;
while (number <= 100) {
number += 1;
if (number % 2 == 0) {
System.out.println(number);
}
}
答案 6 :(得分:-1)
这是使用Java 8流api和range函数的解决方案:
System.out.print("Please enter a number between 1 and 10: ");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
IntStream stream = IntStream.rangeClosed(2, number);
stream.filter( i -> i % 2 ==0).forEach( i -> System.out.format("%d\t",i));
答案 7 :(得分:-2)
for (int i = 2; i <= number; i++) {
if (i % 2 = 0) {
System.out.print(i + " ");
}
}
以上是代码。