I cant figure out where to put a loop - java

I have tried a do loop and a while loop. I just can't seem to figure out where to put a loop so once the program has completely run I want it to Question the user "Yes I want to continue" or "No" and it ends. This is a class assignment and I am using eclipse and it correct somethings which really sent me for a loop myself.
Code
import java.util.Scanner;
public class studentgpa {
public static void main(String[] args) {
Scanner consoleInput = extracted();
printGPA(consoleInput);
}
public static void printGPA(Scanner input) {
System.out.println("Enter a student record: ");
String name = extracted().next();
System.out.print("Enter Number of grades you will be entering: ");
int count = extracted().nextInt();
int sum = 0;
System.out.println("Enter Grades: 95 enter 98 enter and so on ");
for (int i = 1; i <= count; i++) {
sum += extracted().nextInt();
}
double average = (double) sum / count;
System.out.println(name + "'s grade is " + average);
}
private static Scanner extracted() {
return new Scanner(System.in);
}
}

You would need to wrap the content inside of main in a do while loop like this and prompt the user asking if they want to continue
do {
Scanner consoleInput = extracted();
printGPA(consoleInput);
System.out.println("Do you want to add another student? (Yes/No)");
String continue = consoleInput.nextLine(); // storing the user's response
} while (continue.equals("Yes"));

Just begin your function printGPA with a String like this
String continueLoop="Yes";
while("Yes".equals(continueLoop)){
///put the code you already have
continueLoop=extracted().next();
}
The code above will loop until you enter something other than "Yes".

If you need to ask the user then you need to add a loop at the begining of printGPA.
String ans="yes";
while(ans.equalsIgnoreCase("Yes")){//checks the user input is yes or no
//your code
System.out.println("Do you want to continue?");
ans=extracted().next();
}
After changes, the pringtGPA should look like this
public static void printGPA(Scanner input)
{
String ans="yes";
while(ans.equalsIgnoreCase("Yes")){
System.out.println("Enter a student record: ");
String name = extracted().next();
System.out.print("Enter Number of grades you will be entering: ");
int count = extracted().nextInt();
int sum = 0;
System.out.println("Enter Grades: 95 enter 98 enter and so on ");
for (int i = 1; i <= count; i++) {
sum += extracted().nextInt();
}
double average = (double) sum / count;
System.out.println(name + "'s grade is " + average);
System.out.println("Do you want to continue?");
ans=extracted().next();
}//end of while loop
}
Hope it helps.Happy Coding!!

Related

How can I avoid my loop to take the previous answer of the user?

I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.

how to prompt user to break in a for loop?

package task;
import java.util.*;
public class Task {
public static void main(String[] args) {
System.out.println("Enter \"t\" to terminate.");
for(;;){
Scanner input = new Scanner(System.in);
int i;
double I = Double.POSITIVE_INFINITY;
for(i = 0; i <= I; i++){
System.out.println("Integer " + i);
String a = input.next();
if(a.equals("c")){
break;
}
}
}
}
}
I am having trouble in prompting the user to enter "t" to end the for loop. I basically want the for loop to print out every single positive integer, and when I decide to end, I enter "t".
If I could get some help, I'd appreciate it. Thanks!
You could simply use a do while instead of a for+break
Do while :
System.out.println("Enter \"t\" to terminate.");
Scanner input = new Scanner(System.in);
String pressed;
int i = 0;
while (true) {
i=0;
do {
System.out.println("Integer " + i);
pressed = input.next();
i++;
} while (!pressed.equals("t"));
}
Note that you are not testing if the input is an integer.

How to find the average in a do-while loop

I have to write a program that asks the user to enter an integer value. After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even.
I have done this so far with a do-while loop, but I am confused on how to get the averages of the values the user enters. How would you get the average for all the numbers entered?
Here is my code so far:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
From the Question looks like following things need to handled,
haven't add mechanism for addition into single variable.
put all variable to out from do...while loop body...
created additional variable according to requirement.
see all this things covered by me with following code snippet.
do something likewise,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
In order to calculate Average, you need 2 things: Sum of all numbers and Count of all numbers involved in the Average calculation.
Your sum and count which involved in the Average calculation needs to be out of the do..while scope in order for them to be known at the calculation stage.
I also took the liberty of fixing your code a little bit
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int count = 0;
int sum = 0;
String answer = "";
do {
System.out.print("Enter any number : ");
int num = scan.nextInt();
boolean isEven = (num % 2 == 0);
System.out.println(num + " is an " + (isEven ? "even" : "odd") + " number.");
sum += num;
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.toLowerCase().equals("y"));
System.out.println("Average: " + (sum/count));
}
}
Change your code like this:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr is average. that means when you input an integer. we add num and avr . and when finish looping. we divideto count. like this:
1-5-9-11
avr = 1+5+9+11;
count = 4;
avr = avr/4;

Only allowing numbers to be taken from user input in java

I have a little averaging program I have made and, I am trying to only allow it to take in numbers. Everything else works but, I can't seem to figure it out. I am still learning so, any advise or pointers would be awesome!
Here is my code.
import java.util.Scanner;
public class THISISATEST {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int count = 0;
int i = 1;
while (i <= 10) {
i++;
{
System.out.print("Enter the test score: ");
int tS = keyboard.nextInt();
count++;
sum = (sum + tS);
}
System.out.println(sum);
}
System.out.println("The Average is = " + sum / count);
}
}
Inside your while loop use the following code:
System.out.print("Enter the test score: ");
while (!keyboard.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
keyboard.next();
}
int tS = keyboard.nextInt();
//If input is a valid int value then the above while loop would not be executed
//but it will be assigned to your variable 'int ts'
count++;
sum = (sum + tS);

Having Trouble Making a for loop with a do-while loop

just started with Java and my assignment this week is to write a program that asks the user how many test scores they want to enter, which the user fills in and then the program asks them to enter test scores up until that counter is met, and display the average amongst the scores.I feel like i have the brunt of it but just need some more help its kind of in a dead loop and I'm stuck. I've moved my for loop around and it either puts my display text into a neverending loop or the program stalls after asking for number of scores to be entered (this is where it is now). Any help is appreciated:
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int count = 0;
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
while (testScore <= 100)
{
// get the input from the user
System.out.print("Enter the number of scores to be entered: ");
for (scoreCount = 0; count <=100; scoreCount++)
scoreCount = sc.nextInt();
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount = scoreCount + 1;
scoreTotal = scoreTotal + testScore;
}
else if (testScore != 999)
System.out.println("Invalid entry, not counted");
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.println("Enter more test scores? ('y' to continue, 'n' to close): ");
choice = sc.next();
System.out.println();
}
}
}
Try something like this:
// put this above main() - this way you can use it without ever defining a `Scanner` object again
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
// store number of scores to enter
int numScores = 0;
// input number of scores to enter
System.out.print("How many scores would you like to enter? ");
numScores = in.nextInt();
// store sum of scores
int scoreTotal = 0;
// input scores
for(int i = 0; i < numScores; i++)
scoreTotal += in.nextInt();
// print count, sum, and average of scores
System.out.printf("\nScore count: %d", numScores);
System.out.printf("\nScore total: %d", scoreTotal);
System.out.printf(\n Average score: %d", scoreTotal/numScores);
}
I think this should run, but it may have a bug or two. I do not have Java any more, but I will be able to help if it produces an error. Just place this in your class and see how it works. You shouldn't need to modify it at all.
it is not a good idea to have so many nested whiles, it is very inefficient.
it is a good idea to surround the code with try/catch blocks, I didn't put it in there since I'm not sure you have learnt it.
I think you should take user input as total amount of scores, instead of using 100 in the for loop.
anyway, this is what I would do, hope this code helps:
import java.util.Scanner;
public class test{
public static void main(String[] args){
int count = 0;//amount of scores entered by user
int total = 0;//total score added up
int current = 0;//current amount of scores entered
System.out.println("How many scores would you like to enter?");
Scanner sc = new Scanner(System.in);
count = sc.nextInt();
do{
System.out.println("current amount of scores entered is "+current+" please enter the next score");
total += sc.nextInt();
current ++;
}
while(current < count);
System.out.println("the average score of "+current+" entered scores is "+total/count);
}
}

Categories

Resources