Calculating volume weighted price - java

...
else if(choice == 3) {
ArrayList<Integer> shares = new ArrayList<Integer>();
System.out.print("Type in quantity: ");
int quantity = Integer.parseInt(reader.nextLine());
System.out.println("Enter total quantity either as a single number or many numbers by pressing enter after each: ");
while (reader.hasNextInt()) {
int share = reader.nextInt();
shares.add(share);
}
System.out.println("Enter total price: ");
Scanner reader1 = new Scanner(System.in);
double price = Double.parseDouble(reader1.nextLine());
int sum = 0;
System.out.println((price*quantity)/sum);
for(Integer d : shares){
sum += d;
return;
}
Here I am trying to calculate a single value out of 3 value (price*quantity)/sum this is the main formula but sum value is calculated by first entering a series of integers which are then summed and used in the main formula.
The problems:
I can not make the While loop to stop when user enters Null value, I only managed to make it stop when user enters a letter instead of a number
Currently when i run this program I get a result Infinity why ?

Because you are checking reader.hasNextInt(), which returns false for non integer input only.
If you want to take input until end of file, you can do this way:
String input = null;
while(!(input = sc.nextLine()).isEmpty()) {
int share = Integer.parseInt(input);
shares.add(share);
}
You are getting Infinity since you are dividing by sum whose value is zero.
I think you might be trying to do this:
int sum = 0;
for(Integer d : shares){
sum += d;
}
System.out.println((price*quantity)/sum);

Related

Prompt user to enter values until the same value is entered thrice in a row

I have a question regarding loops. Basically the program rotates around prompting user to enter integers until three integers have been entered which are the same ones but the issue is if i enter a different integer at the beginning and then enter three same integer i am not able to make my program accept it as three similar integer in the row..
This is the actual question: Write a Java program that prompts the user to enter integers from the keyboard one at a time. The program stops reading integers once the user enters the same value three times consecutively (meaning three times in a row, one after the other). Once input is completed the program is to display the message “Same entered 3 in a row
output:
Enter an integer: 77
Enter an integer: 56
Enter an integer: 56
Enter an integer: 78
Enter an integer: 56
Enter an integer: 22
Enter an integer: 22
Enter an integer: 22
Same integer value entered thrice
I am not able to get the above output correctly. Can anyone please help me in this..
Here is the same program which i tried:
import java.util.Scanner;
public class Naim5c
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int count = 0;
int a,b,c;
do{
System.out.println("enter an integer");
a = input.nextInt();
System.out.println("enter an integer");
b = input.nextInt();
System.out.println("enter an integer");
c = input.nextInt();
if(a==b)
{
if(b==c)
{
System.out.println("Same integer entered thrice");
}
}
else if (b==c)
{
System.out.println("enter an integer");
a = input.nextInt();
if(c==a)
{
System.out.println("Same integer entered thrice");
}
}
//System.out.println("enter an integer");
//a = input.nextInt();
else if (c==a)
{
System.out.println("enter an integer");
b = input.nextInt();
if( a==b )
{
System.out.println("Same integer entered thrice");
}
}
}while(a!=b && b!=c);
}
}
By the look of it (at least according to you) you require the need to detect when a User enters three integer numbers of the same value three times in a row rather than throughout the entire entry cycle. All you really need is a counter variable and another integer variable to hold the previously entered value. Something like this:
Scanner input = new Scanner(System.in);
int a; // To hold User's current entry value.
int count = 0; // To hold the number of times the same value was entered.
int prevInt = 0; // To hold the value previously entered.
do{
// Since we're in a loop we only need to have
// a single prompt.
System.out.print("Enter an integer: --> ");
a = input.nextInt(); // Get User Input
// Is User entry equal to what what entered
// previously?
if (a == prevInt) {
// Yes it is...
count++; // Increment our counter
// if our counter reaches 3 then let's
// break out of our do/loop.
if (count == 3) { break; }
// Otherwise let's continue the loop from
// the start.
continue;
}
// Nope, not equal to the User's last entry so
// let's make prevInt hold the Users new entry.
prevInt = a;
// Let's reset our counter to 1. We need to set
// to 1 because the last User's input which is
// now held in prevInt is the actual first entry
// for the new integer value.
count = 1;
} while(count < 3); // Keep looping if our counter is less than 3
// Display that a triple entry was made.
System.out.println("Same integer (" + a + ") entered thrice");
You don't need three variables. Just one variable for remembering the last int and a counter variable for recording how many times you've seen the last integer.
int count = 0;
Integer prevInt = null;
do {
System.out.println("enter an integer");
int i = input.nextInt();
if (prevInt == null || i != prevInt) {
count = 1;
} else {
count++;
}
prevInt = i;
} while (count != 3);
System.out.println("Same integer value entered thrice");
You can try this.
Scanner input = new Scanner(System.in);
int num = 0; //holds the current input
boolean check = false; // checking for the input
ArrayList<Integer> number = new ArrayList<Integer>();
do {
System.out.println("Enter an integer");
num = input.nextInt();
number.add(num); // add the current input to the array list
if (number.size() >= 3) { // check if there's 3 or more values in the array
if (number.get(number.size() - 1) == number.get(number.size() - 2) && number.get(number.size() - 2) == number.get(number.size() - 3))
{ // check for input if the same
check = true;
System.out.println("\nSame integer value entered thrice");
}
}
} while(check == false);
// checking for loop to continue of no 3 consecutive input of number is the same
Hello if you want to make a loop you need the for command. And loops uses arrays
int[] I = new int[3]
for(j=0;j<3;j++)
{
System.out.println("enter an integer");
I[j] =input.nextInt();
}
if(I[0]==I[1] || I[1]==I[2]){
System.out.println("Same integer entered thrice");
continue;
}
Assume that code is inside your do while code. Feel free to reply if you have questions
You should simply loop everything back to inputing using "continue".

Collecting two integers in a loop to take a weighted average (without an array)

I'm working on an assignment where I need to ask the user for console input for how many items they have, then ask them for two integers (earned and max possible) which I can then calculate the weighted average. It needs to be done with a loop, not an array for this assignment. I have figured out how to gather the number of items and one of the integers, but I don't know how to gather multiple integers within a for loop. Here's the method I have so far:
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
I am able to tally the sum of earned scores with this method, but not the maximum possible scores so that I can take a weighted average.
Thanks!
You need to read the user input (only) integers in a loop and sum each values(weighted and score). You could return one of the sums with something like the following:
public int returnSum() {
Scanner keyboard = new Scanner(System.in);
boolean isValid = false;
int sum1;
while (*NotAtEndOfInput or Some Condition to Signal End of Input*) {
System.out.print("Please enter score: ");
try {
num = keyboard.nextInt();
sum1+=num;
} catch (InputMismatchException ex) {
//In case user enters anything else than integer, catch
//the exception and let the program move ahead to let the user enter again.
System.out.println("Wrong input. Ony integer input will be processed.");
//discards anything which is not int
keyboard.nextLine();
}finally{
//close input stream to avoid memory leak.
keyboard.close();
}
}
return sum1;
}
You will need to read and sum the other number similarly. Hope this helps.

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Checking for negative values with scanner in

I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p

Array not capturing first user entry

I am attempting to fill an array with floating point numbers using a method. Every time I run my program it does not capture the first number entered.
How can I correct my code so it captures the first user input?
Thanks!
public static void main(String[] args)
{
//Read user input into the array
final int INITIAL_SIZE = 8;
double[] inputs = new double[INITIAL_SIZE];
Scanner in = new Scanner(System.in);
System.out.println("Please enter the number of credits for a course, Q to quit:");
double credits = in.nextDouble();
int currentSize = 0;
while (in.hasNextDouble())
{
if (credits <= 0)
{
System.out.println("All entries must be a positive number.");
}
else
{
// Grow the array if it has been completely filled
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = in.nextDouble();
currentSize++;
}
}
System.out.println(Arrays.toString(inputs));
}
Prolem is You did not store first user entry, so it's not showing to you
Scanner in = new Scanner(System.in);
System.out.println("Please enter the number of credits for a course, Q to quit:");
--> double credits = in.nextDouble();
You have taken the value from user but did not stored it in inputs
If you want to take value of credit from user and want to store credit in inputs then you should do:
double credits = in.nextDouble();
inputs[0] = credits ;
int currentSize = 1;
The problem might be in this line : inputs[currentSize] = in.nextDouble();
You are storing the first value in credits but not assigning it to inputs array.

Categories

Resources