Hey I'm trying to teach myself java OO programming using BlueJ and some material from my university, so far it's gone smoothly but I've stumbled on a couple of questions I need help with.
For question 12.1, I have a solution and it work but I'm not sure it's the most efficient or it does entireley what the question is asking as the 'while' condition doesn't seem to affect much going on. Can somebody check this for me?
12.1 a new project:
Start a new project - call it looping. Add a new class to it - Loops. Start adding a single method to it - any sensible name. In this method, write a do-while loop which prints the numbers from 1 to 5. Then modify your code so that, instead of printing each value in turn, it prints the totals of the numbers from 1 up to that value. So it calculates: 1; 1+2; 1+2+3; 1+2+3+4; 1+2+3+4+5. This means that your solution needs a loop inside a loop.
12.2: project from qu 12.1, looping
This question requires keyboard input so you need to make appropriate classes available. One way to do this is to include the InputReader class in your project whose complete code is provided below, though you could use the Scanner class directly, if you prefer. Whichever way you prefer, include code so your Loops class can use a Scanner object.
import java.util.Scanner; /** * InputReader reads typed text input from the standard text terminal. * * @author Lisa Payne * @version Jan 2007 */ public class InputReader { private Scanner reader; /** * Create a new InputReader that reads text from the text terminal. */ public InputReader() { reader = new Scanner(System.in); } /** * Accesses a String typed in text terminal * * @returns String value input */ public String getString() { String input = reader.nextLine(); return input; } /** * Accesses a int typed on a single line in text terminal * * @returns int value input */ public int getInt() { int input = reader.nextInt(); reader.nextLine(); return input; } }
Start a second method in your Loops class - any sensible name. In this method you need to write code similar to that in question 12.1 (indeed you may want to copy 'n paste that to give you a start). This method should total a series of positive integers which the user enters from the keyboard. The user will type in each value followed by an <Enter> keypress. After the last value the user will type a negative value: this is the terminal sentinel. (Of course this method requires only a single loop - not a loop inside a loop.)
/** * Prints totals of numbers between 1 to 5. */ public void calculate() { int count = 1; int total = 0; int j; do { for(j = 1; j <= 5; j++) { total += j; System.out.print(total + " "); count++; } } while(count < 6); }
For 12.2 I have no idea how to incorporate what is being asked with a loop. Can somebody help?!