Java方法字符模式 - 初学者



我在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;
}

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达到n-1。那时,迭代停止。这会导致迭代n的次数,其中i的值为[0, 1, 2, ..., n-1]的值。

可以通过再次应用相同的原理来解决其余问题。

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;
}

最新更新