I'm in the beginning of Java 7 Software design learning switch() and do...while () and what not.
When I compile and run the program in Intelli J IDEA 13, it compiles and runs fine but nothing will break when the statements are complete.
For example, when the program is run, on case 2, when I enter -1 after I input 3 grades (90, 90, 90, -1) it gives me the average (270) but then it repeats...
It should break and go back to the beginning of the switch menu. Even when I enter 3 at the menu, it just displays "No Code Here... " to infinity, even with a break statement (even though break statements are outdated).
import java.util.Scanner;
public class TestingPlatform {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter 1 to set percentage of total for new grades, 2 to enter new grades, 3 to get average, and 4 to quit: ");
int choice = input.nextInt();
do {
switch (choice) {
case 1:
System.out.println("Enter percent to multiply by: ");
double percent = input.nextDouble();
System.out.println("You entered " + percent);
break;
case 2:
int total;
int gradeCounter;
int grade;
double average;
total = 0;
gradeCounter = 0;
System.out.println("Enter grade or -1 to quit: ");
grade = input.nextInt();
while (grade != -1) {
total = total + grade;
gradeCounter = gradeCounter + 1;
System.out.println("Enter grade or -1 to quit: ");
grade = input.nextInt();
}
if (gradeCounter != 0) {
average = (double) total / gradeCounter;
System.out.printf("\nTotal of the %d grades is %d\n", gradeCounter, total);
System.out.printf("Class average is %.2f\n", average);
} else
System.out.println("No grades were entered.");
break;
case 3:
System.out.println("No code here yet....");
break;
}
} while (choice != 4);
}
}
You are taking input once, then looping while input is not 4. Since the input never changes, that's forever.
The break inside the switch just jumps out of the switch. Then you continue your loop.
Put these lines:
System.out.println("Enter 1 to set percentage of total for new grades, 2 to enter new grades, 3 to get average, and 4 to quit: ");
choice = input.nextInt();
Inside the do loop, not outside it. Then you will ask for new input every time you loop.
You'll have to declare choice outside the loop though, since you reference it in the while at the bottom.
Put this line above the do loop:
int choice;
So the reason it will always loop again and hit the switch again is because you are never changing the value of choice again. The break statement is only breaking out of the switch statement, not the loop itself. After you finish the switch you need to ask the user again if they want to pick another option or if they want to enter four to quit.
break statements will only break out of the inner most...group? Statement? I'm not sure what the correct word would be, but it only will break out one level, not all the way.
Just for the sake of saying it, always remember that you have four parts of a loop: Initialization, Condition, Body, and Changer.
Initialization: where the variables IN THE CONDITION are assigned their initial values; this could happen inside the loop in the case of a do...while(); and there could be multiple locations
Condition: the part that decides if your loop will continue or not
Body: the code that is being looped over and over
Changer: (this is the one most often missed, I've noticed) a spot, or spots, where variables IN YOUR CONDITION are having their values changed; there could be multiple locations and multiple variables being affected
Related
I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}
I am trying my hand a few basic do-while codes, and am running into a couple of problems.
I want the code to ask the user to input 1 of 3 options (choosing which group they would like to add a number to, or to exit and total), give an error if they input an irrelevant option, and then total all ints at the end for each group.
public static void main(String[] args) {
String answer = "default";
int grp1 = 0;
int grp2 = 0;
int input1 = 0;
int input2 = 0;
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (answer.equals("A") || answer.equals("B"));
grp1 += input1;
grp2 += input2;
keyboard.close();
System.out.println("Group 1's total is: + grp1);
System.out.println("Group 2's total is: + grp2);
}
I need the to add a qualifier for if the user does not input a valid option, I tried using else:
else {
System.out.println("Invalid option - Try again.")
}
but this just skips to printing the totals, and does not ask the user for another input. How would I best achieve this?
Also,
grp1 += input1;
grp2 += input2;
Only counts the lasted entered int, is there a way to have it add all the entered ints?
Any help would be greatly appreciated, even outside of the questions I asked.
I think you have two confusions.
1) The "while" line in your code applies to the "do" block above it. That means that based on where the grp1 += and grp2 += lines are, they will only ever be run once. I suggest moving those calls to the end of the loop. You could move each line inside the relevant if block so that the code is run every time the user successfully enters a number after A or B.
2) The while condition is asking if the user entered "A" or "B". It's saying if they did, continue looping by going back to "do". If they entered literally anything else (any invalid answer), it will stop and run the code after the "while" line. I think what you really want is while (!answer.equals("X")), which will continue the loop until the user correctly enters an "X" character.
You'll also want to move those grp += lines up a bit.
Just change the condition inside while And also shift the totalling logic
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
grp1 += input1;
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
grp2 += input2;
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (!answer.equals("X"));
keyboard.close();
This will make your do while loop running i.e showing options to user until they wishes to exit. And also group total would be updated properly. I have updated answer based on answer by #Devin Howard
I am trying to simulate a dice game experiment. The goal is to find the average amount of rolls it will take to get the same value of a die to show in the wanted amount of consecutive rolls.
My program asks the user how many times the user wants to run the program. So it will run the loop, then stop after they get their answer, then show the amount of throws it took. Then it will repeat as many times as the user specified.
I want to take the totalThrows from each experiment and add each totalThrows together then divide by my variable turns to get the average amount of throws it would take.
I am having some trouble getting the sum of all the totalThrows. And I can only get the last totalThrow. I would appreciate it if any of you could give some suggestions on how to resolve this. I think an array could help but I haven't learned arrays in class yet.
Here is my code.
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
int value, turns=0, nSides, rollLength; //declare variables
int totalThrows=0, roll=0, count=0,finish=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
System.out.println("\n");
do
{
//Countinue loop until count = rollLength
while(count!=rollLength){
roll = randomNumber.nextInt(nSides)+1;
totalThrows++; //will increment after every roll
//When roll comes up as a watched value I want to increment count by one
if(roll==value){
count++; //This should stop until count is my rollLength
}
else if (roll!=value){ //When an unwanted roll comes up start over
count=0;
}
}
//finish counts how many times the experiment was successful
if (count==rollLength){
finish++;
}
System.out.println("\n");
//Display totalThrows it took until rollLength variable occurs
System.out.println("Your total rolls is: "+ totalThrows);
} while(finish!=turns); //This will repeat the experiment
}
}
Simply declare another variable up top:
int averageThrows = 0;
Add to this value each time the loop ends:
do {
// ...
averageThrows += totalThrows;
} while( finish != turns );
And then divide it by the number of turns:
averageThrows /= turns;
That ought to do it for you.
I am trying to understand what sentinel is or how it works with the program. Anyways this is the block of code I am trying to understand. I know it is a sentinel control loop, but I don't know what it does.
private static final int SENTINEL = -999
From what I have Googled is that by having a negative integer it indicates the end of a sequence. But how does it do that? Oh, and how do I initialize the sentinel? Is it already initialized?
public static int gameScore(int[] teamBoxScore) { //This is telling me the name of an array
int output = 0;
for (int v : teamBoxScore){ //I know that this the values of the array will be stored in the variable "v".
if (v !=SENTIENL) {//
output += v;
}
}
return output;
}
Please and Thank you! I am learning how to code with Java
There is nothing special about a "sentinel." It is simply any constant of your choosing that is not a legitimate value in a data set, so you can use it to mark the end of a sequence. For example, if a team's box score will never be less than zero, -999 (or any other negative value) can be used as a break/end marker.
Usually, there are better, cleaner ways to do this.
to understant sentinel-controlled repetition let's see a simple example,
import java.util.Scanner; // program uses class Scanner
public class ClassAverage
{
public static void main(String[] args)
{
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);
// initialization phase
int total = 0; // initialize sum of grades
int gradeCounter = 0; // initialize # of grades entered so far
// processing phase
// prompt for input and read grade from user
System.out.print("Enter grade or -1 to quit: ");
int grade = input.nextInt();
// loop until sentinel value read from user
while (grade != -1)
{
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
// prompt for input and read next grade from user
System.out.print("Enter grade or -1 to quit: ");
grade = input.nextInt();
}
// termination phase
// if user entered at least one grade...
if (gradeCounter != 0)
{
// use number with decimal point to calculate average of grades
double average = (double) total / gradeCounter;
// display total and average (with two digits of precision)
System.out.printf("%nTotal of the %d grades entered is %d%n",
gradeCounter, total);
System.out.printf("Class average is %.2f%n", average);
}
else // no grades were entered, so output appropriate message
System.out.println("No grades were entered");
}
} // end class ClassAverage
now let's run it
Enter grade or -1 to quit: 97
Enter grade or -1 to quit: 88
Enter grade or -1 to quit: 72
Enter grade or -1 to quit: -1
Total of the 3 grades entered is 257
Class average is 85.67
In a sentinel-controlled loop, prompts should remind the user of the sentinel. its a good Practice to do
reference: Java™ How To Program (Early Objects), Tenth Edition
Sentinel value is used to avoid extra checks inside loops.
For instance, when searching for a particular value in an unsorted list, every element will be compared against this value, with the loop terminating when equality is found; however to deal with the case that the value should be absent, one must also test after each step for having completed the search unsuccessfully. By appending the value searched for to the end of the list, an unsuccessful search is no longer possible, and no explicit termination test is required in the inner loop; afterwards one must still decide whether a true match was found, but this test needs to be performed only once rather than at each iteration.
Refer https://en.wikipedia.org/wiki/Sentinel_value
/---------------------------------------
-----------------Quizzes.java------------
----------------------------------------/
import java.util.Scanner;
import java.text.NumberFormat;
public class Quizzes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
NumberFormat per = NumberFormat.getPercentInstance();
//User to input keys for quiz
System.out.println("How many questions are in the quiz?");
int numques = scan.nextInt();
int[] keys = new int[numques];
for (int i=0; i<keys.length; i++)
{
System.out.print("Please enter the key for # " + (i+1)+ ": " );
keys[i] = scan.nextInt();
}
//User to input answer
System.out.println("\nGrading Quizzes");
System.out.println("--------------------");
int correct=0;
for (int i=0; i<keys.length; i++)
{
System.out.println("Please enter the answer for # " + (i+1)+ ": ");
int answer= scan.nextInt();
if (answer== keys [i])
{
System.out.print("Number "+(i+1)+" is correct.\n");
correct++;
}
else
{
System.out.print("Number "+(i+1)+" is incorrect.\n");
}
}
double cal=(double) correct/numques;
System.out.println("Total number of correct is "+correct);
System.out.println("The percent correct is " +per.format(cal));
System.out.println("Would you like to grade another quiz? (y/n)");
String user_input=scan.next();
while(user_input.equals("y"))
{ correct=0;
for (int i=0; i<keys.length; i++)
{
System.out.println("Please enter the answer for # " + (i+1)+ ": ");
int answer= scan.nextInt();
if (answer== keys [i])
{
System.out.print("Number "+(i+1)+" is correct.\n");
correct++;
}
else {
System.out.print("Number "+(i+1)+" is incorrect.\n"); }
}
cal=(double) correct/numques;
System.out.println("Total number of correct is "+correct);
System.out.println("The percent correct is " +per.format(cal));
}
System.out.println("Goodbye!");
}
}
How would I make the program go back to where the user would have to enter the answer using the while loop? No matter what I tried, right when it prints out, "Would you like to grade another quiz, and if the user type y, it would just end. Can anyone point out what I'm doing wrong
Edit 1: Well I got it to re-run again after the while loop but it keep asking me to input the answer for the question over and over and over again, it doesn't break out of the loop,it doesn't go back to the part where it asked if I wanted to grade another. This is the output
How many questions are in the quiz?
2
Please enter the key for # 1: 1
Please enter the key for # 2: 2
Grading Quizzes
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
3
Number 2 is incorrect.
Total number of correct is 1
The percent correct is 50%
Would you like to grade another quiz? (y/n)
y
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
2
Number 2 is correct.
Total number of correct is 2
The percent correct is 100%
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
2
Number 2 is correct.
Total number of correct is 2
The percent correct is 100%
Please enter the answer for # 1:
while(user_input.equals('y'))
should be
while(user_input.equals("y")) // see the double quotes here
Problem with your code is that character 'y' is autoboxed to instance of Character class which is the subclass of Object.
Class Object is the root of the class
hierarchy. Every class has Object as a
superclass. All objects, including
arrays, implement the methods of this
class
So is the candidate for public boolean equals(Object).
String implementation of boolean equals(Object) checks whether the instance is of type String. if it fails, it will simply return false.
If you want to compare with 'y', then try this.
while(user_input.equals(((Character)'y').toString()))
I will put the question a while loop and it will be something like
while (true) {
// ask the users the questions
// ask if he wants to continue... if no then break; else continue
}
Ok add a while(true) at the beginning of your program and add the appropriate brackets to encompass the whole method's contents. Then, delete the current while loop you have. Say after you get your input for user_input:
if (user_input.equals("y")) {
}
else {
break;
}
You will replace this while with your while(user_input.equals("y")) loop and the problem you pointed will go away but i think still your code will not work as you expected. I think your will need these more correction on your code
while loop should be this one while(user_input.equalsIgnoreCase("y"))
Put the opening and closing braces for while loop and in end while after finishing your for loop put these two statement to check again and again.
follow the following snap of code
while(user_input.equalsIgnoreCase("y"))
{
for (int i=0; i<keys.length; i++)
{
....
}
System.out.println("Would you like to grade another quiz? (y/n)");
user_input=scan.next();
}