Java :: Aufgabe #3 :: Lösung #4

22 Lösungen Lösungen öffentlich
#3

Quersumme berechnen und ausgeben

Anfänger - Java von Gustl - 12.08.2012 um 14:49 Uhr
Schreiben sie ein Konsolenprogramm, das eine int-zahl > 0 und < 10000 einliest,
ihre Quersumme berechnet und das Ergebnis wie folgt ausgibt:

Konsolenausgabe:

Zahl eingeben (0-10000): 3698
Quersumme: 3 + 6 + 9 + 8 = 26
#4
vote_ok
von tumble (20 Punkte) - 06.10.2012 um 14:22 Uhr
Kern der Lösung ist die calculateChecksum-Methode. Der Rest ist nur glue code, um die eng gesteckten Anforderungen der Aufgabe zu erfüllen. Zugegeben, die Methode nimmt direkt einen String, keinen int, aber die Adapter-Methode spare ich mir einfach mal. Der Einzeiler dafür ist banal.
Quellcode ausblenden Java-Code
	/**
	 * Calculates the checksum for the number given as {@link String}.
	 * 
	 * @param value
	 *            String representation of a number for which you want the
	 *            checksum to be calculated
	 * @return the checksum of the specified number
	 * @throws IllegalArgumentException
	 *             if you pass an empty {@link String}, null or a "dirty" String
	 *             (only numbers and a leading minus are allowed)
	 */
	static int calculateChecksum(String value) {
		if (value == null || value.isEmpty()) {
			throw new IllegalArgumentException("No empty input or null as argument allowed");
		}
		// Removing potentially leading minus sign from input string
		final boolean isNegative = value.startsWith("-") ? true : false;
		if (isNegative) {
			value = value.substring(1, value.length());
		}
		// Validating and splitting input string into single digits
		int[] digits = new int[value.length()];
		for (int i = 0; i < digits.length; i++) {
			if (!Character.isDigit(value.charAt(i))) {
				throw new IllegalArgumentException("Input value must not contain any characters but digits");
			}
			digits[i] = Character.getNumericValue(value.charAt(i));
		}
		int result = 0;
		// Actual checksum calculation
		for (int i = 0; i < digits.length; i++) {
			result += digits[i];
		}
		// Bringing back the minus according as input string was negative
		return isNegative ? -1 * result : result;
	}

	/**
	 * This is just glue code to fit the task's requirement.
	 * 
	 * @param input
	 */
	private static void evaluateInput(String input) {
		int valueOfInput = 0;
		try {
			valueOfInput = Integer.valueOf(input);
		} catch (NumberFormatException e) {
			// tolerating wrong input here yet, checksum method will handle it
			System.out.println("Your input was not a number, this will not end well...");
		}
		if (valueOfInput < 0 || valueOfInput > 10000) {
			System.out.println("Your input was outside the allowed range, but I am smart enough anyway. Result is being calculated.");
		}
		StringBuilder builder = new StringBuilder();
		builder.append("Checksum: ");
		final boolean isNegative = input.charAt(0) == '-';
		final char[] inputAsCharArray = input.toCharArray();
		for (int i = isNegative ? 1 : 0; i < inputAsCharArray.length; i++) {
			if (isNegative) {
				builder.append("-");
			}
			builder.append(inputAsCharArray[i]);
			builder.append(" + ");
		}
		builder.replace(builder.length() - 2, builder.length(), "= ");
		builder.append(Checksum.calculateChecksum(input));
		System.out.println(builder.toString());
	}

	public static void main(String[] args) {
		System.out.print("Enter a number (0-10000):");
		try (Scanner input = new Scanner(System.in)) {
			Checksum.evaluateInput(input.nextLine().trim());
		}
	}

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben
2128051

Du scheinst einen AdBlocker zu nutzen. Ich würde mich freuen, wenn du ihn auf dieser Seite deaktivierst und dich davon überzeugst, dass die Werbung hier nicht störend ist.