代码如下。
我想输入一些数字,测试每个数字是否低于 10,打印出低于 10 的总金额并打印出每个数字。
如何从循环中提取数字并在循环结束时打印它?
如果我输入4,2,11,12
并且循环完成,我如何打印出4
和2
?
不使用数组。我是编程新手,还没有接触过数组。
谢谢
class Numbers
{
public static boolean isNum(int num)
{
boolean returnValue;
returnValue = false;
if(num >= 0 && num < 10)
{
returnValue = true;
}
return returnValue;
}
public static void main (String [] args)
{
int input; //numbers entered by user
int numCount = 0; //numbers less than 10
int index;
boolean result;
System.out.print("How many numbers to test? ");
input = EasyIn.getInt();
result = isNum(input);
for(index = 0; index <= input; index++ )
{
System.out.println("Enter a number ");
input = EasyIn.getInt();
if(result == true)
{
numCount++;
}
}
System.out.println("Total numbers below 10 is " + numCount);
}
}
最佳答案
如果您绝对必须等到循环完成才能打印出您的数字,并且无法使用数组,您始终可以创建一个字符串并继续将有效数字附加到其中(也许逗号分隔)。然后在循环完成后打印出这个字符串。
例如:
String output = "";
for (index = 0; index <= input; index++)
input = EasyIn.getInt();
result = isNum(input);
if(result == true)
{
numCount++;
output += input.ToString() + ", "; // you will probably want to remove the last comma
}
}
output = output.replaceAll(", $", ""); // remove last comma
System.out.println("Total numbers below 10 is " + numCount);
System.out.println("The numbers below 10: " + output)
关于java - 计算 10 以下的数字并打印每一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21758920/