Tuesday, June 25, 2019

Java 'do while' loop not working



I have this code:



import java.util.*; 

public class Vormpjes {

public static void main(String[] args){

String vorm;
String nogmaals;
double diameter;
double basis;
double hoogte;

Scanner keyboard = new Scanner(System.in);

do {
System.out.println("Kies uit de 'cirkel', 'driehoek' of 'vierhoek':");

vorm = keyboard.nextLine();

if (vorm.equals("cirkel")){
System.out.println("Geef een diameter op (in cm)");
diameter = keyboard.nextDouble();

cirkel C1 = new cirkel();
C1.setDiam(diameter);
System.out.println("De diameter = " + C1.getDiam() + " cm");
System.out.println("De straal = " + C1.getRadius() + " cm");

System.out.println("De oppervlakte van de cirkel = " + C1.berekenOpp() + " cm2");
System.out.println("");
}

if (vorm.equals("driehoek")){
System.out.println("Geef de basis van de driehoek (in cm)");
basis = keyboard.nextDouble();

driehoek D1 = new driehoek();
D1.setBasis(basis);

System.out.println("Geef de hoogte van de driehoek (in cm)");
hoogte = keyboard.nextDouble();
D1.setHoogte(hoogte);
System.out.println("De oppervlakte = " + D1.berekenOppDriehoek() + " cm2");
System.out.println("");
}

System.out.println("Typ 'J' in als u het programma nogmaals wilt uitvoeren, druk anders op een andere wilekeurige toets.");
nogmaals = keyboard.nextLine();
}

while (nogmaals.equalsIgnoreCase("J"));
}
}


And the class 'cirkel' (that's how you spell circle in Dutch haha)



public class cirkel extends Vormpjes{

public double diam;

public double r;

//constructor
public cirkel(){

}

public double getDiam(){
return this.diam;
}


public void setDiam(double diam){
this.diam = diam;
}

public double getRadius(){
r = 0.5 * getDiam();
return this.r;
}


public double berekenOpp(){
return Math.PI * r * r;
}

public double berekenOmtrek(){
return 2 * Math.PI * r;
}

}



When the program asks the user if he wants to run the program again or not, I'm unable to type anything after while condition.



Why is it not working? I don't get errors or anything...


Answer



Each time you call nextDouble() the user will enter a double and press enter. This will put a double and a newline in the buffer. The double is consumed by nextDouble(), but the newline character lingers around until you call nextLine().



In your case this becomes a problem, because when you ask the user for a J (or something else) the "old" newline character is consumed before the user manages to enter anything.



In other words, simply change




diameter = keyboard.nextDouble();


to



diameter = keyboard.nextDouble();
keyboard.nextLine();



to consume the newline character that was entered after the double.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...