我需要帮助创建一个循环来查看从1到数字1的每个值。 另外如何测试每个值以查看它是否为a 数字的除数,如果是,则将其加到总和中。
这是我到目前为止所做的:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Please enter a positive integer: ");
int n = input.nextInt();
while (n < 0) {
System.out.println(n + " is not positive.");
System.out.print("Please enter a positive integer: ");
n = input.nextInt();
}
}
答案 0 :(得分:0)
您可以将其用作应用程序的起始块:
package Testers;
import java.io.Console;
public class Application {
public static void main(String[] args)
{
Console console = System.console();
if (console == null)
{
System.err.println("No console.");
System.exit(1);
}
boolean keepRunning = true;
while (keepRunning)
{
String name = console.readLine("Type your positive integer");
try{
int integer = Integer.parseInt(name);
if(integer < 0){
System.out.println("You must specify a positive integer!");
}
for(int i = 1; i<integer; i++){
// our variable "i" is smaller than "integer". This will parse all the numbers between one and "integer" -1.
if(i % 2 == 0){
//"i" IS divisible by 2. Of course, you can change this value to what you want to change it to.
//Here you can add it to a sum
}else{
//"i" is not divisible by 2. Of course, you can change this value to what you want to change it to.
}
}
}catch(NumberFormatException e){
System.out.println("You must specify a positive integer!");
}
}
}
}
答案 1 :(得分:0)
如果您想要执行已知次数的操作,最好使用UInt16[] availableRequestedStates = { 2, 3, 4, 6, 7, 8, 9, 10, 11 };
compSystem["AvailableRequestedStates"] = availableRequestedStates;
compSystem.Put();
ManagementBaseObject inParams = compSystem.GetMethodParameters("RequestStateChange");
inParams["RequestedState"] = 2;
ManagementBaseObject result = compSystem.InvokeMethod("RequestStateChange", inParams, null);
循环。如果您想为for
到1
执行某些操作,则循环可能看起来像
n-1
请注意,它从1开始计数,并在for(int i = 1; i < n; i++) { // do stuff }
大于或等于i
时立即停止。
为了知道一个数字(比如n
)是否可以被某个数字整除,比如n
,可以使用模运算符k
。如果%
这意味着n % k == 0
可以被n
整除。使用k
语句可以对此进行测试,当您有一些if
变量时,您可以添加任何您想要的变量来进行总结。
希望有所帮助