import java.util.Scanner;
public class Assignment5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a;
System.out.println("Please enter a number between 1 and 9:");
int[] graph = new int[10];
for(int i = 0; i < 10; ++i){
a = scan.nextInt();
graph[i] = a;
}
}
// this is the method I'm required to use for
// this array assignment
public static void printVertical(int[] graph){
for(int i = 0; i < graph.length; i++){
for(int j = 0; j < graph[i]; j++){
System.out.print(" " + graph[i]);
}
System.out.println();
}
}
// this is what I've got for the horizontal method
// I took the for loop and nested for loop from the vertical.
// I'm stuck on changing the variable to flip the graph -90 degrees
public static void printHorizontal(int[] graph){
for(int i = 0; i < graph.length; i++){
for(int h = 0; h < graph[i]; h++){
System.out.print(" " + graph[i]);
}
System.out.println();
}
}
public static int calculateTotal(int[] graph){
int sum = 0;
for( int num : graph ){
sum = sum + num;
}
System.out.print("The total is: " + sum);
return sum;
}
}
printVertical
方法中的 for 循环未正确返回图形。
我做错了什么?
输出需要如下所示:
Sample output:
2 4 6 8 9 8 6 4 3 2
---- Vertical Graph ----
2 2
4 4 4 4
6 6 6 6 6 6
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
8 8 8 8 8 8 8 8
6 6 6 6 6 6
4 4 4 4
3 3 3
2 2
---- Horizontal Graph ----
9
8 9 8
8 9 8
6 8 9 8 6
6 8 9 8 6
4 6 8 9 8 6 4
4 6 8 9 8 6 4
2 4 6 8 9 8 6 4 2
The total is: 52
2 4 6 8 9 8 6 4 2
最佳答案
考虑下面给出的代码。它可能会解决您的问题..
import java.util.Scanner;
public class Assignment5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a;
System.out.println("Please enter a number between 1 and 9:");
int[] graph = new int[10];
for(int i = 0; i < 10; ++i){
a = scan.nextInt();
graph[i] = a;
}
System.out.println("----------Vertical Graph-------------");
printVerticalGraph(graph);
System.out.println("----------Horizontal Graph-------------");
printHorizontalGraph(graph);
}
public static void printVerticalGraph(int[] graph)
{
for (int i = 0 ; i < graph.length; i++)
{
for (int j = 0 ; j < graph[i] ; j++)
{
System.out.print(graph[i]+" ");
}
System.out.println();
}
}
public static void printHorizontalGraph(int[] graph)
{
for (int i = 0 ; i < graph.length; i++)
{
for (int j = 0 ; j < graph.length; j++ )
{
if (i > 10 - graph[j])
{
System.out.print(graph[j]);
}
else
System.out.print( " ");
System.out.print(" ");
}
System.out.print("\n");
}
}
}
这是示例输出..
Please enter a number between 1 and 9:
2
4
6
8
9
8
6
4
3
2
----------Vertical Graph-------------
2 2
4 4 4 4
6 6 6 6 6 6
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
8 8 8 8 8 8 8 8
6 6 6 6 6 6
4 4 4 4
3 3 3
2 2
----------Horizontal Graph-------------
9
8 9 8
8 9 8
6 8 9 8 6
6 8 9 8 6
4 6 8 9 8 6 4
4 6 8 9 8 6 4 3
2 4 6 8 9 8 6 4 3 2
关于java - 使用java中的数组打印水平和垂直图中的数字图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711146/