我需要帮助实现一个循环,告诉用户只输入正整数,但我不知道从哪里开始。有人能帮我吗。
import java.util.Scanner;
public class GCD {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int firstN = input.nextInt();
System.out.print("Enter another positive integer: ");
int secondN = input.nextInt();
System.out.println("The GCD of " + firstN + " and " + secondN + " is: " + gCd(firstN, secondN));
}
public static int gCd(int firstN, int secondN) {
if(secondN == 0) {
return firstN;
} else
return gCd(secondN, firstN%secondN);
}
}
答案 0 :(得分:0)
int firstN=0;
while(firstN<=0){
System.out.print("Enter a positive integer: ");
firstN = input.nextInt();
};
//implement a similar loop for secondN
循环将继续,直到firstN为正
答案 1 :(得分:0)
在您的情况下,您需要用户至少输入一次。但是,您希望不断要求用户输入内容,直到它有效为止。
在我看来,import com.fasterxml.jackson.databind.node.ObjectNode;
ArrayList<ObjectNode> employee = new ArrayList();
for(int i = 1; i < 4; i++){
ObjectNode em = Json.newObject();
em.put("companyName", "cName" + i);
employee.add(em);
}
ObjectNode company = Json.newObject();
company.put("companyName", "cName");
company.putArray("employee").addAll(employee);
return Json.newObject().put("company", company);
循环是编写这种逻辑的最清晰的方法,因为它完全符合您的要求而没有任何无关的黑客攻击。
例如,
do-while
do-while循环首先执行“do”部分,然后检查“while”条件。所以,你首先要求用户提供一个号码,如果你不喜欢它,你就会继续问他们另一个号码。
如果有什么不清楚,请告诉我!
编辑:
如果您想在数字为负数时向用户提供错误消息,则需要考虑修改后的算法。你想要
我假设您了解Java中的各种循环,例如 Scanner input = new Scanner( System.in );
int firstN;
do {
System.out.println( "Enter a positive integer:" );
firstN = input.nextInt();
} while ( !(firstN > 0) );
,for
,while
。如果您可以自己编写这个逻辑并在您遇到问题时发表评论,请与您联系。
答案 2 :(得分:0)
$cart_products = $this->context->cart->getProducts();
答案 3 :(得分:0)
这应该在主
中运行 System.out.print("Enter a positive integer: ");
Scanner input = new Scanner(System.in);
int posInt;
while((posInt=input.nextInt())<=0){
System.out.println("Inter only positive integers.");
}
System.out.println("You entered the number:"+posInt);
答案 4 :(得分:0)
为什么不试试:
Public static int gCd(int firstN, int secondN) {
if(secondN < 0|| firstN< 0) {
print("enter a positive value");
} else
return firstN%secondN;
}