Jakob Eklund Jakob Eklund - 18 days ago 7
Java Question

Why does this loop not ackowledge the first two inputs?

I'm writing a main method that asks the user for input in the form of the length of the radius and height of a cone, and then calls 3 other mathematical methods to determine the area of the bottom of the cone, as well as the surface area and volume of it.

The idea is that you should be able to enter several sets of inputs, and signal that you're done by entering "q". An example input could for example be " 10 5 6 8 7 5 q". The program should then calculate everything three times, with two sets of radius and height and then break the loop. Instead, it ignores the first two inputs and does the remaining four perfectly. It basically computes n-1 sets of heights and radiuses, where n is the numbers of sets provided. I'd really appreciate some help on this.

while(true) //Infinite loop
{
if (scan.hasNextInt()) //If next input is an integer, read it
{
radie = scan.nextInt();
height = scan.nextInt();
}
else if (scan.next().equals('q'))
{ //If it instead if "q", break the loop

break;
}


do
{
if (scan.hasNextInt())
{
radie = scan.nextInt();
height = scan.nextInt();
}


System.out.print("r = "+radius);
System.out.println("h = "+height);
System.out.println("Bottom area: "+ area(radius));
System.out.println("Surface area: "+area(radie, height));
System.out.println("Volume: "+ volume(radius, height));

}while (scan.next() != "\n");
}

Answer

Problem with your code is that you are never using the first two int scanned in the while loop. Do this instead:

int radius;
int height;

//provided user would be entering radius and height in pairs
while (scan.hasNextInt()) {
    radius = scan.nextInt();
    height = scan.nextInt();
    //Call your methods
}

Alternatively, since you don't know the number of parameters user would be entering, it'd be better if you create an ArrayList for radius as well as height and add inputs to the list and then process them from the list. This would help you preserve input even after exiting while loop:

    ArrayList<Integer> radiusList = new ArrayList<>();
    ArrayList<Integer> heightList = new ArrayList<>();


    while (scan.hasNextInt()) {
        radiusList.add(scan.nextInt();
        heightList.add(scan.nextInt());
    }

    int radius;
    int height;
    for (int i = 0; i < radiusList.size(); i++) {
        radius = radiusList.get(i);
        height = heightList.get(i);
        //Call your methods.
    }