PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to check if each element in a string array is an integer?

 November 14, 2022     arrays, error-handling, integer, java, java.util.scanner     No comments   

Issue

I'm attempting an error check that determines whether all the the elements of an array are integers, i've been stuck for a long time though. any ideas on how to get started would be helpful.

Scanner scan = new Scanner(System.in);

System.out.print("Please list at least one and up to 10 integers: ");
String integers = scan.nextLine();

String[] newArray = integers.split("");

Solution

Using the String you made with the scanner, loop over a space-delimited list and check that each element is an integer. If they all pass, return true; otherwise return false.

Credit for the isInteger check goes to Determine if a String is an Integer in Java

public static boolean containsAllIntegers(String integers){
   String[] newArray = integers.split(" ");
   //loop over the array; if any value isnt an integer return false.
   for (String integer : newArray){
      if (!isInteger(integer)){
         return false;
      }   
   }   
   return true;
}

public static boolean isInteger(String s) {
  try { 
      Integer.parseInt(s); 
   } catch(NumberFormatException e) { 
      return false; 
   }
   // only got here if we didn't return false
   return true;
}


Answered By - astennent
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing