I am new to stackoverflow. First I would like the program to loop with a price, then a question(enter another price?), price, then a question and so on. Below is the output.
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Please enter a price:
99
Please enter a price:
22
However it will keep looping at the end with "Please enter a price:". I want it to do:
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Enter another price?
y
Please enter a price:
22
Can anyone help me with this? Also, sometimes the average does not update fully. Thanks :)
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice;
System.out.println("Please enter a price: ");
integer = input.nextInt();
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
}
while (addPrice.equalsIgnoreCase("Y"));
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
You need to replace your while with an if
if (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
In fact, addPrice is not modified within your second while loop, and so you have an infinite loop.
In order to do the averaged price, you're in the right way but not in the right place :P
count = count +1 and sum = sum + integer should be done after each integer = input.nextInt(). In your current code, you don't increment the counter and don't add the integer for the last input.
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
}
}
while (addPrice.equalsIgnoreCase("Y"));
Finally here is a improved version which avoid the use of if.
int sum = 0;
int integer = 0;
String addPrice = "Y";
while( "Y".equalsIgnoreCase(addPrice) ) {
System.out.println("Please enter a price: ");
integer = input.next();
sum += integer ;
count++;
System.out.println("Enter another price? ");
addPrice = input.next();
}
int avg = sum / count ;
What you should do is change your logic a bit. You need to repeat two actions, entering a price and asking if the user wants to enter another price. Only one loop is required for this.
do {
System.out.println("Please enter a price: ");
integer = input.nextInt();
count = count + 1;
sum = sum + integer;
System.out.println("Enter another price? ");
addPrice = input.next();
} while (addPrice.equalsIgnoreCase("Y"));
i think you want something like this:
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice = "Y";
while (addPrice.equalsIgnoreCase("Y")){
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++;
sum += integer;
System.out.println("Enter another price? ");
addPrice = input.next();
}
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
Try this:
EDIT Added min and max.
public class ReadInPrice {
public static void main(String[] args) {
//better to use 2 scanners when dealing with both string and int
//one for string ; one for ints
Scanner strScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
boolean enter = true;
int sum = 0;
int count = 0;
int min=Integer.MAX_VALUE;
int max=0;
while (enter) { //while user wants to keep adding numbers
System.out.println("Please enter a price: ");
int price = intScanner.nextInt();
if(price < min)
min=price;
if(price > max)
max=price;
sum += price;
count++;
System.out.println("Enter another price? ");
String answer = strScanner.nextLine();
if (!answer.equalsIgnoreCase("Y"))
enter = false; //user doesn't want to keep adding numbers - exit while loop
}
double average = (double)sum / count;
System.out.println("Average = " + average);
System.out.println("Min = " + min);
System.out.println("Max = " + max);
strScanner.close();
intScanner.close();
System.exit(0);
}
}
Related
I'm trying to store the sum of 2 numbers inside a while loop so that once the loop ends multiple sums can be added up and given as a total sum, however I am rather new to Java and am not sure how to go about doing this.
I'm trying to use an array but I'm not sure if it is the correct thing to use. Any help would be greatly appreciated.
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
Int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[0]=AddedNum;
TotalNum[1]=;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
System.out.println("The total sum of all the numbers you entered is " + TotalNum);
}
}
There is a data container called ArrayList<>. It is dynamic and you can add as many sums as you need.
Your example could be implemented like this:
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> listOfSums = new ArrayList<>();
int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
listOfSums.add(AddedNum);
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
// Then you have to calculate the total sum at the end
int totalSum = 0;
for (int i = 0; i < listOfSums.size(); i++)
{
totalSum = totalSum + listOfSums.get(0);
}
System.out.println("The total sum of all the numbers you entered is " + totalSum);
}
}
From what I see, you come from a background of C# (Since I see capital letter naming on all variables). Try to follow the java standards with naming and all, it will help you integrate into the community and make your code more comprehensible for Java devs.
There are several ways to implement what you want, I tried to explain the easiest.
To learn more about ArrayList check this small tutorial.
Good luck!
Solution with array:
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
int Num1, Num2, AddedNum;
String answer;
int count = 0;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[count]=AddedNum;
count++;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
int TotalSum = 0;
for(int i = 0; i <count; i++ ) {
TotalSum += TotalNum[i];
}
System.out.println("The total sum of all the numbers you entered is " + TotalSum);
}
}
This solution is not dynamic. There is risk that length of array defined on beginning will not be enough large.
This is the code:
import java.util.Scanner;
public class javapractice {
public static void main(String[] Args) {
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number :");
int number = input.nextInt();
boolean nextint = input.hasNextInt();
if (nextint) {
count++;
XX += number;
} else {
break;
}
input.nextLine();
}
int YY = XX/count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();
}
}
I want the output to print the sum of the numbers entered and when I enter let's say a word like "Hello", it breaks out of the loop and prints Sum 0 0 and AVG = 0.
The issue I'm having is that whenever I enter the number, it asks me for it two times and doesn't take the next number in the row after that and whenever I enter a string variable lets say "I", it outputs Inputmismatch. What would be the fix to this?
Don't mix nextLine() and all the other next methods; pick one. If you want to read a line's worth of text, just call next(), but if you want the input to flow as 'everytime a user hits enter, read another token', which you usually do, update the definition of 'what defines a token?': scanner.useDelimiter("\r?\n");.
Try this code:
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number: ");
if (input.hasNextInt()) {
count++;
XX += input.nextInt();
} else {
break;
}
}
int YY = XX / count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();
my lecturer give me these question:
1. Write a program that does the following:
a. Get the number of students from user (n)
b. Ask user to enter n grades of n students, store them in an array.
c. Print out the max, the min, and the average of those n grades.
Note: write 3 methods to return the max/min/average element of an array
and use them in this program.
I try to do it, but the output of my program doesn't like what I'd expected.
Here is my code:
package javaapplication2;
import java.util.*;
public class JavaApplication2 {
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i;
}
}
return max;
}
public static double min(double[]y) {
double min = max(y);
for (int i =0; i < y.length; i++) {
if (y[i] < min) {
min = y[i];
}
}return min;
}
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
double grades [] = new double [5000];
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
}
And here is my output:
Enter student's name:
k
Enter student's score:30
The max grade is: 0.0
The min grades is: 0.0
Enter student's name:
Yah, I dont know why my max grade and min grade is 0.0. Anyone, please help me, thank you !!!
Your problem comes from the grade array s being reassigned each loop
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
//you set the grades array each loop to a new empty array
double grades [] = new double [5000]; //<--- Move this one out
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
Move it out and then try to get the methods done :)
Edit:
You also have a little error in the max method in regard of the value.
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i; //<-- Not max = i but max = x[i] :)
}
}
return max;
}
In the function where you are calculating max, you should use:
if (max < x[i]) {
max = x[i];
}
As you want to return the element and not it's index. Also you would want to declare your array named grades before the while loop or else it would create a new array on every iteration.
And for improving the code performance:
1. you can in your max/min functions, exit the loop as soon as you encounter a value=0. In your current code the loop iterates 5000 times even if there is a single entry.
2. in your min function instead of doing double min = max(y); you should use double min = Double.MAX_VALUE;. It will prevent the unnecessary calling of the max function.
We are supposed to create a loop that repeats for the number of times needed by the student. I am completely lost when it comes to setting up a loop that doesn't run on a predetermined count in the code.
We have to create the loop. I dont really even know where to start since there is nothing in the book that I can see that address that style of condition yet.
Any help is appreciated to get me going in the right direction.
import java.util.*;
public class TestScoreStatistics
{
public static void main (String args[])
{
int score;
int total = 0;
int count = 0;
int highest;
int lowest;
final int QUIT = 999;
final int MIN = 0;
final int MAX = 100;
Scanner input = new Scanner(System.in);
System.out.print("How many scores would you like to enter >> ");
enterCount = input.nextInt();
System.out.print("Enter a score >> ");
score = input.nextInt();
//Create a while statement that will loop for the amount entered
while( count != QUIT )
{
}
System.out.print("Enter another score >> ");
score = input.nextInt();
}
System.out.println(count + " scores were entered");
System.out.println("Highest was " + highest);
System.out.println("Lowest was " + lowest);
System.out.println("Average was " + (total * 1.0 / count));
}
}
So. It seems that you want to request entering scores until the user entered as many scores as defined in enterCount:
List<Integer> scores = new ArrayList<Integer>();
while( count < enterCount ) {
System.out.print("Enter another score >> ");
score = input.nextInt();
scores.add(score);
count++;
}
You probably have to define some kind of List where you put the scores in.
i apologize i know this looks simple but i'm kinda new to coding. the goal of the program is to take inputs from the user starting at index 0 and then save the inputs into the array. i'm probably close to solving this but i need some help.
here is the code:
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[numberOfGrades] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
Your logic is a bit off. numberOfGrades is the.. well.. number of grades. And when you do this: grades[numberOfGrades] = input.nextInt(); then you put the user's input in the grades array in location numberOfGrades, which you don't want.
What you do want is:
do {
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
This way, the array in location counter is accessed, and the user's input is placed inside it in the correct location.
Also, to calculate the average of the grades, like you are trying to do in the end of your program, you should do:
double sum = 0;
for (int grade : grades)
sum += grade;
And then your average will be:
average = 1.0d * sum / grades.length;
You can just as well put this summing logic inside your do-while loop and avoid the extra loop I introduced.
this instruction
grades[numberOfGrades] = input.nextInt();
must be replaced by
grades[counter] = input.nextInt();
try this ...
The thing that you were doing wrong is in the do while loop you were inserting value in the same array index grades[numberOfGrades] = input.nextInt(); should be replaced by grades[counter] = input.nextInt();
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
You can try like this
public class ArrayTest {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("enter number of elements");
int n=input.nextInt();
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++){//for reading array
arr[i]=input.nextInt();
}
for(int i: arr){ //for printing array
System.out.println(i);
}
}