IP Umrechnung(Java):splittenIP

Aus IT074-Wiki

Wechseln zu: Navigation, Suche

Inhaltsverzeichnis

Beschreibung

  • erhält eine beliebige Zeichenkette
  • trennt die Eingabe hart nach einem Punkt
  • gibt einen String-Array aus 4 Elementen aus
  • mögliche Fehler
    • zu wenige Oktetten
    • zu viele Oktetten
    • leere Eingabe
    • falsche Trennzeichen

ausgegebener Array kann Buchstaben enthalten !

Code

Source

  • um spezifischere Fehlertexte ausgeben zu lassen, muss man die entsprechenden Stellen auskommentieren, diese stehen in der Regel einkommentiert oberhalb der zu werfenden Exception (throw new IPException(*)), z.B. // System.out.println("Too many dots");
//package ipconvert;
 
import java.util.*;
import java.io.*;
import java.lang.*;
 
public class IPProjekt1 {
 
	public static void main(String args[]) throws IOException {
		/* Some input magic, for testing this class as a standalone program
		 * Hint: Regardless if there are non-valid IPs given,
         	 * the program will continue the work [[Bild:Face-smile.png]]
		 * If args is not empty ... */
                if (args.length != 0 ){
                        // For each element in args ...
                        for (String strIp : args){
                                // ... do print results 
                                printResults(strIp);
                        }
                }
                // Else ...
                else {
                        // Print the quit hint
                        System.out.println("Type quit to exit");
                        // ... and open an interactive input instead
                        BufferedReader brInput = new BufferedReader (new InputStreamReader(System.in));
                        String strIp = new String();
                        // While infinity ...
                        while ( true ) {
                                // ... do receive input ...
                                strIp = brInput.readLine();
                                // ... except quit is typed, then break the infinite loop
                                if ( strIp.equals("quit")) break;
                                // Print results for the given input
                                printResults(strIp);
                        }
		}
	}
 
	protected static Integer printResults(String strInput) {
		// Create a new string buffer $strbresult for appending iteration elements
		StringBuffer strbResult = new StringBuffer();
		// Try to ...
		try {
			// ... iterate through the returned array from splittenIP
			for (String strOctet : splittenIP(strInput)) {
				// Append each array element to the string buffer
				strbResult.append(strOctet);
				// Append also a space character to beautify the output
				strbResult.append(" ");
			}
			// Print the string buffer to standard out
			System.out.println(strbResult);
		}
		// Except there is a IPException, in this case print the error message
		catch (IPException e) {
			//System.out.println(e);
		}
		// Return zero to return something, Java ... *tsts*
		return 0;
	}
 
	public static String [] splittenIP(String strIp) throws IPException {
		/* Defining Regular Expressions which will be used
		 * FIXME Here is a place where one could optimize the code.
		 * FIXME One could pre-compile the regexs, doing so would
         	 * lead to the reuse of the pre-compiled ones, which would be faster. */
 
		// Matches if only whitespace is inputted
		String strRegExOnlyWhitespace = "\\s*";	
		// Matches if the delimiter character is a non-alphanumeric character
		String strRegExDelimMismatch = ".*\\W+.*";
		// Matches if there is a non-alphanumeric character at the end of the input
               	String strRegExNoAlphaNumAtEndOfLine = ".*\\W$";
		// Matches if there is a non-aplhanumeric character at the beginning of the input
               	String strRegExNoAlphaNumAtBeginningOfLine = "^\\W.*";
		// Matches if multiple dots are given in a row
               	String strRegExTooManyDots = ".*[\\.]{2,}?.*";
 
		// Test if the input is empty
		if (( strIp.length() == 0) || strIp.matches(strRegExOnlyWhitespace)){
			// Throw a new IPException from IPException class with the given error code
			throw new IPException(6);
		}
 
		// Create a new tokenzizer to separate the input by a dot character
		StringTokenizer stTokenizer = new StringTokenizer(strIp, ".");
		int i = 0;
		// Count the ammount of tokens and write it in $iTokens
		int iTokens = stTokenizer.countTokens();
		// Create a new string array with $iToken elements
		String [] strArrayIp = new String[iTokens];
 
		// Determine, if there are multiple dots in row
		if (strIp.matches(strRegExTooManyDots)) {
			// Printout the error
			// System.out.println("Too many dots");
			// Throw a new IPException from IPException class with the given error code
			throw new IPException(7);
		}
 
		// Loop through tokens until no one has left ($iToken times)
		while (stTokenizer.hasMoreTokens()) {
			// Fill $strArrayIp with the currently processed token
       			strArrayIp[i] = stTokenizer.nextToken();
			// Determine, if the current token has one or more non alphamueric character(s) inside
			if (strArrayIp[i].matches(strRegExDelimMismatch)) {
				// Print the number of the wrong token and its content
				// System.out.println("Delimiter mismatch in token "+(i+1)+" ("+strArrayIp[i]+")");
				// Throw a new IPException from IPException class with the given error code
				throw new IPException(7);
			}
			// Increment counter $i
	       		i++;
		}
		// Determine if there were too few tokens given
		if (iTokens < 4) {
			// System.out.println("Too few octets, only "+iTokens+" given.");
			// Throw a new IPException from IPException class with the given error code
			throw new IPException(2);
		}
		// Determine if there were too many tokens given
		if (iTokens > 4) {
			// System.out.println("Too many octets, "+iTokens+" given.");
			// Throw a new IPException from IPException class with the given error code
			throw new IPException(3);
		}
		// Determine, when there were 4 tokens given, if ...
		if (iTokens == 4) {
			// ... the input begins with a non-alphanumeric character
			if (strIp.matches(strRegExNoAlphaNumAtBeginningOfLine)) {
				// System.out.println("First character wrong.");
				// Throw a new IPException from IPException class with the given error code
				throw new IPException(3);
			}
			// ... the input ends with a non-alphanumeric character
			if (strIp.matches(strRegExNoAlphaNumAtEndOfLine)) {
				// System.out.println("Last character wrong.");
				// Throw a new IPException from IPException class with the given error code
				throw new IPException(3);
			}
		}
		// If all went well up to here, return $strArrayIp
		return strArrayIp;
	}
}

SVN

Tags

  • hier liegen unterschiedliche Entwicklungsstadien v0.1, v0.2 usw.

https://trac.it074.de/ipconversion/browser/tags/IPProjekt1_incl_IPException

Persönliche Werkzeuge