Need Help Creating a Loop.
my program compiles with no errors though I need help actually getting the program to loop. I want it to loop if yes is entered , and stop if no is entered. How would I go about doing this? can someone please provide the proper code needed? I am very new to Java and I am trying my best to learn. this program is a project from a book I am reading.
here is my code:
Code :
/* Protoype program to be used to prove first concepts Algorithm project */
import java.io.*;
import java.lang.*;
import java.text.*;
import java.util.*;
//Set up public class
public class document2
{
//declare main() method
public static void main(String[] args) throws IOException
{
//Declare data types
float length,width,area,circum,loop,yes,no;
//set up input stream
Scanner readin = new Scanner(System.in);
//prompt for length
System.out.println("\n\n enter value for length");
//stream in length and convert to float
length = readin.nextFloat();
//prompt for width
System.out.println("\n\n enter value for width");
//stream in width and convert to float
width = readin.nextFloat();
//Calculate results
area = length*width;
circum = 2* (length + width);
//prepare data for out put display
DecimalFormat twodig = new DecimalFormat("########.##");
System.out.print("\n\nThe results of the calcuations are\n\n\n");
System.out.print("the area is:\t\t" + twodig.format(area) + "\n\n");
System.out.println("the circumference is:\t\t" + twodig.format(circum));
//prompt for loop
System.out.println("\n\n calculate again YES / NO ?");
//stream in width and convert to float
loop = readin.nextFloat();
}//end main
}//end class
Re: Need Help Creating a Loop.
I guess you didn't like the help you already received on another forum?
This thread has been cross posted here:
http://www.java-forums.org/new-java/43951-need-help-creating-loop.html
Although cross posting is allowed,
for everyone's benefit, please read:
Java Programming Forums Cross Posting Rules
The Problems With Cross Posting
Re: Need Help Creating a Loop.
This looks over-engineered, or I don't understand what you are doing.
Simply put, this will continue the loop if the user enters yes, and discontinue it if the user enters no.
Code :
import java.util.Scanner;
public class yesOrNo{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
boolean yes = true;
final String YES = "yes";
final String NO = "no";
String userInput;
while(yes == true){
System.out.print("yes or no: ");
userInput = input.nextLine();
if (userInput == YES){
yes = false;
}
else if(userInput == NO){
yes = true;
}
else{
yes = true;
}
}
}
}
Re: Need Help Creating a Loop.
bglueck, don't spoonfeed. Also don't compare Strings with the equals operator (==), use equals() or equalsIgnoreCase() instead.
Re: Need Help Creating a Loop.
Quote:
Originally Posted by
OutputStream
Also don't compare Strings with the equals operator (==), use equals() or equalsIgnoreCase() instead.
Your right. Thanks for catching my mistake.