我一直在努力弄清楚这段代码,但似乎无法修复它:
import java.util.Scanner;
public class Graphs
{
public void drawHistograms()// draws 5 histograms
{
Scanner input = new Scanner( System.in );
int number1 = 0; // first number
int number2 = 0; // second number
int number3 = 0; // third number
int number4 = 0; // fourth number
int number5 = 0; // fifth number
int inputNumber; // number entered by user
int value = 0; // number of stars to print
int counter = 1; // counter for current number
while ( counter <= 5 )
{
System.out.println( "Enter number: " );
inputNumber = input.nextInt();
// define appropriate num if input is between 1-30
if ( inputNumber >= 1 && inputNumber <= 30 )
{
switch ( inputNumber )
{
case 1:
number1 = inputNumber;
break; // done processing case
case 2:
number2 = inputNumber;
break; // done processing case
case 3:
number3 = inputNumber;
break;
case 4:
number4 = inputNumber;
break; // done processing case
case 5:
number5 = inputNumber;
break; // done processing case
}counter++;
} // end if
else
System.out.println(
"Invalid Input\nNumber should be between 1 and 30" );
} // end while
// print histograms
for ( counter = 0; counter <= 4; counter++ )
{
switch ( counter )
{
case 1:
value = number1;
break; // done processing case
case 2:
value = number2;
break; // done processing case
case 3:
value = number3;
break; // done processing case
case 4:
value = number4;
break; // done processing case
case 5:
value = number5;
break; // done processing case
}
for ( int j = 0; j <= value; j++ )
{
System.out.print( "*" );
} System.out.println();
} // end for loop
} // end method drawHistograms
} // end class Graphs
我的输出应该是这样的:
Enter number: 5
Enter number: 2
Enter number: 8
Enter number: 4
Enter number: 6
*****
**
********
****
******
关于如何解决此问题的任何想法?我很难过。我已经尝试更改开关中的变量,看看输出会发生什么变化;无论我输入什么数字,我都会得到几乎相同的东西。
答案 0 :(得分:2)
我看到以下两个问题:
switch
也应该启用counter
而不是inputNumber
。switch
周围的循环,您应该从1到5而不是0到4循环。旁注:最好使用列表或数组来存储5个数字,而不是为每个数字使用单独的变量。
答案 1 :(得分:1)
首先,你不需要switch
。考虑以下方法
public void drawHistograms() {
Scanner input = new Scanner(System.in);
int[] number = new int[5]; // define an array
int inputNumber;
int counter = 0; // set counter to 0
while (counter <= 4) {
System.out.println("Enter number: ");
inputNumber = input.nextInt();
if (inputNumber >= 1 && inputNumber <= 30) { // if input is valid
number[counter] = inputNumber; // add that value to array
} else {
System.out.println("Number should be between 1 and 30");
}
counter++; // increment counter
}
// now your array contains all inputs
for (int i = 0; i < number.length; i++) { // iterate array
for (int j = 0; j < number[i]; j++) {// iterate up to element value
System.out.print("*");
}
System.out.println("");
}
}