Reader für Benutzereingabe in Eclipse importieren

Alpinwhite

Aktives Mitglied
Hallo, wir sollen für Benutzereingaben ein package verwenden, dass sich Input.readInt nennt. Wenn ich mit Eingabeaufforderung arbeite und die Datei im gleichen Ordner liegt wie die Java Datei funktioniert es problemlos. In Eclipse allerdings nicht. Da wir aber mit diesem Input arbeiten sollen frage ich mich wie ich es in Eclipse bekomme. Ich stecke jetzt bei der Benutzereingabe fest.

Wir sollen einen Zufallsarray mit 10 Stellen generieren, sortieren, ausgeben und den Benutzer dann eine Zahl dazwischen eingeben lassen, welche dann ebenfalls richtig einsortiert wird.

Java:
import java.util.Random;

public class Array {

    public static void main(String[] args) {
   
    int zufallsZahlen[] = new int[10];
    int z=0;
    int tobeSorted = 0;
    int benutzerEingabe = 0;
   
    System.out.print("Unsortiert: [");
           
    for(int i=0;i<zufallsZahlen.length;i++){
        zufallsZahlen[i] = (int) (Math.random()*20);
        tobeSorted=zufallsZahlen[i];
        z=i-1;
   
        if(i==zufallsZahlen.length-1){
                System.out.print(zufallsZahlen[i]);
        }
            else{
                System.out.print(zufallsZahlen[i]+",");
            }
   
       
       
            while(( z >=0) && (tobeSorted < zufallsZahlen[z])){
                zufallsZahlen[z+1] = zufallsZahlen[z];
                z= z-1;
       
        }
        zufallsZahlen[z+1] = tobeSorted;
    }   
        System.out.println("]");
        System.out.print("Sortiert: [");
        for(int i=0; i<zufallsZahlen.length; i++){
        System.out.print(zufallsZahlen[i]+",");
        }
        System.out.println("]");
        System.out.print("Welche positive ganze Zahl wollen Sie dem Array hinzufügen?");
        benutzerEingabe=Input.readInt();
    }

}
 

Alpinwhite

Aktives Mitglied
Ja eine ziemlich grosse Java Datei:

Java:
/*
* Input.java
* Institute for Pervasive Computing
* Johannes Kepler University Linz, Austria
* http://www.pervasive.jku.at
*
* Copyright (c) 2009 Michael Matscheko
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* last update: 2017-10-04 Andreas Riener
*/

import java.io.IOException;
import java.io.InputStream;

/**
* Input is a utility class, providing easy to use methods to read any primitive
* data type from the default system input, without having to deal with enhanced
* java concepts like exceptions, streams or error handling.
*
* <p>
* Example: <blockquote>
*
* <pre>
* System.out.print(&quot;Enter number a: &quot;);
* double a = Input.readDouble();
* System.out.print(&quot;Enter number b: &quot;);
* double b = Input.readDouble();
* System.out.println(&quot;a + b = &quot; + (a + b));
* </pre>
*
* </blockquote>
*
* <p>
* There are read-Methods for the following data types: <tt>char</tt>,
* <tt>boolean</tt>, <tt>byte</tt>, <tt>short</tt>, <tt>int</tt>,
* <tt>long</tt>, <tt>float</tt>, <tt>double</tt>, <tt>String</tt>
*
* <p>
* Values are expected to be on separate lines: You have to press enter after
* each value, therefore moving to the next line. If you have to read multiple
* values from a single line, use {@link #readString()} to read a full line as
* text, split it into several parts and convert each part into whatever data
* type you need. Of course this is not recommended for programming beginners.
*
* <p>
* There is one additional method to read several characters from a single line:
* {@link #readCharSequence}. This method will return character after character
* from one line. When the end of the line is reached, '\n' is returned as a
* line feed character (independent of the operating system), then
* readCharSequence will continue with the next line.
*
* <p>
* All methods will automatically handle errors:
* <ul>
* <li>If an invalid value is entered, the user is told to enter a new, correct
* value. (e.g., if an integer is expected and letters are entered, a message
* like "Not a valid int, please try again" will be displayed, and the user is
* forced to enter a new value) </li>
* <li>If an unresolvable error is encountered (e.g., the system input stream
* has been closed), the application is immediately terminated.</li>
* </ul>
*
* @version 1.2, 2012-10-25
*/
public class Input {

    // the System Input Stream
    private static final InputStream in = System.in;

    // line buffer
    private static StringBuilder line = new StringBuilder(1024);

    // current offset in line buffer (in readCharSequence)
    private static int lineOffset = -1;
  
    // last character that was read
    private static int lastChar = -1;

    // hide default constructor
    private Input() {
    }
  
    // read and return next character
    private static int nextChar() throws IOException {
        int c = in.read();
        if (c == -1) throw new IOException("Input stream closed.");
        return c;
    }

    // read and return next line, excluding any line feed chars
    private static String nextLine() {
        // clear buffer
        lineOffset = -1;
        line.setLength(0);
        // read until any line feed char is encountered
        try {
            int c;
            do {
                c = nextChar();
                if (c == '\n' && lastChar == '\r') c = nextChar(); // skip \n if last char was \r
                lastChar = c;
                line.append((char) c);
            } while (c != '\n' && c != '\r' && c != '\u0085' && c != '\u000C');
        } catch (IOException e) {
            // fatal error, terminate application
            System.out.println();
            System.out.println("Fatal Error: " + e.getMessage());
            System.exit(0);
        }
        line.setLength(line.length()-1);
        return line.toString();
    }

    /**
     * Read the next character from a character sequence.
     *
     * <p>
     * This method will return character after character, including a line feed
     * character. Entering "ab" and pressing enter will produce a character
     * sequence of <tt>'a'</tt>, <tt>'b'</tt> and <tt>'\n'</tt>. The line feed
     * character is always <tt>'\n'</tt>, no matter which operating system is
     * running.
     *
     * <p>
     * If reading directly from System.in, the different line feed sequences of
     * operating systems need to be taken into account:
     * <ul>
     * <li>Any Windows: <tt>'\r'</tt> followed by <tt>'\n'</tt></li>
     * <li>Any unix based system (e.g., Linux): <tt>'\n'</tt></li>
     * <li>MacOS prior to MacOS X (MacOS X is unix-based): <tt>'\r'</tt></li>
     * <li>There might be others, but it is highly unlikely you will encounter
     * any.</li>
     * </ul>
     *
     * <p>
     * Java provides the local line feed sequence as a String in the system
     * property <tt>line.separator</tt>. To retrieve this property, use the
     * method <tt>System.getProperty("line.separator")</tt>.
     *
     * <p>
     * Calling any other read method than readCharSequence will drop the
     * remaining characters of the sequence.
     *
     * <p>
     * The following example will read 2 characters from a character sequence,
     * ignore any remaining characters on the line, and then read a floating
     * point number: <blockquote>
     *
     * <pre>
     * System.out.print(&quot;Enter at least two characters: &quot;);
     * char c1 = Input.readCharSequence();
     * char c2 = Input.readCharSequence();
     * System.out.print(&quot;Enter a number: &quot;);
     * double x = Input.readDouble();
     * </pre>
     *
     * </blockquote>
     *
     * <p>
     * Note: readCharSequence will wait until a full line has been entered,
     * before returning the first character of the sequence. This is actually a
     * limitation by Java, since the user is allowed to edit the line: the
     * sequence may change until the enter key has been pressed.
     *
     * @return A <tt>char</tt> value.
     */
    public static char readCharSequence() {
        if (lineOffset < 0) {
            nextLine();
            lineOffset = 0;
        }
        if (lineOffset >= line.length()) {
            lineOffset = -1;
            return '\n';
        }
        return line.charAt(lineOffset++);
    }

    /**
     * Read a single character.
     *
     * <p>
     * Like all the other read-methods, readChar expects a SINGLE value
     * (character) in one line. If you want to read several consecutive
     * characters from a line, use the method {@link #readCharSequence}.
     *
     * @return A <tt>char</tt> value.
     */
    public static char readChar() {
        char c = '\0';
        boolean valid = false;
        do {
            String s = nextLine();
            if (s.length() == 1) {
                c = s.charAt(0);
                valid = true;
            } else {
                System.out.print("Not a valid char, please try again: ");
            }
        } while (!valid);
        return c;
    }

    /**
     * Read a boolean value.
     *
     * <p>
     * The expressions "true", "on", "yes" and "1" mean <tt>true</tt>,
     * "false", "off", "no" and "0" mean <tt>false</tt>. Evaluation is case
     * insensitive, so entering "TRUE" or "True" is also considered to be a
     * correct boolean value.
     *
     * @return A <tt>boolean</tt> value.
     */
    public static boolean readBoolean() {
        boolean b = false;
        boolean valid = false;
        do {
            String s = nextLine();
            if (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("on") || s.equalsIgnoreCase("yes")
                    || s.equals("1")) {
                b = true;
                valid = true;
            } else if (s.equalsIgnoreCase("false") || s.equalsIgnoreCase("off")
                    || s.equalsIgnoreCase("no") || s.equals("0")) {
                b = false;
                valid = true;
            } else {
                System.out.print("Not a valid boolean, please try again: ");
            }
        } while (!valid);
        return b;
    }

    /**
     * Read an 8 Bit integer number.
     *
     * <p>
     * Valid numbers have to be within [-128, 127].
     *
     * @return A <tt>byte</tt> value.
     */
    public static byte readByte() {
        byte n = 0;
        boolean valid = false;
        do {
            try {
                n = Byte.parseByte(nextLine());
                valid = true;
            } catch (NumberFormatException e) {
                System.out.print("Not a valid byte, please try again: ");
            }
        } while (!valid);
        return n;
    }

    /**
     * Read a 16 Bit integer number.
     *
     * <p>
     * Valid numbers have to be within [-32768, 32767].
     *
     * @return A <tt>short</tt> value.
     */
    public static short readShort() {
        short n = 0;
        boolean valid = false;
        do {
            try {
                n = Short.parseShort(nextLine());
                valid = true;
            } catch (NumberFormatException e) {
                System.out.print("Not a valid short, please try again: ");
            }
        } while (!valid);
        return n;
    }

    /**
     * Read a 32 Bit integer number.
     *
     * <p>
     * Valid numbers have to be within [-2147483648, 2147483647].
     *
     * @return An <tt>int</tt> value.
     */
    public static int readInt() {
        int n = 0;
        boolean valid = false;
        do {
            try {
                n = Integer.parseInt(nextLine());
                valid = true;
            } catch (NumberFormatException e) {
                System.out.print("Not a valid int, please try again: ");
            }
        } while (!valid);
        return n;
    }

    /**
     * Read a 64 Bit integer number.
     *
     * <p>
     * Valid numbers have to be within [-9223372036854775808,
     * 9223372036854775807].
     *
     * @return A <tt>long</tt> value.
     */
    public static long readLong() {
        long n = 0;
        boolean valid = false;
        do {
            try {
                n = Long.parseLong(nextLine());
                valid = true;
            } catch (NumberFormatException e) {
                System.out.print("Not a valid long, please try again: ");
            }
        } while (!valid);
        return n;
    }

    /**
     * Read a 32 Bit floating point number.
     *
     * <p>
     * Valid numbers have to be within [-3.403 x 1E38, 3.403 x 1E38] and it is
     * not allowed to enter special floating point values like Infinity or NaN
     * (Not-a-Number).
     *
     * <p>
     * Floating point numbers may be entered with an exponent, e.g., 1.2E8.
     *
     * @return A <tt>float</tt> value.
     */
    public static float readFloat() {
        float n = 0;
        boolean valid = false;
        do {
            try {
                n = Float.parseFloat(nextLine().replace(',', '.'));
                valid = !Float.isInfinite(n) && !Float.isNaN(n);
            } catch (NumberFormatException e) {
                // do nothing, valid = false
            }
            if (!valid) System.out.print("Not a valid float, please try again: ");
        } while (!valid);
        return n;
    }

    /**
     * Read a 64 Bit floating point number.
     *
     * <p>
     * Valid numbers have to be within [-1.798 x 1E308, 1.798 x 1E308] and it is
     * not allowed to enter special floating point values like Infinity or NaN
     * (Not-a-Number).
     *
     * <p>
     * Floating point numbers may be entered with an exponent, e.g., 1.2E8.
     *
     * @return A <tt>double</tt> value.
     */
    public static double readDouble() {
        double n = 0;
        boolean valid = false;
        do {
            try {
                n = Double.parseDouble(nextLine().replace(',', '.'));
                valid = !Double.isInfinite(n) && !Double.isNaN(n);
            } catch (NumberFormatException e) {
                // do nothing, valid = false
            }
            if (!valid) System.out.print("Not a valid double, please try again: ");
        } while (!valid);
        return n;
    }

    /**
     * Read a single text line.
     *
     * <p>
     * A single line, excluding any line feed characters, is returned. If an
     * empty line is entered, an empty String (<tt>""</tt>) is returned.
     * This method will never return <tt>null</tt>.
     *
     * <p>
     * There is no method to read multiple text lines at once. Call readString
     * repeatedly to do that.
     *
     * @return A <tt>String</tt> value.
     */
    public static String readString() {
        return nextLine();
    }

}
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
Haubitze_Broese Pattern für Links in RSS-Reader Java Basics - Anfänger-Themen 6
K Warum wird hier nur etwas in eine txt Datei geschrieben und nicht in alle drei (InputStream/OutputStream/Reader/Writer) Java Basics - Anfänger-Themen 1
R CSV Reader läuft nicht richtig an Java Basics - Anfänger-Themen 8
S Input/Output Reader/Writer finden file nicht Java Basics - Anfänger-Themen 3
L Klassen NFC Reader und JavaFx Problem -> threads? Java Basics - Anfänger-Themen 2
A Reader wohin werden Daten gespeichert? Java Basics - Anfänger-Themen 7
Textsurfer Erste Schritte CSV Import Reader Writer Java Basics - Anfänger-Themen 0
W Reader Java Basics - Anfänger-Themen 9
W Java XML-Reader: Content not allowed in Prolog Java Basics - Anfänger-Themen 7
D Jpg in BufferedImage Reader oder Array ablegen? Java Basics - Anfänger-Themen 5
H "Conways GameofLife - Vom Reader ins Array" Java Basics - Anfänger-Themen 5
C FileWriter bzw. Reader fehlerhaft Java Basics - Anfänger-Themen 6
Sogomn Input/Output Reader, Writer und Streams Java Basics - Anfänger-Themen 6
P txt reader Problem Java Basics - Anfänger-Themen 17
L buffered reader produziert zu viele und seltsame zeichen Java Basics - Anfänger-Themen 2
A Interface Reader interface verwenden Java Basics - Anfänger-Themen 4
S Input/Output Reader: "null" wenn While-Ende Java Basics - Anfänger-Themen 5
F Reader - brauche Hilfe Java Basics - Anfänger-Themen 19
M Reader-Problem Java Basics - Anfänger-Themen 5
Haubitze_Broese RSS-Reader? Java Basics - Anfänger-Themen 2
A Problem Reader Java Basics - Anfänger-Themen 39
Developer_X Sav-Data reader, fehler Java Basics - Anfänger-Themen 2
V Buffered Reader, erst ab bestimmter Zeile auslesen? Java Basics - Anfänger-Themen 8
K Probleme mit Buffered Reader Java Basics - Anfänger-Themen 8
P Buffered Reader an Anfang setzen Java Basics - Anfänger-Themen 4
D RSS Reader mit Redaktionssystem Java Basics - Anfänger-Themen 7
L Streams und Reader/Writer Java Basics - Anfänger-Themen 8
F Was gibt der Buffered Reader zurück bei Dateiende? Java Basics - Anfänger-Themen 2
T Writer/Reader Problem Java Basics - Anfänger-Themen 4
H Buffered Reader Java Basics - Anfänger-Themen 7
G Buffered REader, String, ist mein code korrekt? Java Basics - Anfänger-Themen 4
Kerstininer Vererbung Hilfe beim lernen von Objektorientierung für eine Klausur Java Basics - Anfänger-Themen 10
Sniper1000 Java 391 für Windows Java Basics - Anfänger-Themen 37
P Wieso kann ich als Index für einen Array einen Char angeben? Java Basics - Anfänger-Themen 3
benny1993 Java Programm erstellen für ein Fußball-Turnier Java Basics - Anfänger-Themen 3
V Durchschnittliche Volatility in Prozent für 4 Stunden berechnen Java Basics - Anfänger-Themen 14
P Welches SDK für das erstellen einer ausführbaren Datei? Java Basics - Anfänger-Themen 4
C negamax-Algorithmus für Tic-Tac-Toe spielt manchmal falsch Java Basics - Anfänger-Themen 10
D Apache HTTPClient für alle Fälle Java Basics - Anfänger-Themen 41
J Layout Manager, welcher ist der Richtige für mein Program? Java Basics - Anfänger-Themen 1
J Fehlermeldung unverständlich für Jakarta Java Basics - Anfänger-Themen 17
M Minimax-Algorithmus für Vier gewinnt Java Basics - Anfänger-Themen 11
M GUI für Vier-Gewinnt. Java Basics - Anfänger-Themen 4
I JPA Query für mehrere Klassen Java Basics - Anfänger-Themen 3
D Quellcode für cmd funktioniert nicht Java Basics - Anfänger-Themen 9
R Operatoren Rechenoperation in Java verwenden für Calculator Java Basics - Anfänger-Themen 2
R Operatoren Rechenoperation verwenden für Taschenrechner. Java Basics - Anfänger-Themen 32
Ostkreuz Counter für Booleanwerte Java Basics - Anfänger-Themen 8
B Regex Ausdrücke für Monate Java Basics - Anfänger-Themen 7
I BlueJ Queue Frage für Klausur Java Basics - Anfänger-Themen 2
K loop pausieren für eine bestimmte Anzahl? Java Basics - Anfänger-Themen 1
Jxhnny.lpz Randomisier für Buttons Java Basics - Anfänger-Themen 13
W Intuitive interface für Komponenten Java Basics - Anfänger-Themen 4
M "Class<T> clazz" im Constructor - auch für int möglich? Java Basics - Anfänger-Themen 7
B Schrankensystem mit Farberkennung für Flashgame funktioniert nicht wie geplant Java Basics - Anfänger-Themen 4
I Code für Bezahlsystem (auch bei Offline Aktivität) Java Basics - Anfänger-Themen 7
U jUnit 5 Test für eine addMethode Java Basics - Anfänger-Themen 18
M monte carlo Algorithmus für 4 gewinnt Java Basics - Anfänger-Themen 12
frager2345 Java Singleton Muster -> Methode für Konstruktor mit Parametern Java Basics - Anfänger-Themen 3
izoards Sortier Algorithmus für Bounding Box Elememte Links nach Rechts und von Oben nach Unten Java Basics - Anfänger-Themen 33
M generate Methode für Streams Java Basics - Anfänger-Themen 6
I Datenmodell für "Tags" Java Basics - Anfänger-Themen 6
Lion.King for-Kontrollstruktur für Pyramide Java Basics - Anfänger-Themen 8
B Mit Countdown Midnestdauer für Teilaufgabenerledigung erzwingen Java Basics - Anfänger-Themen 8
J File length als Prüfwert für Download Java Basics - Anfänger-Themen 5
K Spieleidee gesucht für Informatikprojekt - JAVA (BlueJ)? Java Basics - Anfänger-Themen 15
P Zähler Variable für mehrere Objekte Java Basics - Anfänger-Themen 6
javamanoman Java für Online Banking Java Basics - Anfänger-Themen 12
NadimArazi Wie kann ich eine collision detection für die Paddles in meinem Pong Programm hinzufügen? Java Basics - Anfänger-Themen 4
JordenJost Java ist auch eine Insel für Anfänger Java Basics - Anfänger-Themen 2
P9cman Tipps für Rekursive Aufgaben mit Strings oder allgemein Java Basics - Anfänger-Themen 2
F Suche nach betreuender Person für eine Jahresarbeit der 12. Klasse. Java Basics - Anfänger-Themen 6
I SQL / JPA Query für StartDate und EndDate Java Basics - Anfänger-Themen 1
T getMethode für ein Array Java Basics - Anfänger-Themen 2
Fats Waller Farben mixen für den Hintergrund ? Java Basics - Anfänger-Themen 1
H Suche jemanden für kleine Uni-Abgabe/ mit Vergütung Java Basics - Anfänger-Themen 1
K Für was braucht man die left und right shift operatoren? Was bringen die, also welchen Zweck haben die? Java Basics - Anfänger-Themen 15
N Api nur für Textdatein (.txt) Java Basics - Anfänger-Themen 2
bluetrix Programmieren eines Bots für Zahlen-Brettspiel Java Basics - Anfänger-Themen 9
M Wie kann eine Methode für ein vorhandenes "Array von char" einen Index-Wert zurückliefern? Java Basics - Anfänger-Themen 3
R Ist Java das Richtige für mich? Java Basics - Anfänger-Themen 4
E Mittelquadratmethode für Hexadezimalzahlen Java Basics - Anfänger-Themen 1
P Einfacher regulärer Ausdruck (RegEx) für E-Mail-Adressen Java Basics - Anfänger-Themen 2
Kiki01 Wie würde eine geeignete Schleife aussehen, die die relative Häufigkeit für jeden Charakter in einem Text bestimmt? Java Basics - Anfänger-Themen 3
N Fehler im Code (Aufgabe für Anfänger) Java Basics - Anfänger-Themen 11
O Wie erstelle ich eine Instanz in einer Klasse für die ich die Instanz will? Java Basics - Anfänger-Themen 4
S BubbleSort für ArrayLists Java Basics - Anfänger-Themen 3
T Übungsbuch für Anfänger Java Basics - Anfänger-Themen 3
L Konzept für Quiz Java Basics - Anfänger-Themen 33
D Methoden Plathhalter für Integer in einer Methode Java Basics - Anfänger-Themen 19
B Datentyp für Einzelnes Objekt oder Liste Java Basics - Anfänger-Themen 9
D Welche GUI Library für eine Client Server Chat App Java Basics - Anfänger-Themen 14
T Algorithmus für Index mit min-Wert Java Basics - Anfänger-Themen 2
Aqtox Hallo ich muss für die Schule ein Wuerfell Duell erstellen jedoch habe ich ein fehler Java Basics - Anfänger-Themen 4
L loop für Namen Java Basics - Anfänger-Themen 11
kxrdelis Konstruktor für ein Rechtwinkliges Dreieck Java Basics - Anfänger-Themen 10
S Fehler bei Code mit SubStrings für mich nicht auffindbar. Java Basics - Anfänger-Themen 4
nevel Programm für die Summer der Zahlen 1- 1ß Java Basics - Anfänger-Themen 12
I Entity erstellen, die für API gedacht ist Java Basics - Anfänger-Themen 33
C Archiv für eigene Klassen Java Basics - Anfänger-Themen 9

Ähnliche Java Themen

Neue Themen


Oben