由于某种原因,数组超出范围

时间:2015-10-23 20:53:12

标签: java

我正在尝试编写一个程序,该程序从用户处获取一串int,并打印出包含多少正数和负数,并在读取0时停止。如果只输入0,则应打印“否”输入的数字除外0.“ 下面我包含了我的代码:

import java.util.Scanner;
public class Ex4_1
{
    public static void main(String[]args)
    {
         Scanner input = new Scanner(System.in);
         System.out.println("Enter an integer, the input ends if it is 0 (use commas in between numbers):");
         String str = input.nextLine();
         int x = str.length();
         int positive = 0;
         int negative = 0;
         for(int i = 0; i< x; i++)
         {
             int w = 0;
             String[] num = new String[x];
             num = str.split(",");
             if(d1 > 0)
             { 
                 positive += 1;
             }
             else if(d1 < 0)
             {
                 negative += 1;
             }
             else if(d1 == 0)
             {
                 System.out.println("No numbers entered except 0.");
             }
         }

         System.out.println("The number of positives is " + positive );
         System.out.println("The number of negatives is " + negative);
    }
}

1 个答案:

答案 0 :(得分:-1)

d1 = Integer.parseInt(num [i]);

import java.util.Scanner;  
    public class Ex4_1  
    {  
          public static void main(String[]args)  
        {  
             Scanner input = new Scanner(System.in);  
             System.out.println("Enter an integer, the input ends if it is 0         (use commas in between numbers):");  
         String str = input.nextLine(); 
 String[] num = new String[x];  
         num = str.split(","); 
         int x = num.length();  
     int positive = 0;  
     int negative = 0;
if(x==1 && num[0]=="0")  
System.out.println("No numbers entered except 0.");  
else {    
     for(int i = 0; i< x; i++)  
     {  
         int w = 0;  
         if(d1 > 0)  
         {   
             positive += 1;  
         }  
         else if(d1 < 0)  
         {  
             negative += 1;  
         }  
         else if(d1 == 0)  
         {  
             break;  
         }  
     }   
     System.out.println("The number of positives is " + positive );  
     System.out.println("The number of negatives is " + negative);  
    }}  
}  

根据您的问题,这应该是正确的代码!