英文:
how to make a switch
问题
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = 1;
for (int i = 1; i <= 30; i++) {
if (i % a == 0) {
b = 1;
System.out.print("X");
} else {
System.out.print("O");
}
}
}
}
- 我将3输入到扫描器中
- 期望的结果
- XXXOOOXXXOOOXXXOOOXXX
英文:
import java.util.Scanner;
public class Main2 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int a=scan.nextInt();
int b=1;
for (int i=1;i<=30;i++){
if(i%a==0){
b=1;
System.out.print("X");
}else {
System.out.print("O");
}
}
}
}
- I drive 3 into the scanner
- the desired result
- XXXOOOXXXOOOXXXOOOXXX
答案1
得分: 0
尝试这个:
if (i % a == 0) {
b = 1 - b;
}
if (b == 1) {
System.out.print("X");
} else {
System.out.print("O");
}
更新:使用 switch
语句:
for (int i = 0; i < 30; i++) {
if (i % a == 0) {
b = 1 - b;
}
switch (b) {
case 0:
System.out.print("O");
break;
case 1:
System.out.print("X");
break;
}
}
英文:
Try this:
if (i%a==0) {
b = 1-b;
}
if(b==1){
System.out.print("X");
}else {
System.out.print("O");
}
UPDATE: with a switch
statement:
for (int i=0; i<30; i++) {
if (i%a==0) {
b = 1-b;
}
switch (b) {
case 0:
System.out.print("O");
break;
case 1:
System.out.print("X");
break;
}
}
答案2
得分: 0
根据我理解你的代码,不需要使用开关语句。我通过嵌套的for循环得到了所需的输出。
int XPerGroup = 3;
int group = 4;
for(int i = 0; i < group; i++){
for (int j = 0; j < XPerGroup; j++) {
System.out.print("X");
}
System.out.print(" ");
}
你可以将硬编码的变量改成使用Scanner输入。
英文:
From what I can understand from your code, there is no need for a switch. I got the desired output by use of nested for loops.
int XPerGroup = 3 ;
int group = 4;
for(int i = 0; i < group; i++){
for (int j = 0; j < XPerGroup; j++) {
System.out.print("X");
}
System.out.print(" ");
}
You can just change hardset variables into scanner input.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论