Java: Beispiele

Aus Flinkwiki
Wechseln zu: Navigation, Suche
Seitenübersicht
Zur Seite "Java"
Zur Seite "Eclipse"
Zur Seite "Netbeans"
Zur Seite "Kotlin"

Snippets

Zufallszahl:

int computerNumber = (int) (Math.random()*100 + 1);



Skripte

Wörter zählen

package de.kaiguenster.javaintro.wordcount;

import java.io.*;
import java.util.*;

/**
 * Ein einfacher Wortzähler, der aus einem beliebigen {@link InputStream} Wörter zählt. 
 * Wörter sind alle Gruppen von alphabetischen Zeichen. Das führt zum Beispiel beim 
 * abgekürzten "geht's" dazu, dass es als "geht" und "s" gezählt wird.
 * @author Kai
 */
public class WordCount {

    
    private InputStream source;
    private Map<String, Integer> wordCounts = new HashMap<>();
    private int totalCount = 0;
    
    /**
     * Erzeuge ein neues WordCount-Objekt aus einem {@link InputStream}
     * @param source - der Inputstream, aus dem gelesen wird. Sollte auch wirklich 
     * Textdaten enthalten, sonst ist das Ergebnis ungewiss.
     */
    public WordCount(InputStream source){
        this.source = source;
    }
    
    /**
     * Zählt Wörter aus dem InputStream
     */
    public void count(){
        try(Scanner scan = new Scanner(source)){
            scan.useDelimiter("[^\\p{IsAlphabetic}]+");
            while (scan.hasNext()){
                String word = scan.next().toLowerCase();
                totalCount++;
                wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
            }
        }    
    }

    /**
     * @return die Anzahl Wörter im Text
     */
    public int getTotalCount(){
        return totalCount;
    }
    
    /**
     * @return die Menge aller gefundenen Wörter im Text
     */
    public Set<String> getWords(){
        return Collections.unmodifiableSet(wordCounts.keySet());
    }
    
    /**
     * Findet, wie oft ein bestimmtes wort im Text vorkommt.
     * @param word - das Wort, nach dem gesucht wird
     * @return - wie oft das Wort im Text vorkommt
     */
    public int getCount(String word){
        Integer result = wordCounts.get(word);
        return result != null ? result : 0;
    }
    
    /**
     * Die Main-Methode wird ausgeführt, wenn WordCount als Programm aufgerufen wird. 
     * @param args - erwartet wird genau ein Aufrufparameter: ein Dateiname
     * @throws FileNotFoundException - diese Exception wird nie wirklich geworfen, 
     * der Fehler wird vorher abgefangen
     */
    public static void main(String[] args) throws IOException {
        if (args.length != 1) fail("WordCount requires exactly one file name as argument");
        File f = new File(args[0]);
        if (!f.exists()) fail("File does not exist " + f.getAbsolutePath());
        if (!f.isFile()) fail("Not a file " + f.getAbsolutePath());
        if (!f.canRead()) fail("File not readable " + f.getAbsolutePath());
        try(FileInputStream in = new FileInputStream(f)){
            WordCount count = new WordCount(new FileInputStream(f));
            count.count();
            System.out.println("Words in total: " + count.getTotalCount());
            count.getWords().stream().sorted().forEach((word) -> {
                System.out.println(word + ": " + count.getCount(word));
            });
        }
    }    
    
    /**
     * Hilfsmethode zu main: im Fehlerfall schreibt diese Methode eine Fehlermeldung 
     * und beendet das Programm
     * @param message - die Fehlermeldung
     */
    private static void fail(String message){
        System.err.println(message);
        System.exit(1);
    }
}


[1]


Fibonacci

package de.kaiguenster.javaintro.fibonacci;

/**
 * Java-Programm zur Berechnung von Fibonacci-Zahlen.
 * Auruf: java de.kaiguenster.javaintro.fibonacci.Fibonacci <n>. Dabei ist
 * n der Index der gesuchten Fibonacci-Zahl, <code>...Fibonacci 6</code> berechnet
 * die 6. Zahl der Folge: 5
 * @author Kai
 */
public class Fibonacci {

    public static int fibonacci(int n){
        if (n < 0) 
            throw new IllegalArgumentException("Fibonaccizahlen sind für negativen Index nicht definiert.");
        else if (n == 0) 
            return 0;
        else if (n == 1) 
            return 1;
        else
            return fibonacci(n - 1) + fibonacci(n - 2);
    }
    
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Aufruf: java de.kaiguenster.javaintro.fibonacci.Fibonacci <n>");
            System.exit(1);
        }
        int n = Integer.parseInt(args[0]);
        int result = fibonacci(n);
        System.out.println("Die " + n + ". Fibonacci-Zahl ist: " + result);
    }
}

[2]


Einen String umkehren

/**
 * Programm zum Umkehren von Strings in der Kommandozeile. 
 * @author Kai
 * @version 1.0
 */
package de.kaiguenster.javaintro.reverse;

/**
 *
 * @author Kai
 */
public class Reverse {

    /**
     * Kehrt einen <code>String</code> zeichenweise um. Zum Beispiel wird "Hallo, Welt!" zu "!tleW ,ollaH"
     * @param in der umzukehrende <code>String</code>
     * @return den umgekehrten <code>String</code>
     * @throws IllegalArgumentException wenn in == <code>null</code> ist.
     */
    public static String reverse(String in){
        if (in == null) throw new IllegalArgumentException("Parameter in muss übergeben werden.");
        StringBuilder out = new StringBuilder();
        for (int i = in.length() - 1; i >= 0; i--){
            out.append(in.charAt(i));
        }
        return out.toString();
    }
    
    public static void main(String[] args) {
        if (args.length != 1){
            System.out.println("Aufruf: java de.kaiguenster.javaintro.reverse.Reverse \"<text>\"");
            System.exit(1);
        }
        String reversed = reverse(args[0]);
        System.out.println(reversed);
    }
 
}

[3]






Quellen

Links


Youtube


Bücher


|