java 数组,从键盘输入数字

确定此数组中符号更改的次数。 例如,在数组 1,-34, 8, 14, -5,-8,-78, 3 中,符号改变了 4 次。


public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int count = 0;
        Integer last = null;
        while (true) {
            try {
                System.out.println("请输入一个数字(输入其他任意字符退出):");
                String s = sc.nextLine();
                Integer tmp = Integer.parseInt(s);
                if (last != null) {
                    int r = tmp * last;
                    if (r < 0) {
                        count++;
                    }
                }
                last = tmp;
            }catch (Exception e) {
                break;
            }
        }
        System.out.println(count);
    }
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
           Scanner sc=new Scanner(System.in); 
           int n = sc.nextInt();
           int a=0,count = 0;
           for(int i=0;i<n;i++)
           {
                int b = sc.nextInt();
                if(i==0)
                      a = b;
                else if(a*b < 0)
                      count++;
                a = b;
           }
           System.out.println(count);  
    }
}

遍历数组当前位置与前一个位置正负不同就统计次数加一