gpt4 book ai didi

JAVA:使用While循环打印出与读入的数字一样多的字符

转载 作者:行者123 更新时间:2023-11-29 05:54:19 25 4
gpt4 key购买 nike

您好,我在介绍计算机科学实验室工作时遇到问题:

CharacterLine.java:编写一个打印一行字符的程序。提示用户输入一个字符,然后询问一个数字。如果数字小于 1 或大于 80,则告诉用户退出程序。使用 while 循环打印出与读入的数字一样多的字符。例子:请输入字符:&请输入数字:15您的线路:&&&&&&&&&&&&&&

这是我的代码:

import java.util.Scanner;

public class CharacterLine

{
public static void main(String[] args)
{

Scanner kb = new Scanner (System.in);
int number;
System.out.print("Please enter a character: ");
String character = kb.next();
int charact = character.length();

System.out.print("Please enter a number: ");
number = kb.nextInt();

while ( number <= 80 && number >= 1 ){

if ( number <= 80 && number >= 1 ) {
int bills = (charact * number);
System.out.println("Your line: " + charact++);
}
else {
System.out.println("error.");
}
System.out.println();
System.out.print("Please enter a number: ");
number = kb.nextInt();
}
if ( number > 80 ){
System.out.println("That number is too large");
}
else if ( number < 1 ){
System.out.println("That number is too small");
}
else{
System.out.println("error");
}
}
}

我在知道如何乘以用户输入的数字并使输出数字乘以用户输入的一个字母时遇到问题。

谢谢,威廉

最佳答案

您可以使用循环迭代给定的 次..并打印字符..

if ( number <= 80 && number >= 1 ) {

char myChar = '*';

// This while loop will run 15 times if value of number is 15..
while(number > 0) {
System.out.println(myChar);
number--; // Decrement the value of `number` by 1.
}
}

上面的 while 循环说:

While the value of number is greater than 0, execute the loop, and print the statement inside it.. After printing, decrement the value of number by 1, and check the condition once again... Continue this process while number > 0

关于JAVA:使用While循环打印出与读入的数字一样多的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12763699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com