Java方法字符模式 - 初学者

时间:2018-04-03 19:56:55

标签: java methods user-input user-defined-functions

我在我的第一个学期的java和我的阅读障碍使得这个更加困难,但我坚持。我需要获取用户输入的行数,字符数和字符类型。这是为了hw,所以任何建议都表示赞赏。我需要使用一个方法(调用)来创建一个带有相应输入变量的模式,并打印总字符数:

行数:3
字符数:6
字符:X

XXXXXX
XXXXXX
XXXXXX

总人物:18
这是我到目前为止的代码:

static Scanner console = new Scanner(System.in);  
  public static void main (String[] args)  
  {  
    int totalChar;  
    int numLn = console.nextInt();          //Should I assign here or  
    int charPerLn = console.nextInt();      //after sys.println?  
    char symbol = console.next().charAt(0);  

    System.out.println("# of lines: " +numLn);

    System.out.println("# of characters: "+charPerLn);

    System.out.println("Character: "+symbol);

    System.out.print(Pattern);    //Pretty sure this is wrong or at
                                  //least in the wrong place to call

    System.out.println("Total Characters: "+totalChar);
    totalChar = numOfLines * charPerLine;
}

public static int Pattern(int x)
{
    int pattern;

    //I need a nested while or for loop here but I'm not sure how to 
    //assign the main's values for #lines and #character
    //Am I over-thinking this?  

    return pattern;
}

2 个答案:

答案 0 :(得分:1)

Pattern方法应类似于以下内容:

public static int Pattern(int lineCount, int charCount, char character) {

    for (int i = 0; i < lineCount; i++) {
        // Repeat the supplied character for charCount
    }
}

Pattern方法现在包含行数和每行字符数的参数,因为这些值将决定迭代的次数。我将保留每行正确打印字符数的逻辑(这将给出整个答案),但循环(索引i)遍历行数。通常,当您想要重复某些n次时,您创建一个具有以下基本结构的循环:

for (i = 0; i < n; i++) { /* ... */ }

这意味着在第一次迭代时,i等于0,然后是1,然后是2,依此类推,直到i到达{{1} }}。此时,迭代停止。这导致迭代n-1次,其中n取值为i

问题的其余部分可以通过再次应用同样的原则来解决。

答案 1 :(得分:0)

static Scanner console = new Scanner(System.in);  
public static void main (String[] args)  
{  
    int totalChar;  
    int numOfLines = console.nextInt(); 
    int charPerLine = console.nextInt(); // keep your variable names consistent by using either "charPerLn" or "charPerLine", not both :)
    char symbol = console.next().charAt(0);  

    System.out.println("# of lines: " + numOfLines);
    System.out.println("# of characters: " + charPerLine);
    System.out.println("Character: " + symbol);
    System.out.println(getPattern( /* [use, the, parameters, from, above, here] */ ));

    totalChar = numOfLines * charPerLine; // first assign to totalChar, then you can print it
    System.out.println("Total Characters: " + totalChar);
}

public static String getPattern(int numOfLines, int charPerLine, char symbol) // you want to return a string, so we change "int" to "String" here
{
    String pattern = "";

    /* As "that other guy" said, nested for loops go here */
    for(/* ... */)
    {
        /* ... */
        for(/* ... */)
        {
         /* ... */
        }
        /* ... */
    }

    return pattern;
}