【问题标题】:Simple for statement program with user inputs带有用户输入的简单 for 语句程序
【发布时间】:2014-12-29 01:01:45
【问题描述】:

我无法让我的程序减去用户在下一行输入的字符,直到它达到零。例如,用户输入 5 作为长度和字符 Y,程序应在第一行打印五个“Y”,然后在第二行打印四个“Y”......直到零。像这样... ln(YYYY)
ln(YYYY) ln(YYY) ln(YY) ln(Y) 我不能让程序超过我会得到的第一行: ln(YYYY ln(Y) ln(Y) ln(Y) ln(Y)

我有什么:

    int length;
    char d;     // tried using only char 'd' but scanner has a hard time with chars, so I used        String
    String UserChar;

    //scanner is needed
    Scanner sc = new Scanner(System.in);

    //get user data and initialize variables
    System.out.println("Please input a positive whole number.");
    length = sc.nextInt();
    sc.nextLine();
    System.out.println("Please input one character.");
    UserChar = sc.next();
    sc.nextLine();
    sc.close();

    //do computation
    for(int a = length; a > 1 ; a = a - 1)  //prints user input on first line
    {
        System.out.print(UserChar);
    }

    for(int i = 0; i < length; i = i + 1)   //how many lines get printed
    {
        System.out.println(UserChar);
    }



    // print results (occurs in previous step)
}

}

【问题讨论】:

    标签: for-loop input char subtraction


    【解决方案1】:

    为此,您需要使用嵌套循环。第一个循环将控制我们打印的长度,然后第二个循环将根据第一个循环中使用的变量进行打印。例如:

    //Gets how many chars to print going from n..1
    for(int a = length; a >= 1 ; a = a - 1)  
    {
        for(int i = 0; i < a; i = i + 1) //prints char a times
        {
            System.out.print(UserChar);
        }
        System.out.println();
    }
    

    Here is an example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多