我收到該錯誤,我不知道爲什麼。我已經嘗試了一些不同的東西,比如從(!(flag... then == '+'
開始,另一個與==
開始,其中do語句下面的行也出現錯誤。任何人都看到了問題?我現在想要得到的主要目標是for循環重複打印繩索,並在另一個地方向左或向右打印旗幟。Do-while循環「字符串索引超出範圍」
package program2;
import java.util.Scanner;
import java.lang.Math;
public class Program2 {
public static int MAX_LENGTH = 21;
public static int MIN_LENGTH = 5;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the length of the rope: ");
int ropeLength = keyboard.nextInt();
while (ropeLength < MIN_LENGTH || ropeLength > MAX_LENGTH || ropeLength % 2 != 1) {
System.out.println("Thats not a valid length (odd number between 5 and 21)");
System.out.print("Enter the length of the rope: ");
ropeLength = keyboard.nextInt();
}
char a;
String flag = "+";
for (int i = 0; i < ropeLength/2; i += 1) {
System.out.print("-");
}
System.out.print(flag);
for (int i = 0; i < ropeLength/2; i += 1) {
System.out.print("-");
}
System.out.println("");
do {
//a = flag.charAt(ropeLength);
double rand = Math.random();
if (rand > 0.5) {
for (int i = 0; i < (ropeLength/2) - 1; i++) {
System.out.print("-");
}
System.out.print(flag);
for (int i = 0; i < (ropeLength/2) + 1; i++) {
System.out.print("-");
}
if (rand < 0.5) {
for (int i = 0; i < (ropeLength/2) + 1; i++) {
System.out.print("-");
}
System.out.print(flag);
for (int i = 0; i < (ropeLength/2) - 1; i++) {
System.out.print("-");
}
}
}
} while (flag.charAt(0) != '+' || flag.charAt(ropeLength - 1) != '+');
}
}
,並作爲do while循環,我的循環似乎只被重複一次或兩次。
do {
//a = flag.charAt(ropeLength);
double rand = Math.random();
if (rand > 0.5) {
for (int i = 0; i < (ropeLength/2) - 1; i++) {
System.out.print("-");
}
System.out.print(flag);
for (int i = 0; i < (ropeLength/2) + 1; i++) {
System.out.print("-");
}
if (rand < 0.5) {
for (int i = 0; i < (ropeLength/2) + 1; i++) {
System.out.print("-");
}
System.out.print(flag);
for (int i = 0; i < (ropeLength/2) - 1; i++) {
System.out.print("-");
}
}
}
} while (flag.charAt(0) != '+' || flag.charAt(ropeLength - 1) != '+');
}
和最後一件事,我需要,我有權下做註釋掉的代碼?
假設ropeLength = 13。'flag.charAt(ropeLength - 1)'的值應該是什麼? – Ingo 2013-03-16 00:53:12
你標誌變量的長度爲1. – 2013-03-16 01:00:58