The program I'm trying to write needs to input a user-defined number of Int values and produce the product of those values, and then determine all of the factors of that product. The values will be input through a Do-While Loop until the user enters a negative number, and then all the positive numbers will be multiplied together to form a product in the form of a Double. I'm fairly certain I can figure out how to get the factors of the product, but when it comes to finding the actual product I'm completely at a loss. Here is the code I've written so far, minus my failed attempts at producing a product.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int Value;
double Product;
do
{
System.out.print("Value: ");
Value = in.nextInt();
}
while (Value>=0);
}
This is all I've been able to figure out, looping the Value prompt until a negative Int is entered. As far as getting the product I've tried If-Statements both inside and outside the loop, but either my code is wrong or my statements are wrong, or more likely I'm just trying the wrong method. I'm not asking anybody to write the code for me, but if somebody could point me in the right direction I would very much appreciate it.
What tips would you suggest to determine the product from an unknown number of user-difined values?
You should set product variable to be initially equal to 1 and multiply the value of product by the input number each time the user writes a number.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int value;
double product=1;
do
{
System.out.print("Value: ");
value = in.nextInt();
product *= value //product= product * value;
}
while (value>=0);
System.out.println("Product is: "+product);
}
Related
Hi so I've started learning java online for two weeks now, but as I watched those tutorials, I felt the only way I'd actually grasp that information was to practice it. My other programs worked great, but just when I decided to do something spectacular (for me only of course; a java expert would find creating this program mind-numbing), something went terribly wrong. I'd really appreciate if you could take a look at my code below of an averaging program that could average any amount of numbers you want, and tell me what in the world I did wrong.
UPDATE: Eclipse just outputs a random number after typing in just one number and then shuts down the program.
Here is a snapshot where I type in the console to average 6 numbers and then start with the number 7, but for some reason, when I hit enter again, it outputs 8.
package justpracticing;
import java.util.*;
public class average{
int grade = 0;
int average;
Scanner notoaverage = new Scanner(System.in);
System.out.println("Please enter the amount of numbers you'd like the average of! ");
final int totalaverage = notoaverage.nextInt();
Scanner averagingno = new Scanner(System.in);
System.out.println("Start typing in the " + totalaverage + " numbers");
int numbers = averagingno.nextInt();
int counter = 0;
public void averagingnumbers(){
while(counter<=totalaverage){
grade+=numbers;
++counter;
}
}
public void printStatement(){
average = grade/totalaverage;
System.out.println(average);
}
}
It seems that you have created an average Object in another class, and are calling the methods given from a main class.
I don't know what exactly you're having trouble with, but one problem is here:
average = grade/totalaverage;
These 2 variables that you are dividing are both integers. That means that the result will also be an integer. This is called truncation. What you want to do is first convert at least one of the integers to a double:
... = (grade * 1.0) / totalaverage;
You also want your average variable to be a double instead of an integer so that it can be a lot more accurate.
Sorry for such a basic level question guys. But I'm starter in programming. Not a computers guy. So kindly help me.
In this code when I give input 1000000000, 1000000000, 999999999 the answer should be 4. But my answer is 1. I expect the if statement to execute but it is not executing here.
if you take m*n as a room and "a" as the side as a square tile. Then I want to count MINIMUM no. of tiles required to fill the floor of room. tiles may cover a bit more area but should not leave the room empty. this is my objective. It's working with inputs like 6,6,4 or 15,20,13 etc.
Now its working guys. I had posted the correct code with those minor changes below.
import java.util.Scanner;
public class TheatreSquare {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
float m=input.nextFloat();
float n=input.nextFloat();
float a=input.nextFloat();
long i=(int)(m/a);
long j=(int)(n/a);
if((a*a*i*j)<m*n){
if(a*i<m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j<n){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
}
System.out.println((double)(i*j));
}
}
Your floats are overflowing when you multiply them. Defining m, n and a as doubles will solve the issue:
double m = input.nextDouble();
double n = input.nextDouble();
double a = input.nextDouble();
The int conversion loses precision.
Here in this case, a*a*i*j is equal to m*n Hence the if loop will not execute. Also a*i is equal to m and a*j is equal to n.
Hence i isi and j is 1, so i*j is 1.
You need to allow it to go if it is equal too.
Replace
if((a*a*i*j)<m*n){
if(a*i<m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j<n){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
}
with
if((a*a*i*j) <= m*n){
System.out.println("Entered if block");
if(a*i <= m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j <= n ){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
System.out.println("i is:"+ i +"j is:"+j);
}
thankyou #Mureinik, #Uma Lakshmi Kanth, #Diego Martinoia for helping to solve this. All your answers contributed to solve my question. this is working now. as #Mureinik said my floats are overflowing( though I dont know the meaning). I used Double instead of float and that's it. its working. :-)
import java.util.Scanner;
public class TheatreSquare {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
double m=input.nextDouble();
double n=input.nextDouble();
double a=input.nextDouble();
long i=(long)(m/a);
long j=(long)(n/a);
if((a*a*i*j) <m*n){
if(a*i < m){
//to check weather it is entering if()
i+=1;
}
if(a*j < n ){
//to check weather it is entering if()
j+=1;
}
}
System.out.println((long)(i*j));
}
}
The reason for your behavior is that you are reading numbers as floats. Floats have limited precision, so your m n and a are the same value (at runtime). Reading them as long (and getting rid of all the decimal stuff) should help. But, as mentioned in the comment, we don't know what you wanted to achieve!
--- EDIT DUE TO NEW INFO ---
You have to cover an area of m times n square meters. You have an unit of computation of 1 tile, i.e. a times a square meters (both assumed to be decimal).
Assuming you can cut your tile with good-enough precision, your result will be:
Math.ceiling((m*n) / (a*a));
i.e., either your area is an exact multiple of your tiles (and you can always cut them in rectangles to match the shape of the room), or you'll have some "spare" space to fill in, thus you will need 1 more tile, a part of which you'll use to cover the remaining space, and a part of which you'll throw away.
The Student Union is organising a student trip and they are determining how many cars are required.
Prompt the user to enter the total number of students going on the trip.
Then determine how many cars are required (5 to a car) and how many students are left without transport.
import java.util.Scanner;
class P2Trip
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
int students;
int space = 5;
int sum;
System.out.println("How many students are going today?: ");
students = input.nextInt();
sum =(students / space);
System.out.println("Ammount of cars needed: " + sum);
}
}//code works fine, but im not sure how to get a remainder of students without a lift.
From your comment, it looks like you just need help with who will be left without a car. You need to use modular division (some people call it remainder) with the percent sign (%). Here is the line of code you are missing:
System.out.println("Amount of people without a car: "+students%sum);
The full code for the program is:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) [
Scanner s=new Scanner(System.in);
int carCapacity=5;
System.out.println("How many students?");
int students=s.nextInt();
int cars=students/carCapacity;
int leftOver=students%carCapacity;
System.out.println("Cars needed: "+cars);
System.out.println("Students left over: "+leftOver);
}
}
Have a look at the remainder/modulo operator here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
In my view, there are two corrections you can do in your program:
sum = (student/space);
int leftstudent;`
leftstudent=(students%space);
System.out.println("left students without transport are " +leftstudent);
You might want to check the modular division operator in Java.
Division / Divisor = coefficient
Division % Divisor = remainder
To find the remainder of number students for example you will have to use "%".
This question already has answers here:
min change greedy algorithm in java
(2 answers)
Closed 8 years ago.
I have a cashregister program that inputs purchases and payment and outputs the change due. i need it to not give just an amount but what particular coins/dollars user should get back. heres two methods i have
public void recordPurchase()
{
System.out.print("Enter total purchase price or negative number to end: ");
double input = keyboard.nextDouble();
while(input > 0)
{
purchase = purchase + input;
System.out.print("Enter total purchase price or negative number to end: ");
input = keyboard.nextDouble();
}
}
public double giveChange(Money moneyTypes)
{
double change = payment - purchase;
purchase = 0;
payment = 0;
//computes change rounding to two decimal places
change = (double)(Math.round(change*100))/100;
return change;
}
I need to output what coins/dollars person should get back. i have the money types saved in an array called moneyTypes. for example if the change due is $1.06 it would output you receive a dollar nickel and penny.
any advice would help. Thanks! if you need to see more of the code let me know
I'll give you an advice how to do it, not a solution.
Make a list of possible coin/note values.
Then from the biggest to lowest, compute how many times it fits into the remainder, and subtract this amount of money from the value. Make a note of the number of coins/notes.
This way, you will get the numbers you need.
count = Math.floor(remainder/coinValue) might help you.
Looks like this is the week for this type of question. And after reading through all of the new ones and several old ones, I'm no less confused!
I have a text file with 5 employees, each having 10 salary values listed beneath their name. I am to read in this file, find and display the employee Name, minimum salary, maximum salary and the average salary for each person. I must have 3 loops: One to control reading the file, one to lad the data into the array, and one to do the calculations. I have to print the information for each person on one line, and i must allow decimals rounded to 2 decimal places apparently using Math.round which I've never heard of!
I am embarrassed to show you the mess of code I have because it's not much, but I don't know after reading all that I have if I've even started correctly. I do not know if I have even the right idea of how to proceed. Your help is appreciated.
UPDATED CODE: AGAIN!
import javax.swing.*;
import java.io.*;
public class MinMaxSalary3
{
public static void main(String args[])throws Exception
{
// Declare input file to be opened.
FileReader fr = new FileReader ("salary.dat");
BufferedReader br = new BufferedReader (fr);
//General Declarations
final String TITLE = "Employee's Salary Report";
String employeeName, salaryString;
double avgSalary=0.0;
double totalSalary = 0.0;
double sum = 0.0;
// Declare Named Constant for Array.
final int MAX_SAL = 10;
// Declare array here.
int salary[] = new int[MAX_SAL];
System.out.println (TITLE);
while ((employeeName = br.readLine()) != null)
{
System.out.print ("" + employeeName);
// Use this integer variable as your loop index.
int loopIndex;
// Assign the first element in the array to be the minimum and the maximum.
double minSalary = salary[1];
double maxSalary = salary[1];
// Start out your total with the value of the first element in the array.
sum = salary[1];
// Write a loop here to access array values starting with number[1]
for (loopIndex = 1; loopIndex < MAX_SAL ;loopIndex++)
// Within the loop test for minimum and maximum salaries.
{
if (salary[loopIndex] < minSalary)
{
minSalary = salary[loopIndex];
if (salary[loopIndex] > maxSalary)
maxSalary = salary[loopIndex];
}
{
// Also accumulate a total of all salaries.
sum += sum;
// Calculate the average of the 10 salaries.
avgSalary = sum/MAX_SAL;
}
// I know I need to close the files, and end the while loop and any other loops. I just can't think that far right now.
}
{
// Print the maximum salary, minimum salary, and average salary.
System.out.println ("Max Salary" + maxSalary);
System.out.println ("Min Salary" + minSalary);
System.out.println ("Avg Salary" + avgSalary);
}
System.exit(0);
}
}
}
I must have 3 loops: One to control reading the file, one to lad the
data into the array, and one to do the calculations.
What I've written below might just be more gobbledygook to you now, but if you ever get past this class it might be useful to know.
Another way to look at this would be more object-oriented and better decomposition to boot: You need an object to hold the data, to perform the calculations, and render output. How you get that data is immaterial. It's files today; next time it might be HTTP requests.
Start with an Employee object. I deliberately left out a lot of detail that you'll have to fill in and figure out:
package model;
public class Employee {
private String name;
private double [] salaries;
public Employee(String name, int numSalaries) {
this.name = name;
this.salaries = new double[numSalaries];
}
public double getMinSalary() {
double minSalary = Double.MAX_VALUE;
// you fill this in.
return minSalary;
};
public double getMaxSalary() {
double maxSalary = Double.MIN_VALUE;
// you fill this in.
return maxSalary;
}
public double getAveSalary() {
public aveSalary = 0.0;
if (this.salaries.length > 0) {
// you fill this in.
}
return aveSalary;
}
}
The beauty of this approach is that you can test it separately, without worrying about all the nonsense about file I/O. Get this object right, put it aside, and then tackle the next piece. Eventually you'll have a clean solution when you assemble all these smaller pieces together.
Test it without file I/O using JUnit:
package model;
public class EmployeeTest {
#Test
public void testGetters() {
double [] salaries = { 10000.0, 20000.0, 30000.0, 40000.0 };
Employee testEmployee = new Employee("John Q. Test", salaries);
Assert.assertEquals("John Q. Test", testEmployee.getName());
Assert.assertEquals(10000.0, testEmployee.getMinSalary(), 1.0e-3);
Assert.assertEquals(40000.0, testEmployee.getMaxSalary(), 1.0e-3);
Assert.assertEquals(25000.0, testEmployee.getMinSalary(), 1.0e-3);
}
}
The approach you would want to espouse in this situation is an object-oriented approach. Bear in mind that objects are a representation of related data. Consider that an Employee may have information about their salary, name, and what department they work in (as an example).
But that's just one Employee. You may have hundreds.
Consider creating a model of an Employee. Define what is most pertinent to one of them. For example, they all have to have a name, and have to have a salary.
One would then elect to handle the logic of finding information about the collection of Employees - including min, max, and average salaries - outside of the scope of the generic Employee object.
The idea is this:
An Employee knows everything about itself.
The onus is on the developer to tie multiple Employees together.
It's possible that I don't know enough about what your problem is specifically looking for - I'm not even sure that you can use objects, which would really suck - but this is definitely a start.
As for your compilation errors:
salary is a double[]. An array holds many different values of type double inside of it, but a double[] isn't directly a double. Assigning a non-array type to an array type doesn't work, from both a technical stance, and a semantic stance - you're taking something that can hold many values and trying to assign it to a container that can hold one value.
From your code sample, you want to use a loop (with a loop variable i) to iterate over all elements in salary, and assign them some value. Using just salary[0] only modifies the first element.