Java :: Aufgabe #3
22 Lösungen

Quersumme berechnen und ausgeben
Anfänger - Java
von Gustl
- 12.08.2012 um 14:49 Uhr
Schreiben sie ein Konsolenprogramm, das eine
ihre Quersumme berechnet und das Ergebnis wie folgt ausgibt:
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
Lösungen:

import java.io.* ; public class Quersumme { public static int quersumme ( String numberstring ) { int sum = 0 ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) sum += Integer.parseInt( numberstring.substring( i , i + 1 ) ) ; return sum ; } public static void main ( String[ ] args ) { System.out.print( "Zahl eingeben (0-10000): " ) ; int number ; try { BufferedReader in = new BufferedReader( new InputStreamReader ( System.in ) ) ; String numberstring = in.readLine( ) ; in.close( ) ; System.out.print( "Quersumme: " ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { System.out.print ( numberstring.substring( i , i + 1 ) ) ; if ( i == numberstring.length( ) - 1 ) { System.out.print( " = " ) ; System.out.println( quersumme( numberstring ) ) ; } else System.out.print( " + " ) ; } } catch ( IOException e ) { System.err.println( e.toString( ) ) ; } } }

import java.io.BufferedReader; import java.io.InputStreamReader; public class Quersumme { public static void main(String[] args) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("Zahl eingeben (0-10000): "); int number = Integer.parseInt(in.readLine()); // QS berechnen, wenn gültige Zahl, sonst Programmende if (number > 0 && number < 10000) berechneQuersumme(number); } catch (Exception e) { System.exit(1); } } /** * berechnet die Quersumme einer Zahl und gibt das Ergebnis auf der Konsole * aus * * @param nr * die Zahl, deren Quersumme zu berechnen ist * @return Quersumme zur weiteren Verarbeitung */ private static int berechneQuersumme(int nr) { // Ziffern in Array aufsplitten für Ausgabe char[] array = Integer.toString(nr).toCharArray(); int sum = 0; StringBuffer result = new StringBuffer("Quersumme: "); for (int i = 0; i < array.length; i++) { // Aufsummieren (letzte Ziffer) sum += nr % 10; // letzte Ziffer abschneiden nr /= 10; if (i != 0) result.append(" + "); result.append(array[i]); } result.append(" = ").append(sum); System.out.println(result.toString()); return sum; } }

import java.util.Scanner; public class quersumme { public static void main(String[] args) { Scanner s = new Scanner(System.in); String eingabe = "", ausgabe = ""; boolean ganzeZahl = false; int result = 0; while (!ganzeZahl) { System.out.print("Zahl eingeben (1-10000): "); eingabe = s.next(); if (!eingabe.matches("[0-9]+")) { System.out.println("Nur ganze Zahlen eingeben!"); } else if (Integer.parseInt(eingabe) <= 0 || Integer.parseInt(eingabe) > 10000) { System.out.println("Nur Zahlen >0 und <10000 eingeben!"); } else ganzeZahl = true; } for (int i = 0; i < eingabe.length(); i++) { if (i == 0) { ausgabe = "Quersumme: " + eingabe.charAt(i) + " "; } else { ausgabe = ausgabe + "+ " + eingabe.charAt(i) + " "; } String str = String.valueOf(eingabe.charAt(i)); result = result + Integer.parseInt(str); } ausgabe = ausgabe + "= " + result; System.out.println(ausgabe); } }
Konsolenausgabe:
Zahl eingeben (1-10000): 7896
Quersumme: 7 + 8 + 9 + 6 = 30
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.
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()); } }

import java.util.Scanner; import java.text.*; public class Quersumme { public static void main(String[] args) { Scanner s = new Scanner(System.in); boolean ganzeZahl = false; int zahl = 0; int Quersumme = 0; String ausgabe = ""; System.out.println("Bitte ganze Zahl eingeben!"); while(!ganzeZahl) { if(s.hasNextInt()) { zahl = s.nextInt(); ganzeZahl = true; } else { System.out.println("Bitte ganze Zahl eingeben!"); } } int hilfe = 0; while (zahl / Math.pow(10, hilfe) > 1) { hilfe++; } for (int j = hilfe-1; j >= 0; j--) { Quersumme = Quersumme + (int)(zahl / Math.pow(10, j) % 10); if(ausgabe == "") { ausgabe = "Quersumme: " + (int)(zahl / Math.pow(10, j) % 10); } else { ausgabe = ausgabe + " + " + (int)(zahl / Math.pow(10, j) % 10); } } ausgabe = ausgabe + " = " + Quersumme; System.out.println("Zahl eingegeben: " + zahl); System.out.println(ausgabe); } }
Geht für alle natürlichen Zahlen

//©2012 by Julius J. Hoffmann //written with Eclipse /** Unerwarteterweise hat das Casten der char Variablen bei mir nicht funktioniert, * weswegen ich die char-Var. in einem String zwischengespeichert habe. * Nur zur Vervollständigung hier noch einmal die Cast-Möglichkeit: * int no = (int)nr.charAt(index); * Wenn jemand eine Lösung weiß, kann er sich gerne bei mir melden :) */ import java.util.*; //Importiert Scanner zum Einlesen der Eingabe public class Quersumme { // Java-Klasse mit main-Methode ("ausführende Klasse") public static void main(String[] args) //main-Funktion { System.out.print("zahl eingeben (0-10000): "); //Gibt den String auf dem Bildschirm aus Scanner s = new Scanner(System.in); //legt das Scanner-Objekt an String nr = s.next(); //liest die manuelle Eingabe ein und speichert sie in dem String nr int length = nr.length(); //Bestimmt die Anzahl der Zeichen und speichert sie in length int qs = 0; //Initialisierung der Variablen qs System.out.print("Quersumme: "); /** * Initiieren einer for-Schleife * index - Die Stelle im String, welche addiert werden soll * index < length - Beenden des Hochzählens, wenn index am Ende des Strings angekommen ist * index++ - Weiterrücken des index um 1 Stelle nach jedem Schleifendurchlauf */ for (int index=0; index < length; index++) //s.o. { String a = String.valueOf(nr.charAt(index)); //Speichern der ausgewählten Zahl im Hilfsstring a || "Umformen" von char in String int no = Integer.parseInt(a); //"Umformen" (parsen) des String in einen Int-Wert, Speichern in no qs = qs+no; //Addieren der ausgewählten Stelle zum bisherigen Wert (Iteration) if(index<length-1) System.out.print(no + "+"); //Ausgabe der Summanden mit + else System.out.print(no); //Ausgabe des letzten Summanden } //Beenden der for-Schleife System.out.print(" = " + qs); //Ausgabe der Quersumme } //Beenden der main-Methode } //Schliessen der Klasse

import java.util.Scanner; public class quersummeBerechnen { public static void main(String[] args) { System.out.print("Zahl eingeben: "); Scanner sc = new Scanner(System.in); int ergebnis = 0; int eingegebeneZahl = sc.nextInt(); String zahl = Integer.toString(eingegebeneZahl); int[] splitted = new int[zahl.length()]; for (int i = 0; i < zahl.length(); i++) { splitted[i] = Character.getNumericValue(zahl.charAt(i)); } System.out.print("Quersumme: "); for (int i = 0; i < splitted.length; i++) { ergebnis += splitted[i]; System.out.print((i < splitted.length-1) ? splitted[i] + " + " : splitted[i]+" = "); } System.out.println(ergebnis); sc.close(); } }

/** * @author ElPapito * @date 07.05.2015 */ import java.util.Scanner; public class QuersummeBerechnenUndAusgeben { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Zahl eingeben (0-10000): "); String input = scanner.next(); scanner.close(); int sum = 0; System.out.print("Quersumme: "); for (int i = 0; i < input.length(); i++) { System.out.print(input.charAt(i) + " "); sum += (int) (input.charAt(i) - '0'); if (i < input.length() - 1) { System.out.print("+ "); } } System.out.println("= " + sum); } }

/* Schreiben sie ein Konsolenprogramm, das eine int-zahl > 0 * und < 10000 einliest, ihre Quersumme berechnet und das * Ergebnis wie folgt ausgibt: */ /* author: itsfalse * 22.01.2016 * Geschrieben mit Eclipse. */ import java.util.*; public class No3 { public static int berechneQuersumme(int zahl) { int summe = 0; while(0 != zahl) { summe = summe + (zahl % 10); zahl = zahl / 10; } return summe; } public static void main(String[] args) { System.out.print("Bitte Zahl eingeben (0-10000) :"); Scanner s = new Scanner(System.in); int y = s.nextInt(); System.out.print("Quersumme ist: "+ berechneQuersumme(y)); } }

/* @Author H.K. * @Date 21.02.2016 * * Programmbeschreibung: * Eingabe einer Zahl zwischen 1 und 10000 und Ausgabe der Querzahl der Eingabe */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class mainprogramv2 { public static void main ( String args[] ) throws IOException { int number = 0; String numberasstring = ""; number = inputnumber(number); numberasstring = Integer.toString(number); String querzahl = calcquerzahl(numberasstring); } public static int inputnumber(int number) throws IOException { while (number == 0) { System.out.print ( "Bitte eine Zahl zwischen 1 und 10000 eingeben: " ); BufferedReader input = new BufferedReader ( new InputStreamReader ( System.in ) ); String inputString = input.readLine(); if (inputString.matches("-?\\d+?")) { number = Integer.parseInt(inputString); } else { System.out.println("Eingabe ist keine Zahl!"); } if (number <= 0 || number >=10001) { System.out.println("Die eingegebene Zahl " +number +" liegt nicht zwischen 1 und 10000!"); number = 0; } } return number; } public static String calcquerzahl(String numberasstring) { int length = numberasstring.length() -1; String ausgabe = ""; int result = 0; String[] zahl = new String[length+1]; for (int i = 0; i <= length; i++) { zahl[i] = numberasstring.substring(i, i+1); } for (int i = 0; i < numberasstring.length(); i++) { if (i == 0) { ausgabe = "Quersumme: " + numberasstring.charAt(i) + " "; } else { ausgabe = ausgabe + "+ " + numberasstring.charAt(i) + " "; } String str = String.valueOf(numberasstring.charAt(i)); result = result + Integer.parseInt(str); } ausgabe = ausgabe + "= " + result; System.out.println(ausgabe); numberasstring = String.valueOf(ausgabe); return numberasstring; } }
Ausgabe:
Konsolenausgabe:
Bitte eine Zahl zwischen 1 und 10000 eingeben: 4567
Quersumme: 4 + 5 + 6 + 7 = 22
Ausgabe bei falscher Eingabe:
Konsolenausgabe:
Bitte eine Zahl zwischen 1 und 10000 eingeben: 20000
Die eingegebene Zahl 20000 liegt nicht zwischen 1 und 10000!
Bitte eine Zahl zwischen 1 und 10000 eingeben:

/* * Max F. 07.04.2016 */ public class Quersumme { public static void main(String[] args) { int Zahl1 = 0; int Zahl2 = 0; int quersumme = 0; boolean fehler = true; while (fehler) { try { System.out.println("Bitte Zahl eingeben:"); Scanner Eingabe = new Scanner(System.in); // Scanner erzeugen Zahl1 = Eingabe.nextInt(); // Eingabe einer int(!)-Variable // zuordnen Eingabe.close();// Erzeugten Scanner wieder Schließen Zahl2 = Zahl1;// Wert an Zahl2 übergeben (Für Ausgabe am Ende) fehler = false; //Schleife beenden } catch (Exception e) { // Exception abfangen falls Variable nicht als int gespeichert // werden kann System.out .println("Nur Eingabe von positiven, ganzen Zahlen möglich"); fehler = true; // Schleife erneut durchlaufen } } while (Zahl2 > 0) { quersumme += Zahl2 % 10; //Quersumme = Modulo aus Zahl + Modulo aus alter Zahl Zahl2 = Zahl2 / 10; //Zahl durch 10 teilen } System.out.println("Die Quersumme von " + Zahl1 + " ist " + quersumme); } }

/** * Created by peowpew on 17.01.2017. * * 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 * */ import java.util.Scanner; import java.util.InputMismatchException; public class Quersumme { static int zahl; public static void main (String [] args){ Scanner sc = new Scanner(System.in); try { zahl = sc.nextInt(); } catch (InputMismatchException e) { System.out.println("Bitte nur Integer"); } if ((zahl < 0) || (zahl > 10000)) { System.out.println("Bitte nur Integer zwischen 0 und 10000"); } else { System.out.println(getQuersumme(zahl)); } } private static String getQuersumme(int s_zahl){ String ergebnis = Integer.toString(s_zahl); String [] test = ergebnis.split(""); int i_ergebnis = 0; for (int i = 0;i<ergebnis.length();i++) { System.out.print(test[i]); if (i == ergebnis.length()-1) {System.out.print(" = ");} else {System.out.print(" + ");} i_ergebnis = i_ergebnis + Integer.parseInt(test[i]); } return Integer.toString(i_ergebnis); } }

import java.util.Scanner; public class main { public static void main(String[] args) { final Scanner in = new Scanner(System.in); String number; boolean repeat = false; do { System.out.print("Zahl eingeben (0-10000): "); number = in.nextLine(); try { int num = Integer.parseInt(number); if(number.length() > 5 || num < 0 || num > 10000) { System.out.println("Bitte nur Zahlen von 0 - 10000 eingeben."); repeat = true; } else { repeat = false; } } catch (NumberFormatException e) { System.out.println("Bitte nur Zahlen eingeben."); repeat = true; } } while(repeat); System.out.print("Quersumme: "); char[] chars = new char[number.length()]; number.getChars(0,number.length(), chars, 0); int sum = 0; for(int i = 0; i < chars.length; i++) { sum += Character.getNumericValue(chars[i]); System.out.print(chars[i]); if(i < chars.length -1) { System.out.print(" + "); } } System.out.print(" = " + sum); } }

class quersumme { public static void main (String[] args) throws java.lang.Exception { int eingabe = 3698; int summe = 0; String sEingabe = String.valueOf(eingabe); if(eingabe > 0 && eingabe < 10000) { for(int i = 0; i < sEingabe.length(); i++) { summe += Character.getNumericValue(sEingabe.charAt(i)); } System.out.println("Die Quersumme von " + eingabe + " ist " + summe + "."); } else { System.out.println("Die eingegebene Zahl liegt nicht zwischen 0 und 10.000."); } } }

package de.exception.quersumme_3; public class CrossSum { /** * Berechnet die Quersumme von arg. * * @param arg * @return Die Quersumme aus arg * @throws Exception */ public static int calculate(int arg) throws Exception { if(arg < 0 || arg > 1000) { throw new Exception("Parameter \"arg\" out of boundaries (0 - 1000), "+arg+" was given."); } int result = 0; for(char c : Integer.toString(arg).toCharArray()) { result += c - '0'; } return result; } /** * Berechnet die Quersumme von arg. * Gibt anschließend einen String mit der Berechnung und dem Ergebnis zurück. * * @param arg * @return Das Ergebnis und die Berechnung */ public static String calculate2(int arg) { if(arg < 0 || arg > 1000) { return "Parameter \"arg\" out of boundaries (0 - 1000), "+arg+" was given."; } int result = 0; String output = "Quersumme: "; for(char c : Integer.toString(arg).toCharArray()) { output += c + " + "; result += c - '0'; } output = output.substring(0, output.length() - 2); output += "= " + result; return output; } }

package de.exception.quersumme_3; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class CrossSumTest { @Test void test_calculate() { try { assertEquals(1, CrossSum.calculate(10)); assertEquals(2, CrossSum.calculate(11)); assertEquals(13, CrossSum.calculate(58)); assertEquals(27, CrossSum.calculate(999)); assertThrows(Exception.class, ()->{CrossSum.calculate(-1);}); assertThrows(Exception.class, ()->{CrossSum.calculate(1001);}); } catch (Exception e) { System.out.println(e.getMessage()); } } @Test void test_calculate2 () { assertEquals("Quersumme: 1 + 0 = 1", CrossSum.calculate2(10)); assertEquals("Quersumme: 1 + 1 = 2", CrossSum.calculate2(11)); assertEquals("Quersumme: 5 + 8 = 13", CrossSum.calculate2(58)); assertEquals("Quersumme: 9 + 9 + 9 = 27", CrossSum.calculate2(999)); assertEquals("Parameter \"arg\" out of boundaries (0 - 1000), -1 was given.", CrossSum.calculate2(-1)); assertEquals("Parameter \"arg\" out of boundaries (0 - 1000), 1001 was given.", CrossSum.calculate2(1001)); } }
Main Klasse:
Java-Code
Die Methoden welche ich aus meinem eigenem Methodensammlung package benutzt habe:
Java-Code

import Methodensammlung.Methoden; /** * Die Quersumme der Zahl welche der User eingegeben hat wird berechnet und ausgegeben. * * @author (nOrdan) * @version (08.06.2019) */ public class Quersumme { Methoden m = new Methoden(); public static void main(String [] args) { Quersumme q = new Quersumme(); q.inputs(); } private void inputs() { boolean valid1 = false; int zahl = 0; while (valid1 == false) { String input1 = m.userInput("Geben sie ihre Zahl ein, von welcher die Quersumme berechnet werden soll"); m.errorIntInput(input1); try { zahl = m.parseInt(input1); valid1 = true; } catch(Exception e) { m.errorMessage("Invalid user input","Invalid input"); } } berechnung(zahl); } private void berechnung(int zahl) { int quersumme = 0; int ausgabeZahl = zahl; while (zahl > 0) { quersumme += zahl % 10; zahl = zahl / 10; } m.informationMessage("Die Quersumme von " + ausgabeZahl + " ist " + quersumme,"Ergebnis"); } }
Die Methoden welche ich aus meinem eigenem Methodensammlung package benutzt habe:

public String userInput(String message) { return JOptionPane.showInputDialog(message); } public int parseInt(String input) { return Integer.parseInt(input); } public void errorIntInput(String input) { if (input == null) { System.exit(0); //Drückt der User auf abbrechen wird null zurück gegeben und das Programm wird beendet } else if (input.isEmpty() == true) { } } public void errorMessage(String message,String errorName) { JOptionPane.showMessageDialog(null,message,errorName,JOptionPane.ERROR_MESSAGE); } public void informationMessage(String message,String informationName) { JOptionPane.showMessageDialog(null,message,informationName,JOptionPane.INFORMATION_MESSAGE); }

import java.util.Scanner; public class Main { public static void main(String argsp[]) { int sum = 0; String userInput; Scanner s = new Scanner(System.in); System.out.print("Bitte Zahl zwischen 0 und 10000 eingeben: "); do { userInput = String.valueOf(s.next()); if(tryParseInt(userInput)) { if(Integer.parseInt(userInput) > 0 && Integer.parseInt(userInput) < 10000) { System.out.print("Quersumme: "); for (int i = 0; i < userInput.length(); i++) { System.out.print(userInput.charAt(i)); sum += (int) (userInput.charAt(i) - '0'); if (i < userInput.length() - 1) { System.out.print(" + "); } } System.out.println(" = " + sum); s.close(); } else { System.out.println("Dies ist keine gültige Eingabe, bitte eine gültige Zahl eingeben:"); } } else { System.out.println("Dies ist keine gültige Eingabe, bitte eine gültige Zahl eingeben:"); } } while(!tryParseInt(userInput) || Integer.parseInt(userInput) <= 0 || Integer.parseInt(userInput) >= 10000); } static boolean tryParseInt(String userInput) { try { Integer.parseInt(userInput); return true; } catch (NumberFormatException e) { return false; } } }
Fehlermeldung:
Dies ist keine gültige Eingabe, bitte eine gültige Zahl eingeben:
Konsolenausgabe:
Bitte Zahl zwischen 0 und 10000 eingeben: 5257
Quersumme: 5 + 2 + 5 + 7 = 19

import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Quersumme { public static void main(String[] args) { FrQuersumme frq = new FrQuersumme("Quersumme berechnen"); } } class FrQuersumme extends JFrame implements ActionListener { JLabel lblWBereich = new JLabel("Der gültige Wertebereich liegt zwischen 0 - 10000"); JLabel lblEingabe = new JLabel("Zahl eingeben: "); JTextField tfEingabe = new JTextField(12); JLabel lblAusgabe = new JLabel("Quersumme: "); JTextField tfAusgabe = new JTextField(12); JPanel pEingabe = new JPanel(); JPanel pAusgabe = new JPanel(); FrQuersumme(String titel) { super(titel); setVisible(true); setSize(350, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setLayout(new FlowLayout(FlowLayout.RIGHT, 25, 25)); tfEingabe.setHorizontalAlignment(JTextField.RIGHT); tfEingabe.addActionListener(this); tfAusgabe.setHorizontalAlignment(JTextField.RIGHT); tfAusgabe.setEditable(false); pEingabe.add(lblEingabe); pEingabe.add(tfEingabe); pAusgabe.add(lblAusgabe); pAusgabe.add(tfAusgabe); add(lblWBereich); add(pEingabe); add(pAusgabe); } public void berechneQuersumme(String sEingabe) { try { int iEingabe = Integer.parseInt(sEingabe); if (0 < iEingabe && iEingabe < 10001) { int[] aZahlen = new int[sEingabe.length()]; int summe = 0; StringBuilder sbErgebnis = new StringBuilder(); for (int i = 0; i < sEingabe.length(); i++) { aZahlen[i] = Integer.parseInt(sEingabe.substring(i, i + 1)); sbErgebnis.append(aZahlen[i]); if (i < (sEingabe.length() - 1)) { sbErgebnis.append("+"); } summe = summe + aZahlen[i]; } sbErgebnis.append("=" + summe); tfAusgabe.setText(sbErgebnis.toString()); } else { tfAusgabe.setText("kein gültige Zahl"); } } catch (NumberFormatException e) { tfAusgabe.setText("Bitte Ganzzahl eingeben!"); } } @Override public void actionPerformed(ActionEvent evt) { berechneQuersumme(tfEingabe.getText()); } }

import java.util.Scanner; /** * Schreiben sie ein Konsolenprogramm, das eine int-zahl > 0 und < 10000 einliest, * ihre Quersumme berechnet und das Ergebnis wie folgt ausgibt: * Zahl eingeben (0-10000): 3698 * Quersumme: 3 + 6 + 9 + 8 = 26 * * @author HR_SS * */ public class Quersumme { public static void main(String[] args) { System.out.print("Zahl eingeben (0-10000): "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); sc.close(); String str = ""; int sum = 0; if(input >= 0 && input <= 10000) { while(input != 0) { str += (input % 10); sum += input % 10; input /= 10; } System.out.print("Quersumme: "); for(int i = str.length()-1; i >= 0 ; i--) { System.out.print(str.charAt(i)); if(i >= 1) { System.out.print(" + "); }else { System.out.print(" = "); } } System.out.print(sum); }else { System.out.println("Falsche Eingabe..."); } } } /* Ausgabe: Zahl eingeben (0-10000): 2334 Quersumme: 2 + 3 + 3 + 4 = 12 Ausgabe: Zahl eingeben (0-10000): 454444 Falsche Eingabe... */
Diese Lösung liest tatsächlich eine Integer Variable ein!
Der Umweg über den String dient nur der korrekten Formatierung, wie in der Aufgabenstellung gewünscht...

import java.util.InputMismatchException; import java.util.Scanner; public class Quersumme { public int ergebnis = 0; private int quersumme; public void Quersumme() { boolean abort = false; while (!abort) { try { System.out.println("Gib eine Zahl ein"); Scanner scan = new Scanner(System.in); quersumme = scan.nextInt(); abort = true; } catch (InputMismatchException e) { e.printStackTrace(); System.out.println("Fehler: Gib eine Zahl ein!"); } } } public void showNumber() { System.out.println(quersumme); } public void calcQuersumme() { String numberlength = String.valueOf(quersumme); int lengthasint = numberlength.length(); int[] numbersOfQuersumme = new int[lengthasint]; int teiler = 10; numbersOfQuersumme[0] = quersumme % 10; for (int i = 1; i < lengthasint; i++) { numbersOfQuersumme[i] = (quersumme / teiler) % 10; teiler *= 10; } //addieren der Indizes for (int a = 0; a < lengthasint; a++) { ergebnis = ergebnis + numbersOfQuersumme[a]; } System.out.println("Die Quersumme von " + quersumme + " ist: " + ergebnis); } //public class Main { public static void main(String[] args) { Quersumme neueZahl = new Quersumme(); neueZahl.Quersumme(); neueZahl.showNumber(); neueZahl.calcQuersumme(); } }

import java.util.Scanner; public class QuersummeBerechnenUndAusgeben { public static void main(String[] args) { System.out.print("Gebe eine zahl zwischen 1 und 10000 ein: "); Scanner s = new Scanner(System.in); String zahl = Integer.toString(s.nextInt()); System.out.print("Quersumme: "); for (int i = 0; i < zahl.length(); i++) { if (i < zahl.length() - 1) { System.out.print(zahl.charAt(i) + " + "); } else { System.out.print(zahl.charAt(i) + " = " + zahl); } } } }

/** Returns the sum of digits of a given integer between 1 and 99'999. */ import java.util.Scanner; import java.lang.Math; import java.util.Iterator; import java.util.ArrayList; class SumOfDigits { public static void main(String[] args) { // get the input from the user Scanner scan = new Scanner(System.in); int input = 0; boolean inputType = false; while (!inputType) { System.out.println("Please enter an integer between 1 and 99'999:"); try { input = scan.nextInt(); if (input > 0 && input < 100000) { inputType = true; } else { System.out.println("Please enter an integer between 1 and 99'999!"); } } catch (Exception e) { System.out.println("Error: Input is not an integer!"); scan.next(); } } scan.close(); // get the digits of the integer ArrayList<Integer> digits = new ArrayList<>(); for (int i = 0; i < 5; i++) { digits.add(input / (int) Math.pow(10, 4-i)); input %= (int) Math.pow(10, 4-i); } // get the sum of digits int sum = 0; for (int i = 0; i < digits.size(); i++) { sum += digits.get(i); } // delete the leading 0s Iterator<Integer> iter = digits.iterator(); boolean bool = true; while (bool) { if(iter.next() == 0) { iter.remove(); } else { bool = false; } } // create the string String output = "The sum of digits is: "; for (int i = 0; i < digits.size(); i++) { if (i == digits.size() - 1) { output += digits.get(i); } else { output += digits.get(i) + " + "; } } System.out.println(output + " = " + sum); } }
Konsolenausgabe:
Please enter an integer between 1 and 99'999:
3698
The sum of digits is: 3 + 6 + 9 + 8 = 26