怎样将代码放入循环中,因为它没有再次接受输入。

huangapple 未分类评论58阅读模式
英文:

How can i put the code in a loop because its not taking the input again

问题

while (true) {
    System.out.print("Enter the number of rows ");
    Scanner obj1 = new Scanner(System.in);
    int ro = obj1.nextInt();

    System.out.print("Enter the number of columns ");
    int co = obj1.nextInt();

    if ((ro > 2 && ro <= 10) && (co > 2 && co <= 10)) {
        CLASS obj = new CLASS(ro, co);
        break; // Exit the loop if input is correct
    } else {
        System.out.println("Error: Wrong input. Please enter again");
    }
}

以上代码会将输入部分放入一个循环中,如果输入的行和列不满足要求,会显示错误消息并要求重新输入。当满足条件时,会创建一个名为"CLASS"的对象,并且循环会结束。

英文:

user will enter the row and column of the block. The number of rows and the number of columns should be an integer greater than 2 and less than or equal to 10. If any input is incorrect, show an error message and ask for that input again.

	System.out.print(&quot;Enter the number of rows &quot;);
	Scanner obj1 = new Scanner(System.in);
	int ro = obj1.nextInt();
    
	System.out.print(&quot;Enter the number of columns &quot;);
    int co = obj1.nextInt();
	
	if((ro &gt; 2 &amp;&amp; ro &lt;=10)   &amp;&amp;  (co &gt; 2 &amp;&amp; co &lt;=10))
	{
		CLASS obj = new CLASS(ro,co);
		
	}
	else
	{
        System.out.println(&quot;Erro Wrong ipnut &quot; + &quot;Please enter again&quot;);
             
    }

How can i put the above code in a loop because it only runs one time and not taking the input again when the wrong input is entered its just showing the message.

答案1

得分: 0

在Java中,有名为while和for的循环。请查看:https://www.geeksforgeeks.org/loops-in-java/

英文:

In Java, there are loops named while and for. Look at: https://www.geeksforgeeks.org/loops-in-java/

答案2

得分: 0

这个问题有点愚蠢,但这里有一个快速的解决方案:

while (true) {
    System.out.print("输入行数 ");
    Scanner obj1 = new Scanner(System.in);
    int ro = obj1.nextInt();

    System.out.print("输入列数 ");
    int co = obj1.nextInt();

    if((ro > 2 && ro <= 10) && (co > 2 && co <= 10)) {
        CLASS obj = new CLASS(ro,co);
    } else {
        System.out.println("错误的输入。请重试。");
    }
}
英文:

This question is kind of stupid but here's a quick solution anyways:

while (true) {
    System.out.print(&quot;Enter the number of rows &quot;);
    Scanner obj1 = new Scanner(System.in);
    int ro = obj1.nextInt();

    System.out.print(&quot;Enter the number of columns &quot;);
    int co = obj1.nextInt();

    if((ro &gt; 2 &amp;&amp; ro &lt;=10)   &amp;&amp;  (co &gt; 2 &amp;&amp; co &lt;=10)) {
        CLASS obj = new CLASS(ro,co);
    } else {
        System.out.println(&quot;Error wrong input. Please try again.&quot;);
    }
}

huangapple
  • 本文由 发表于 2020年4月11日 02:18:25
  • 转载请务必保留本文链接:https://java.coder-hub.com/61146276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定