Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

Invalid integer formats

Tue Jul 12, 2011 8:48 pm

i want to find the sum of 10 numbers entered (valid) and also find the no. of valid and non valid nos. entered ....i made the program below but it doesn't work...and need modification in it ?


Code:

import java
.util.*;

public class EH1 {
    
    public static void main
(String[] args){
        
    Scanner s 
= new Scanner(System.in);
        int k=1,c=0,sum=0,invalid=0,valid=0;
        
        System
.out.println("Enter 10 numbers :");
        
while 
(k<=10)
  {
       try
           
{ 
                c 
= s.nextInt();
                sum =sum + c;
                valid++;
                k++;
           }

         
    catch
(NumberFormatException ex) 
   
         
{
            k++;
            System.out.println("  INVALID NUMBER  ");
            invalid++;

         }
 
  
}
        
        System
.out.println("Valid numbers : "+valid);
        System.out.println("Invalid numbers : "+invalid);
        System.out.println("SUM : "+sum);
        
    
}
}
 




Re: Invalid integer formats

Wed Jul 13, 2011 1:24 pm

see the modification i made below
Code:

 Scanner s 
= new Scanner(System.in);
        
int k 10sum 0invalid 0valid 0;
        
String number="";
        
System.out.println("Enter 10 numbers :");

        while (
<= 10) {
            try {
                
number s.next();
                
c=0;
                
c=Integer.parseInt(number);
                
sum sum c;
                
System.out.println("Sum so far"+sum);
                
valid++;
                
k++;
            } catch (
NumberFormatException ex) {
                
k++;
                
System.out.println(" INVALID NUMBER ");
                
invalid++;

            }catch  (
InputMismatchException exception){
                     
k++;
                
System.out.println(" INVALID NUMBER ");
                
invalid++;
            }


        }

        
System.out.println("Valid numbers : " valid);
        
System.out.println("Invalid numbers : " invalid);
        
System.out.println("SUM : " sum);
 


Post a reply
  Related Posts  to : Invalid integer formats
 Invalid Argument error in IE7     -  
 invalid drive or directory     -  
 invalid argument on IE with script to center objects     -  
 integer value overflow     -  
 Dividing two Integer values     -  
 finding the largest integer     -  
 Integer value compare with equal sign     -  
 handle integer overflows and underflows     -  
 rounding performed under integer division     -  
 Ensuring integer are written as 32 bits     -  

Topic Tags

Java Variables