brainfrz

Parsing a list

Sep 27th, 2015
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class ScanTest
  4. {
  5.     public static int[] parseInts( String listStr )
  6.     {
  7.         String[] splitList = listStr.split(" ");
  8.         int[] listInts = new int[splitList.length];
  9.  
  10.         for (int i = 0; i < splitList.length; i++)
  11.         {
  12.             listInts[i] = Integer.parseInt(splitList[i]);
  13.         }
  14.  
  15.         return listInts;
  16.     }
  17.  
  18.     public static int[] parseInts( String listStr, String delimiter )
  19.     {
  20.         String[] splitList = listStr.split(delimiter);
  21.         int[] listInts = new int[splitList.length];
  22.  
  23.         for (int i = 0; i < splitList.length; i++)
  24.         {
  25.             listInts[i] = Integer.parseInt(splitList[i]);
  26.         }
  27.  
  28.         return listInts;
  29.     }
  30.  
  31.  
  32.     public static void main(String[] args)
  33.     {
  34.         Scanner input = new Scanner(System.in);
  35.         int[] ints;
  36.  
  37.         System.out.print("Please enter your list of numbers: ");
  38.         ints = parseInts(input.nextLine(), "+");
  39.  
  40.         for (int i = 0; i < ints.length; i++)
  41.         {
  42.             System.out.println(ints[i]);
  43.         }
  44.  
  45.  
  46.         // For fun and as proof of manipulability
  47.         System.out.println("\nIn reverse:");
  48.         for (int i = (ints.length - 1); i >= 0; i--)
  49.         {
  50.             System.out.println(ints[i]);
  51.         }
  52.  
  53.         System.out.println("\nMultiplied by 2:");
  54.         for (int i = 0; i < ints.length;  i++)
  55.         {
  56.             System.out.println(ints[i] * 2);
  57.         }
  58.     }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment