Hi, ich habe grade angefangen Java zu lernen und habe folgendes Problem.
In Zeile 24-34 wird die do-while Schleife 2 Mal ausgeführt bevor ich meine Eingabe über den Scanner eingeben kann.
In der Console sieht das dann so aus:
Do you wish to continue (yes or no)
>>>Please respond with (yes or no)<<<
Do you wish to continue (yes or no)
Eigentlich will ich nicht das die unteren 2 Zeilen angezeigt werden, jedoch läuft die Schleife immer zweimal durch statt wie gewollt einmal, bevor ich meine Eingabe "yes" oder "no" tätige.
Die mittlere Zeile soll nur angezeigt werden, falls man beim Ersten Mal was anderes als "yes oder "no" eingibt
Kann mir vielleicht jemand erklären woran das liegt bzw was für einem Irrtum ich unterliege?
In Zeile 24-34 wird die do-while Schleife 2 Mal ausgeführt bevor ich meine Eingabe über den Scanner eingeben kann.
In der Console sieht das dann so aus:
Do you wish to continue (yes or no)
>>>Please respond with (yes or no)<<<
Do you wish to continue (yes or no)
Eigentlich will ich nicht das die unteren 2 Zeilen angezeigt werden, jedoch läuft die Schleife immer zweimal durch statt wie gewollt einmal, bevor ich meine Eingabe "yes" oder "no" tätige.
Die mittlere Zeile soll nur angezeigt werden, falls man beim Ersten Mal was anderes als "yes oder "no" eingibt
Kann mir vielleicht jemand erklären woran das liegt bzw was für einem Irrtum ich unterliege?
Java:
import java.util.Scanner;
class SquareRoot {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean status = true;
boolean condition = false;
double number;
double root;
String str;
do {
System.out.println("Enter a number:");
number = scan.nextDouble();
if( number < 0) {
System.out.println(">>>number must be positive<<<");
status = true;
}
else {
root = Math.sqrt(number);
System.out.println("Square root of " +number +" is " +root);
do {
if(condition) System.out.println(">>>Please respond with (yes or no)<<<"); //hint: enter yes or no
condition = true; //if a user doesnt enter yes or no at the first time, the hint gets enabled
System.out.println("Do you wish to continue (yes or no)?");
str = scan.nextLine();
if( str.equals("yes") ) status = true;
if( str.equals("no") ) status = false;
}
while( !(str.equals("yes") || str.equals("no")) );
condition = false; //hint gets dissabled for the next time
}
}
while(status);
System.out.println("\nBye");
}
}