14 Replies - 459 Views - Last Post: 03 August 2013 - 04:34 AM Rate Topic: -----

#1 JohnSalx1028  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-August 13

I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 02:53 PM

Hello,

Currently I am working on an assignment where I need to calculate a payroll and have it repeat itself. Now I got most of it done, but I am at a loss as to how exactly I can add a loop. At the moment when I reply with '1' or '2' it just ends the program. So I need some guidance as to what the next step is. Here is my code

 
import java.util.Scanner;
public class RevisedPayroll {
    
/**
* main method begins execution of Java application
*/

public static void main(String[] args) {
Scanner reader = new Scanner (System.in);               
        
        
double PayRate;
double RegHours;
double WeeklyPay;
double RegPay;
double Response = '1';

if (Response == '1') 

{
     
System.out.print("Employee name: ");
String Name = reader.nextLine(); // read text
        
System.out.print("Rate of pay: ");//user input prompt
PayRate = reader.nextDouble();//read numbers

System.out.print("Reg hours worked: ");//user input prompt
RegHours = reader.nextDouble();//read numbers
        
RegPay = PayRate * RegHours;//calculation
        
WeeklyPay = RegPay;//calculation
        
System.out.println( Name );//prints text
        
System.out.printf("$%.2f\n", WeeklyPay);

while( WeeklyPay <= -1) {

	System.out.println( "Payroll cannot be a negative number" );
	break;
}

System.out.println( "Would you like to do another employee? 1 = yes, 2 = no");
Response = reader.nextDouble(); //Read Reply

   
} } //End Main Method

}  //End Class RevisedPayroll




So what I want it to do now, is when the user replies with a 1, I want it to restart. When the user replies with 2, I want it to say have a nice day and end. I am not asking for the answers I just want to know if you guys can give me some tips or methods to help me continue as I am stuck at the moment. Any Feedback helps

Is This A Good Question/Topic? 0
  • +

Replies To: I am stuck, I need some ideas on how to continue this project.

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2204
  • View blog
  • Posts: 5,236
  • Joined: 10-September 10

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 02:59 PM

What you describe is typically done with a do/while or a while loop. Here's an example of how it's done with a while loop. (This example can be significantly improved, and the do/while loop is usually more appropriate.)
boolean anotherEntry = true;

while ( anotherEntry )
{
    // main code
    
    // then the code that decides whether to continue or end
    if ( response == 1 )
    {
        anotherEntry = true;
    }
    else
    {
        anotherEntry = false;
    }
}

Was This Post Helpful? 1
  • +
  • -

#3 JohnSalx1028  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-August 13

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 03:02 PM

Thanks a ton Greg,

When I was searching for an example I kept running into boolean, but none of the places explained how to use it in the code. This is super helpful.
Was This Post Helpful? 0
  • +
  • -

#4 JohnSalx1028  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-August 13

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 03:18 PM

Ok so, I have altered my code using your suggestion Greg, the problem now is that I am not sure if I have implemented it correctly. When I select option 2 it works perfectly when I choose option 1 instead of looping it just ends the program here is the new code. Also any new suggestions are welcome.

import java.util.Scanner;
public class RevisedPayroll {
    
/**
* main method begins execution of Java application
*/

public static void main(String[] args) {
Scanner reader = new Scanner (System.in);               
        
        
double PayRate;
double RegHours;
double WeeklyPay;
double RegPay;
boolean Loop = true;
double Response = 1;

{
     
System.out.print("Employee name: ");
String Name = reader.nextLine(); // read text
        
System.out.print("Rate of pay: ");//user input prompt
PayRate = reader.nextDouble();//read numbers

System.out.print("Reg hours worked: ");//user input prompt
RegHours = reader.nextDouble();//read numbers
        
RegPay = PayRate * RegHours;//calculation
        
WeeklyPay = RegPay;//calculation
        
System.out.println( Name );//prints text
        
System.out.printf("$%.2f\n", WeeklyPay);

while( WeeklyPay <= -1) {

	System.out.println( "Payroll cannot be a negative number" );
	break;
}

System.out.println( "Would you like to do another employee? 1 = yes, 2 = no");
Response = reader.nextDouble(); //Read Reply

if ( Response == 1 )
{
  Loop = true;
  }
   else
   {
     Loop = false;
	 System.out.println( "Have a nice day!" );
	 }
} } //End Main Method

}  //End Class RevisedPayroll


Was This Post Helpful? 0
  • +
  • -

#5 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2204
  • View blog
  • Posts: 5,236
  • Joined: 10-September 10

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 03:21 PM

What's going on with line 19? Is that supposed to be the beginning of the while loop? Did you forget the while()?
Was This Post Helpful? 1
  • +
  • -

#6 JohnSalx1028  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-August 13

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 03:31 PM

Oops, that was the problem and now the code definitely does work. However when I choose 1, instead of asking What is the employee's name it shows What is the Employee's Name: Rate of Pay:? I am not sure how it would only do this the second run and not the first. Any ideas?

Newest Code
import java.util.Scanner;
public class RevisedPayroll {
    
/**
* main method begins execution of Java application
*/

public static void main(String[] args) {
Scanner reader = new Scanner (System.in);               
        
        
double PayRate;
double RegHours;
double WeeklyPay;
double RegPay;
boolean Loop = true;
double Response = 1;

while(Loop = true) 

{

     
System.out.print("Employee name: ");
String Name = reader.nextLine(); // read text
        
System.out.print("Rate of pay: ");//user input prompt
PayRate = reader.nextDouble();//read numbers

System.out.print("Reg hours worked: ");//user input prompt
RegHours = reader.nextDouble();//read numbers
        
RegPay = PayRate * RegHours;//calculation
        
WeeklyPay = RegPay;//calculation
        
System.out.println( Name );//prints text
        
System.out.printf("$%.2f\n", WeeklyPay);

while( WeeklyPay <= -1) {

	System.out.println( "Payroll cannot be a negative number" );
	break;
}

System.out.println( "Would you like to do another employee? 1 = yes, 2 = no");
Response = reader.nextDouble(); //Read Reply

if ( Response == 1 )
{
  Loop = true;
  }
   else
   {
     Loop = false;
	 System.out.println( "Have a nice day!" );
	 }
} } //End Main Method

}  //End Class RevisedPayroll



Was This Post Helpful? 0
  • +
  • -

#7 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2204
  • View blog
  • Posts: 5,236
  • Joined: 10-September 10

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 03:43 PM

I specifically showed you how to write the while() condition, and you changed it.

Remember the '=' is the assignment operator, '==', is the comparison operator, but neither is required when a boolean is contained in a conditional statement that resolves to 'true' or 'false'. while ( Loop ) is good enough.

Also, follow Java naming conventions: class names are capitalized, method and variable names begin with lower-case letters and are camel-cased after that.

Edit: Oh!, and the input buffer needs to be cleared after the last reader statement. Simply add:

reader.nextLine();

between lines 48 and 50.

This post has been edited by GregBrannon: 01 August 2013 - 03:48 PM

Was This Post Helpful? 2
  • +
  • -

#8 JohnSalx1028  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-August 13

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 03:58 PM

Okay Greg,

Thanks a lot I fixed what you said and re-looked over your code and how I changed it and fixed that and now it works perfectly thanks a lot.
Was This Post Helpful? 0
  • +
  • -

#9 NeoTifa  Icon User is offline

  • Whorediot
  • member icon





Reputation: 2736
  • View blog
  • Posts: 15,814
  • Joined: 24-September 08

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 04:00 PM

May be a bit off topic, especially since it's been a while, but this sort of confuses me a bit. Not so much that it's incorrect, but I guess I've never really seen it before.

while( WeeklyPay <= -1) {

	System.out.println( "Payroll cannot be a negative number" );
	break;
}



Wouldn't one normally just use an if statement? I don't see a reason to have a loop if you're only printing one statement then breaking. Also, aren't breaks usually only used in switches? Sorry to nitpick, but I'm just curious for the styles. Thank you.
Was This Post Helpful? 0
  • +
  • -

#10 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2204
  • View blog
  • Posts: 5,236
  • Joined: 10-September 10

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 04:00 PM

Glad to help, hope you learned the key points. If you ever have any questions, let me know.
Was This Post Helpful? 0
  • +
  • -

#11 JohnSalx1028  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-August 13

Re: I am stuck, I need some ideas on how to continue this project.

Posted 01 August 2013 - 09:54 PM

View PostNeoTifa, on 01 August 2013 - 04:00 PM, said:

May be a bit off topic, especially since it's been a while, but this sort of confuses me a bit. Not so much that it's incorrect, but I guess I've never really seen it before.

while( WeeklyPay <= -1) {

	System.out.println( "Payroll cannot be a negative number" );
	break;
}



Wouldn't one normally just use an if statement? I don't see a reason to have a loop if you're only printing one statement then breaking. Also, aren't breaks usually only used in switches? Sorry to nitpick, but I'm just curious for the styles. Thank you.


Hello,

Like I said I am still fairly new and a tutorial I was looking at showed something similar to this so I altered it to fit into mine, I am sure there are way better ways to go with this though. How would you have done it? If you do not mind answering.
Was This Post Helpful? 0
  • +
  • -

#12 MasterZeddicus  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 39
  • Joined: 30-January 12

Re: I am stuck, I need some ideas on how to continue this project.

Posted 02 August 2013 - 12:17 AM

View PostJohnSalx1028, on 01 August 2013 - 09:54 PM, said:

View PostNeoTifa, on 01 August 2013 - 04:00 PM, said:

May be a bit off topic, especially since it's been a while, but this sort of confuses me a bit. Not so much that it's incorrect, but I guess I've never really seen it before.

while( WeeklyPay <= -1) {

	System.out.println( "Payroll cannot be a negative number" );
	break;
}



Wouldn't one normally just use an if statement? I don't see a reason to have a loop if you're only printing one statement then breaking. Also, aren't breaks usually only used in switches? Sorry to nitpick, but I'm just curious for the styles. Thank you.


Hello,

Like I said I am still fairly new and a tutorial I was looking at showed something similar to this so I altered it to fit into mine, I am sure there are way better ways to go with this though. How would you have done it? If you do not mind answering.



You're lucky to have NeoTifa respond to your post! Her Java skillz are quite 1337. (sorry it's late.)

In general a loop should only be used when you need to return the flow of control to the beginning of your loop and run through it again. Each run through a loop is called an iteration of that loop. Now while you're code does work, essentially what you've done is a loop that does not loop, it has only a single iteration regardless of the outcome, but only happens if a situation is met, in your case the condition for your loop, or for that to happen is when the person enters a number smaller than or equal to -1.

There are two ways that I would personally do this, one as in your case would use a loop, but only because I will be doing input validation and going through a second interation (allowing the user another chance to enter their response if it doesn't work. IE they enter a number below 0 and I say sorry not valid, please enter another number.

The second way would be to simply end the program if invalid information is entered, given everything you're writing here I would assume you're in an elementary java class and have yet to get to the point of needing input validation. I will show you both methods.

but first a note on your methodology. The reason neoTifa asked her question, and I've bolded all of my ifs are you should always say what you're doing in plain english. If you have an If in it when you say it, then you need an if statement to test the validity, not a loop! Programming is all about translating from english to the pc and the most efficient way is the way that is least convoluted. What your statement says in plain english is (As long as my weekly pay is owing them more than a dollar, the computer should print out that payroll cannot be a negative number and then break out of the repetition regardless of whether my weekly pay is owing them more than a dollar), this is why you should be very careful of the break; statement! Generally break does just that, it breaks your loop! It stops regardless of whether your condition is met or not, and that's dangerous stuff when it comes to errors.

In plain english what it should sound more like is "If payroll is negative, there is a problem, tell the user there is a problem and quit."

The first one I will demonstrate is the simple one. The if there is a problem let's exit.

Scanner keyboard = new Scanner(System.in); 
System.out.println("Please enter a positive integer")
int enteredInteger = keyboard.nextInt(); 

//so far I assume you're with me as you've demonstrated input abilities already. 
//Now we will test the integer

if (enteredInteger < 0) //Less than zero is better than <= -1 as payroll could be a double and this accounts for that.  {          
     System.out.println("Integer error, we asked for a positive integer silly!");
     System.out.println("Program will now terminate.");
     System.exit(0); 
}



As you can see what we've done is stored the integer, checked it, and then decided that if it's a bad one we're going to inform the user and exit the program. Extremely simple compared to your while loop.

This is however not very convenient if you have to enter a lot of data as you would have to relaunch the application and restart your data input every time you entered a false data! The easiest way to handle this is with a loop, and the best way to handle a loop is with a flag. A flag is a variable you declare, which while is set to a specific value (usually true or false), will be used to loop until a condition is met to change the flag to the needed value to continue the program.

There are a number of types of loops. The most common would be the While/Do-While/and For loops.

The while loop deals specifically with the type of thing I spoke of before, it iterates while a certain condition is met. It's in the form:

while(someCondition)
{
//Do all the fancy stuff I've written here, if everything goes well
//my condition changes and is no longer valid so the loop stops
//otherwise we try again!
}



Now given your specific assignment I don't want to just give you the answer so I'm going to use an example that's a bit more arbitrary but will still give you the point.

boolean thisIsMyFlag = false; 
int firstInt; 
int secondInt; 

while(!thisIsMyFlag)
//the ! symbol corresponds to the logical operator NOT, essentially while NOT thisIsMyFlag 
//or in plain english "While thisIsMyFlag is not true (therefor false), do my loop.

System.out.println("Please enter two integers with the second being greater than the first"); 
System.out.print("First integer");
firstInt = keyboard.nextInt(); 
System.out.println();//Just to get to a second line after user input
System.out.print("Second integer"); 
secondInt = keyboard.nextInt(); 
System.out.println();

if(secondInt > firstInt)
      thisIsMyFlag = true;

//So now it tests, if the second one is bigger your flag changes to true, since 
//our condition to run the loop is that the flag be false as you can see the loop will not
//iterate again. 
else
    System.out.println("Your first value is greater than the second! Please try again.");
}



As you can see since our if statement asks if the second one is greater than the first, thisIsMyFlag will only ever change to true when that condition is met, meaning that the program will only continue once the user enters the data in the form we require. You have therefore successfully validated your input.

The second form is the Do-While loop. The only difference is you will have the following:

do{
//the code you want executed here
}while(yourConditionsHere)


The big difference between the two is that the do-while loop will always iterate at least once, regardless of the condition you set since the condition is only tested after the first iteration of the loop. This is the loop you will likely use more commonly, and can be done much the same way I did above, I'll leave it to you as an exercise to try and translate my above code into a do while loop instead.

[/code]

the for loop is a bit different and has the format


for(someDeclaredVariable//*; YourConditions; change//**)
{code to be executed here}



* This is not a necessary field, it can be left blank if you declare the variable somewhere else however for loops are usually used in increment or decrement situations, and this helps to make their flag variables self contained and not somewhere arbitrary in your code.

**This is room for a snippet of code which happens after every iteration of your for loop. It can also be left blank.

In it's most basic form a for loop can actually be used exactly like my above while loop. Because for and while and pretty much interchangeable in the english language. For can mean as long as, and while also translates to as long as. So using a for loop in this way is frowned upon but I'll show it regardless.

for(boolean myFlag = false; !flag; //nothing to change after each run)
{

System.out.println("Please enter two integers with the second being greater than the first"); 
System.out.print("First integer");
firstInt = keyboard.nextInt(); 
System.out.println();//Just to get to a second line after user input
System.out.print("Second integer"); 
secondInt = keyboard.nextInt(); 
System.out.println();

if(secondInt > firstInt)
      MyFlag = true;
else
    System.out.println("Your first value is greater than the second! Please try again.");

}




the more common usage would be if you wanted to do something a certain number of times, think about if you wanted to print out the numbers 1-50, if you had to do that with a System.out.println call 50 times that's a lot of code! The simple way would be to do the following:

for(int numberToPrint = 1; numberToPrint<=50 ; numberToPrint++){
System.out.println(numberToPrint); 
}



And that's it, three lines of code instead of 50! What have I done? I made a flag variable which is the same as the variable I'm going to print called numberToPrint. Since I want to print the numbers from 1-50 I started it at 1. Then I declared that I want my loop to run as long as my flag is less than or equal to 50, so once it hits 51 it stops and won't continuing printing. Lastly I added a call to increment numberToPrint by one everytime my loop runs. If you don't know what the increment operator is

int myInt1 = 0;
myInt1++; 

//This statement is exactly equivelant to

int myInt1 = 0;
myInt1 = myInt1 + 1;



the ++ operator simply adds 1 to your number, it would be possible to print say every 5th number by modifying numberToPrint++ to numberToPrint = numberToPrint+5, this would print 1,6,11,16 etc until it hits a number higher than 50.

I hope this has helped you understand control structures and how to properly set up code, as well as given you a better idea on when it's appropriate to use loops, or conditional statements. If you need further help feel free to pm me with the links to your topics. I will not respond in pm as it benefits the whole forum if you post and I answer it publicly where as I only help you if I only answer in your inbox.

Take care and good luck!
Zeddikus J. H.
Was This Post Helpful? 3
  • +
  • -

#13 JohnSalx1028  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-August 13

Re: I am stuck, I need some ideas on how to continue this project.

Posted 02 August 2013 - 12:47 AM

Hello MasterZeddicus,

Boy, saying there was a few better ways to do it was an understatement, these other ways you have shown seem a lot simpler and more refined than what I have made. Thanks for the input these will be super helpful and a good thing to look back on if I am stuck in the future.
Was This Post Helpful? 0
  • +
  • -

#14 MasterZeddicus  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 39
  • Joined: 30-January 12

Re: I am stuck, I need some ideas on how to continue this project.

Posted 02 August 2013 - 11:32 AM

You're very welcome, I'm glad it helped you out. :)
Was This Post Helpful? 0
  • +
  • -

#15 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: I am stuck, I need some ideas on how to continue this project.

Posted 03 August 2013 - 04:34 AM

Why making response a double if it is a int ?

Comparaisons are always tricky with floating point variable
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1