/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * Substring.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 1-3: * Write a program that takes two numbers and a string as command-line * arguments and prints out the substring of the string specified by the * two numbers. * * For example: * % java Substring hello 1 3 * * should print out: * ell * * Handle all possible exceptions that might arise because of bad input. * * @author Matthew Feldt * @version 1.0, 01/27/2001 16:02 */ package com.feldt.examples.basics; public class Substring { public static void main (String args[]) { final String usage = "Usage: java Substring string beginIndex endIndex"; int beginIndex, endIndex; // confirm the right number of command-line arguments if (args.length != 3) { System.err.println(usage); System.exit(-1); } try { // parse beginIndex and endIndex beginIndex = Integer.parseInt(args[1]); endIndex = Integer.parseInt(args[2]); // check for valid input if (beginIndex < 0) throw new NumberFormatException("beginIndex (" + beginIndex + ") must be greater than or equal 0."); if (beginIndex > endIndex) throw new NumberFormatException("beginIndex (" + beginIndex + ") must be less than endIndex (" + endIndex + ")."); if (! (endIndex < args[0].length())) throw new NumberFormatException("endIndex (" + endIndex + ") must be less than string length (" + args[0].length() + ")."); // increment endIndex so String.substring() will include endIndex endIndex++; // print the substring bounded by beginIndex and endIndex System.out.println(args[0].substring(beginIndex, endIndex)); } catch(NumberFormatException e) { System.err.println(e); } } }