matheraum.de
Raum für Mathematik
Offene Informations- und Nachhilfegemeinschaft

Für Schüler, Studenten, Lehrer, Mathematik-Interessierte.
Hallo Gast!einloggen | registrieren ]
Startseite · Forum · Wissen · Kurse · Mitglieder · Team · Impressum
Forenbaum
^ Forenbaum
Status Mathe
  Status Schulmathe
    Status Primarstufe
    Status Mathe Klassen 5-7
    Status Mathe Klassen 8-10
    Status Oberstufenmathe
    Status Mathe-Wettbewerbe
    Status Sonstiges
  Status Hochschulmathe
    Status Uni-Analysis
    Status Uni-Lin. Algebra
    Status Algebra+Zahlentheo.
    Status Diskrete Mathematik
    Status Fachdidaktik
    Status Finanz+Versicherung
    Status Logik+Mengenlehre
    Status Numerik
    Status Uni-Stochastik
    Status Topologie+Geometrie
    Status Uni-Sonstiges
  Status Mathe-Vorkurse
    Status Organisatorisches
    Status Schule
    Status Universität
  Status Mathe-Software
    Status Derive
    Status DynaGeo
    Status FunkyPlot
    Status GeoGebra
    Status LaTeX
    Status Maple
    Status MathCad
    Status Mathematica
    Status Matlab
    Status Maxima
    Status MuPad
    Status Taschenrechner

Gezeigt werden alle Foren bis zur Tiefe 2

Navigation
 Startseite...
 Neuerdings beta neu
 Forum...
 vorwissen...
 vorkurse...
 Werkzeuge...
 Nachhilfevermittlung beta...
 Online-Spiele beta
 Suchen
 Verein...
 Impressum
Das Projekt
Server und Internetanbindung werden durch Spenden finanziert.
Organisiert wird das Projekt von unserem Koordinatorenteam.
Hunderte Mitglieder helfen ehrenamtlich in unseren moderierten Foren.
Anbieter der Seite ist der gemeinnützige Verein "Vorhilfe.de e.V.".
Partnerseiten
Dt. Schulen im Ausland: Mathe-Seiten:Weitere Fächer:

Open Source FunktionenplotterFunkyPlot: Kostenloser und quelloffener Funktionenplotter für Linux und andere Betriebssysteme
StartseiteMatheForenSoftwaretechnik und Programmierungkleines Java programm
Foren für weitere Schulfächer findest Du auf www.vorhilfe.de z.B. Geschichte • Erdkunde • Sozialwissenschaften • Politik/Wirtschaft
Forum "Softwaretechnik und Programmierung" - kleines Java programm
kleines Java programm < Softwaretechnik+Pro < Praktische Inform. < Hochschule < Informatik < Vorhilfe
Ansicht: [ geschachtelt ] | ^ Forum "Softwaretechnik und Programmierung"  | ^^ Alle Foren  | ^ Forenbaum  | Materialien

kleines Java programm: Korrektur
Status: (Frage) beantwortet Status 
Datum: 18:07 Sa 30.10.2010
Autor: BlackSalad

hallo,

also ich sollte ein spiel programmierne, indem ich an den mit TODO gekennzeichneten Stellen code einfüge. zuerst sollte eine Zahl vom computer erraten werden, die er sich vorher "ausgedacht" hat und dann sollte der Mensch eine Zahl systematisch erraten, die sich der PC ausgedacht hat. Hab hier jetzt einen haufen Code und funktionieren tut es nicht und mir wärs deswegen lieb, wenn das jemand so korrigieren könnte, dass es dann im Endeffekt stimmt und ich meine Fehler sehe.








/**
* In this game, I will first choose a secret random number, and one of us (either you or me) must guess it iteratively... <br/>
* All I will reveal for a guess is whether the guess is higher or lower than the secret random number in my mind.<br/>
* You may use everything that is provided to you in this class, but<br/>
* DO NOT CHANGE ANYTHING except for the bodies of the methods marked with "ToDo"!
*
*/
public class ChildrensGame {
/**
* The smallest possible number I may choose.
*/
protected final int MIN;

/**
* The greatest possible number I may think of.
*/
protected final int MAX;

/**
* Just for statistics...<br/>
*/
protected long numberOfGuesses = 0;

/**
* The secret number between {@link #MIN} and {@link #MAX} (both inclusive) to be guessed.
*/
protected final int toBeGuessed;

/**
* Let the games begin (here)!<br/>
* There is no need for you to change this method in any way (but you should test your code with different min/max-values...)!<br/>
* The secret number to be guessed is chosen between {@link #MIN} and {@link #MAX} (both inclusive).<br/>
* @see <a href="http://download-llnw.oracle.com/javase/6/docs/api/java/lang/Math.html#random()">Math.random()</a>
* @param args If you don't provide one (whatever), I'll play by myself - otherwise you can puzzle it out...
*/
public static void main(String[] args) {
int min = 1;
int max = 100;
int toBeGuessed = min + ((int)(Math.random() * (max - min + 1)));
ChildrensGame childrensGame = new ChildrensGame(min, max, toBeGuessed);
if (args.length > 0) {
childrensGame.playWithYou();
} else {
childrensGame.playByMyself();
}
}

/**
* Initialises a new game.<br/>
*/
protected ChildrensGame(int min, int max, int toBeGuessed) {
this.MIN = min;
this.MAX = max;
this.toBeGuessed = toBeGuessed;
}

/**
* Checks whether {@code myGuess} is less than, equal or greater than the real secret number {@link #toBeGuessed} and returns the "encoded result" correspondingly.
* @param myGuess This is the guess to be evaluated.
* @return
* * * * *
-1: if {@code myGuess} is less than the secret value {@link #toBeGuessed}.
0: if {@code myGuess} is exactly the the secret value (yeah!)
1: if {@code myGuess} is greater than the secret value.

*/
protected int checkGuess(int myGuess) {
int result;

  

  if(myGuess < toBeGuessed)
    result = -1;
  else if(myGuess > toBeGuessed)
    result = 1;
  else
    result = 0;



System.out.println("The " + ++numberOfGuesses + ". guess is [mm] \"" [/mm] + myGuess + [mm] "\" [/mm] and it is " + (result < 0 ? "too small." : result > 0 ? "too high." : "PERFECT!"));
return result;
}

/**
* I'll choose the secret number {@link #toBeGuessed} and a human player must try to guess it.
*/
protected void playWithYou() {{


    int toBeGuessed;    // int Variable für die Zufallszahl
    int myGuess;        // int Variable für die Eingabe des Nutzers
    int numberOfGuesses;        // int Variable, die die Versuche mitzählt
    boolean checkGuess = false;}       // Boolean/Wahrheitsvariable für die Schleifenwiederholung, solange
                                // noch nicht die richtige Zahl eingegeben wurde.
  
  

    public playWithYou()    // Konstruktor der Klasse.
      numberOfGuesses = 1;            // Zählervariable wird mit 1 initialisiert.
        
        generateRandomNum();    // Ruft die Methode "generateRandomNum()" auf.
        System.out.println("Bitte geben Sie ihre Zahl ein: ");
    
    
        
        
        while(checkGuess(0)!=toBeGuessed){          /* Solange 'erraten' auf false steht(was es ist, bis die richtige Zahl eingegeben wird,
                           * solange soll diese Schleife wiederholt ausgeführt werden.
                           * Die Schreibweise "!erraten" ist äquivalent zur Schreibweise "erraten == false".
                           */
            
                readInput();    // Ruft die Methode "readInput()" auf, um wiederholt die Nutzereingabe einzulesen.
                compare();     // Vergleicht in jedem Schleifendurchgang die neue Eingabe des Nutzers mit der Zufallszahl.
        
        }}
    
    private void compare() {
// TODO Auto-generated method stub

}

private void readInput() {
// TODO Auto-generated method stub

}

public void generateRandomNum(){
        System.out.println("***Zufallszahl wurde erzeugt***");
        Random ran = new Random();
        toBeGuessed = ran.nextInt(101);/* Hier wird die Zufallszahl erzeugt und in der globalen int Variable  
                             * "zufallsszahl" gespeichert. '101', weil der höchste Wert der übergebenen Zahl exklusiv
                             * behandelt wird. "ran.nextInt(100)" würde also nur eine Zufallszahl zwischen 0 und 99
                             * ermitteln.
                                                         */
        
    
    
    public void readInput();{    /* Hier wird die Eingabe des Nutzers eingelesen.
                         * Schenke dem "try/catch" garkeine Beachtung, auch die Art und Weise,
                         * wie die Eingabe eingelesen wird, ist jetzt nicht so wichtig, das muss man nach
                         * 1, 2 Wochen Java noch nicht verstehen.
                         */
        try{

myGuess = Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void compare();                /* Diese Methode vergleich immer die neu eingegebene Zahl des Nutzers mit der
                            * Zufallszahl.
                            * Bei jeder falschen Eingabe, wird ein Hinweis ausgegeben, ob die eingegebene
                            * Zahl zu groß oder zu klein war. Außerdem wird der Zähler für die Versuche
                            * immer um 1 hochgezählt.
                            */
    
        if (myGuess < toBeGuessed){
            System.out.println("Ihre Zahl ist zu klein!");
            numberOfGuesses++;      // Zähler wird um 1 erhöht. Äquivalent zu "zähler = zähler + 1" oder "zähler += 1"
        }
        else if (myGuess > toBeGuessed){
            System.out.println("Ihre Zahl ist zu groß!");
            numberOfGuesses++;
        }
        else{
            System.out.println("Sie haben richtig geraten! [mm] :)\nSie [/mm] benötigten dafür " + numberOfGuesses + " Versuche.");
            numberOfGuesses++;
            checkGuess = true;           /* "erraten" wird auf "true" gesetzt, sodass sich die Schleife weiter oben
                             * nicht mehr wiederholt.
                             */
        }}}
    



/**
* I'll just pretend that I don't know the value {@link #toBeGuessed} and puzzle myself over it just like a human player.<br/>
* I will do my best to find the secret number within as few steps as possible!
*/
protected void playByMyself(){

}
//  TODO
/**
* Helper infrastructure, used to read human input.
*/
protected int inputInt() {
try {
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
while(true) {
System.out.print("Tell me your guess: ");
String inputString = reader.readLine();
if (inputString == null) throw new java.io.EOFException();
try {
return Integer.parseInt(inputString);
} catch (NumberFormatException e) {
System.out.println("- Your input [mm] (\"" [/mm] + inputString + [mm] "\") [/mm] is not a valid number! Try again...");
}
}
} catch (Throwable throwable) {
System.err.println();
System.err.println("- Sorry, it just doesn't work here with you... I'll shut down now!");
System.exit(1);
return 0;
}
}




Ich würd mich drüber freuen, wenn mir meine Fehler aufgezeigt werden würden, vielelicht mit fettmarkierung, sodass ich sie dann gut nachvollziehen kann.

Lg

        
Bezug
kleines Java programm: Antwort
Status: (Antwort) fertig Status 
Datum: 11:30 Mo 01.11.2010
Autor: jarling

Soll playWithYou eine Funktion oder eine innere Klasse sein? Es kann nur einen Konstruktor haben, wenn es eine Klasse ist. Du kannst es aber so childrensGame.playWithYou(); in der Funktion main nur aufrufen, wenn es eine Funktion wäre.

Hinweis: Funktionsamen haben einen kleinen Anfangsbuchstaben, Klassen beginnen mit großem Anfangsbuchstaben.

Ich würde davon ausgehen, dass es eine Funktion ist und keine innere Klasse, da in main() steht, dass das dort nicht geändert werde braucht.

protected int toBeGuessed; wird in der Funktion generateRandomNum() neu belegt, darf also nicht final deklariert werden.

Ich habe einige Zeilen geändert, es lässt sich jetzt kompilieren...

1:
2: /*
3:  * To change this template, choose Tools | Templates
4:  * and open the template in the editor.
5:  */
6:
7: package childrensgame;
8:
9: import java.io.BufferedReader;
10: import java.io.InputStreamReader;
11: import java.util.Random;
12:
13: /**
14:  * In this game, I will first choose a secret random number, and one of us (either you or me) must guess it iteratively... <br/>
15:  * All I will reveal for a guess is whether the guess is higher or lower than the secret random number in my mind.<br/>
16:  * You may use everything that is provided to you in this class, but<br/>
17:  * DO NOT CHANGE ANYTHING except for the bodies of the methods marked with "ToDo"!
18:  *
19:  */
20: public class ChildrensGame {
21:
22: /**
23:  * The smallest possible number I may choose.
24:  */
25: protected final int MIN;
26:
27: /**
28:  * The greatest possible number I may think of.
29:  */
30: protected final int MAX;
31:
32: /**
33:  * Just for statistics...<br/>
34:  */
35: protected long numberOfGuesses = 0;
36:
37: /**
38:  * The secret number between {@link #MIN} and {@link #MAX} (both inclusive) to be guessed.
39:  */
40: protected int toBeGuessed;
41:
42: boolean checkGuess = false;
43:
44: int myGuess;
45:
46: /**
47:  * I'll just pretend that I don't know the value {@link #toBeGuessed} and puzzle myself over it just like a human player.<br/>
48:  * I will do my best to find the secret number within as few steps as possible!
49:  */
50: protected void playByMyself() {
51:
52: }
53:
54: /**
55:  * Let the games begin (here)!<br/>
56:  * There is no need for you to change this method in any way (but you should test your code with different min/max-values...)!<br/>
57:  * The secret number to be guessed is chosen between {@link #MIN} and {@link #MAX} (both inclusive).<br/>
58:  * @see <a href="http://download-llnw.oracle.com/javase/6/docs/api/java/lang/Math.html#random()">Math.random()</a>
59:  * @param args If you don't provide one (whatever), I'll play by myself - otherwise you can puzzle it out...
60:  */
61: public static void main(String[] args)
62: {
63: int min = 1;
64: int max = 100;
65: int toBeGuessed = min + ((int)(Math.random() * (max - min + 1)));
66: ChildrensGame childrensGame = new ChildrensGame(min, max, toBeGuessed);
67: if (args.length > 0) {
68: childrensGame.playWithYou();
69: } else {
70: childrensGame.playByMyself();
71: }
72: }
73:
74: /**
75:  * Initialises a new game.<br/>
76:  */
77: protected ChildrensGame(int min, int max, int toBeGuessed) {
78: this.MIN = min;
79: this.MAX = max;
80: this.toBeGuessed = toBeGuessed;
81: }
82:
83: /**
84:  * Checks whether {@code myGuess} is less than, equal or greater than the real secret number {@link #toBeGuessed} and returns the "encoded result" correspondingly.
85:  * @param myGuess This is the guess to be evaluated.
86:  * @return
87:  *
88:  *
89:  *
90:  *
91:  * -1 : if {@code myGuess} is less than the secret value {@link #toBeGuessed}.
92: 0 : if {@code myGuess} is exactly the the secret value (yeah!)
93: 1 : if {@code myGuess} is greater than the secret value.
94:  */
95: protected int checkGuess(int myGuess)
96: {
97: int result;
98:
99: if(myGuess < toBeGuessed)
100: result = -1;
101: else if(myGuess > toBeGuessed)
102: result = 1;
103: else
104: result = 0;
105:
106: System.out.println("The " + ++numberOfGuesses +
107: ". guess is  + myGuess +  and it is " +
108:   (result < 0 ? "too small." : result > 0 ? "too high." : "PERFECT!"));
109:
110: return result;
111: }
112:
113: /**
114:  * I'll choose the secret number {@link #toBeGuessed} and a human player must try to guess it.
115:  */
116: protected void playWithYou() {
117: //protected class playWithYou {
118:
119:
120:     //int toBeGuessed;    // int Variable für die Zufallszahl
121:     //int myGuess;        // int Variable für die Eingabe des Nutzers
122:     //int numberOfGuesses;        // int Variable, die die Versuche mitzählt
123:     //boolean checkGuess = false;      // Boolean/Wahrheitsvariable für die Schleifenwiederholung, solange
124:                                 // noch nicht die richtige Zahl eingegeben wurde.
125:
126:     //public playWithYou() {    // Konstruktor der Klasse.
127:       numberOfGuesses = 1;            // Zählervariable wird mit 1 initialisiert.
128:
129:         generateRandomNum();    // Ruft die Methode "generateRandomNum()" auf.
130:         System.out.println("Bitte geben Sie ihre Zahl ein: ");
131:
132:
133:
134:
135:         while(checkGuess(0)!=toBeGuessed){          /* Solange 'erraten' auf false steht(was es ist, bis die richtige Zahl eingegeben wird,
136:                            * solange soll diese Schleife wiederholt ausgeführt werden.
137:                            * Die Schreibweise "!erraten" ist äquivalent zur Schreibweise "erraten == false".
138:                            */
139:
140:                 readInput();    // Ruft die Methode "readInput()" auf, um wiederholt die Nutzereingabe einzulesen.
141:                 compare();     // Vergleicht in jedem Schleifendurchgang die neue Eingabe des Nutzers mit der Zufallszahl.
142:
143:         }
144: }
145:
146:     //private void compare() {
147: // TODO Auto-generated method stub
148:
149: //}
150:
151: //private void readInput() {
152: // TODO Auto-generated method stub
153:
154: //}
155:
156: public void generateRandomNum(){
157:         System.out.println("***Zufallszahl wurde erzeugt***");
158:         Random ran = new Random();
159:         toBeGuessed = ran.nextInt(101);/* Hier wird die Zufallszahl erzeugt und in der globalen int Variable
160:                              * "zufallsszahl" gespeichert. '101', weil der höchste Wert der übergebenen Zahl exklusiv
161:                              * behandelt wird. "ran.nextInt(100)" würde also nur eine Zufallszahl zwischen 0 und 99
162:                              * ermitteln.
163:                                                          */
164: }
165:
166:
167:     public void readInput() {    /* Hier wird die Eingabe des Nutzers eingelesen.
168:                          * Schenke dem "try/catch" garkeine Beachtung, auch die Art und Weise,
169:                          * wie die Eingabe eingelesen wird, ist jetzt nicht so wichtig, das muss man nach
170:                          * 1, 2 Wochen Java noch nicht verstehen.
171:                          */
172:         try{
173:
174: myGuess = Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
175:         }catch(Exception e){
176:             e.printStackTrace();
177:         }
178:     }
179:
180:     public void compare() {                /* Diese Methode vergleich immer die neu eingegebene Zahl des Nutzers mit der
181:                             * Zufallszahl.
182:                             * Bei jeder falschen Eingabe, wird ein Hinweis ausgegeben, ob die eingegebene
183:                             * Zahl zu groß oder zu klein war. Außerdem wird der Zähler für die Versuche
184:                             * immer um 1 hochgezählt.
185:                             */
186:
187:         if (myGuess < toBeGuessed) {
188:             System.out.println("Ihre Zahl ist zu klein!");
189:             numberOfGuesses++;      // Zähler wird um 1 erhöht. Äquivalent zu "zähler = zähler + 1" oder "zähler += 1"
190:         }
191:         else if (myGuess > toBeGuessed){
192:             System.out.println("Ihre Zahl ist zu groß!");
193:             numberOfGuesses++;
194:         }
195:         else{
196:             System.out.println("Sie haben richtig geraten!  benötigten dafür " + numberOfGuesses + " Versuche.");
197:             numberOfGuesses++;
198:             checkGuess = true;           /* "erraten" wird auf "true" gesetzt, sodass sich die Schleife weiter oben
199:                              * nicht mehr wiederholt.
200:                              */
201:         }
202: }
203:
204:
205: //  TODO
206: /**
207:  * Helper infrastructure, used to read human input.
208:  */
209: protected int inputInt()
210: {
211: try {
212: java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
213: while(true) {
214: System.out.print("Tell me your guess: ");
215: String inputString = reader.readLine();
216: if (inputString == null) throw new java.io.EOFException();
217: try {
218: return Integer.parseInt(inputString);
219: } catch (NumberFormatException e) {
220: System.out.println("- Your input  + inputString +  is not a valid number! Try again...");
221: }
222: }
223: } catch (Throwable throwable) {
224: System.err.println();
225: System.err.println("- Sorry, it just doesn't work here with you... I'll shut down now!");
226: System.exit(1);
227: return 0;
228: }
229: }
230: }


(Hinweis: du müsstest den Code ohne Zeilennummern kopieren können, wenn du auf Quelltext ansehen klickst ..)

Bezug
Ansicht: [ geschachtelt ] | ^ Forum "Softwaretechnik und Programmierung"  | ^^ Alle Foren  | ^ Forenbaum  | Materialien


^ Seitenanfang ^
www.matheraum.de
[ Startseite | Forum | Wissen | Kurse | Mitglieder | Team | Impressum ]