Read in an indeterminate integer from the keyboard, and determine the number of positive and negative numbers read, and the program ends when the input is 0.

Read in an indeterminate integer from the keyboard, and determine the number of positive and negative numbers read, and the program ends when the input is 0.

Title description:
Read in an indeterminate integer from the keyboard, and judge the number of positive and negative numbers read, and the program ends when the input is 0.

Problem-solving idea:
Because the number of reading is uncertain, an infinite loop is required. When the input is 0, break out of the loop will do.

Summary:
① The simplest "infinite" loop format: while(true), for(;;) , the reason for the infinite loop is that you don't know how many times it loops, and you need to control the end of the loop according to some conditions inside the loop body.

② How many ways are there to end the loop?
 Method 1: The loop condition part returns false.
 Method 2: In the loop body, execute break

The Java code for this question:

import java.util.Scanner;
public class ForWhileTest {
    
    

	public static void main(String[] args) {
    
    
		
		System.out.println("请输入一个整数:");
		Scanner scan = new Scanner(System.in);
		
		int positiveNumber = 0; //记录正数的个数
		int negativeNumber = 0; //记录负数的个数
		
		for (;;) {
    
     //或者是while(true)
			int number = scan.nextInt();
			//判断number的正负情况
			if (number > 0) {
    
    
				positiveNumber++;
			} else if (number < 0) {
    
    
				negativeNumber++;
			} else {
    
    
				System.out.println("输入的正数的个数为:" + positiveNumber + ",负数的个数为:" + negativeNumber);
				break;
			}
		}
	}

}

Guess you like

Origin blog.csdn.net/qq_45555403/article/details/114139677