[英]Finding how many times a number has, consecutively, been entered by the user. Using loops
[英]Find out how many times a negative and positive number has been entered
我一直在試圖弄清楚我的程序如何找到用戶輸入了多少正數和負數。
我在這里有我的問題:“編寫一個程序,不斷向用戶詢問數字,直到用戶輸入 0。用戶輸入 0 后,程序應該顯示輸入的負數和正數的數量”。
另外,到目前為止,我的代碼在這里:
import java.util.Scanner;
public class NegativeandPositive
{
public static void main(String[] args)
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Input an integer:");
while ((n = input.nextInt()) != 0)
{
System.out.println("You entered " + n);
System.out.println("Input an integer:");
}
}
}
謝謝閱讀。
import java.util.Scanner;
public class NegativeandPositive
{
public static void main(String[] args)
{
int n;
int negative=0,positive=0;
Scanner input = new Scanner(System.in);
while (true)
{
System.out.println("Input an integer:");
n = input.nextInt();
System.out.println("You entered " + n);
if(n==0) break;
//Not using else
//because if it's 0, below won't be executed anyways
if(n < 0) negative++;
else positive++;
}
System.out.println("Negative: "+negative+" ,positive: "+positive);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.