Can anyone tell me how I can write java code for the average of the variables in case the input has a different number of variables each time?I assume that the elementary case of the problem can be solved with the help of a for loop and as long as a loop without reaching arrays.
What about something like that ?
public class Average {
public static void main(String... arguments) {
double average = Stream.of(arguments)
.mapToDouble(Double::parseDouble)
.average()
.orElse(0d);
System.out.println(average);
}
}
Exemple usage:
$ java Average 5 6 10 15 57
18.6
Related
The same formula gives different answers to 2296 and 1500, when the expected answer in both cases is 100. Please explain this behavior. I'm quite surprised by this simple thing. Initially I thought this must be due to operator precedence but I cannot understand this.
program with 2296 :
public class testpercent {
public static void main(String args[]) {
System.out.println("first formula ===>"+(2296 * 100 )/2296);
System.out.println("alternate formula =====>" + (2296/(2296/100)));
}
}
output:
first formula ===>100
alternate formula =====>104
same program with 1500:
public class testpercent {
public static void main(String args[]) {
System.out.println("first formula for ===>"+(1500 * 100 )/1500);
System.out.println("alternate formula for =====>" + (1500/(1500/100)));
}
}
output:
first formula ===>100
alternate formula =====>100
Program with 2296 first does (2296/100) giving 22.96 and drops the remainder of 96. Then does 2296/22 giving 104.
Program with 1500 just does the same but has no remainder and ends up with the "correct" answer.
If you want to get the output right using the alternate formula try using data types like double or float.
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.
I'm working on a question where I need to print the values in a reverse way using for loop in java. I have tried using the while loop and the for loop but I'm not able to print the values till required.
Please find my code below:
Lets say: y=1000, w=150, z=100;
while(y>=w) {
y-=z;
System.out.println(y);
}
i need to print the values like:
1000
900
800
700 and so on.
Kindly help as im new to Java.
public class reverse {
public static void main(String args[]){
int start=1000, end=150, decrement=100;
while(y>=w){
System.out.println(y);
y-=z;
}
System.out.println(w);
}
}
When i Run the code output is as follows:
1000
900
800
700
600
500
400
300
200
150
It is better to use 'for' loop when you have decrement or increment operation.
Use 'while' loop if you want to iterate with a condition.
int y=1000;
int z=100;
int w=150;
//loop to print values
for(int i=y;i>=w;i-=z)
{
//print
System.out.println(i);
}
I tried to write code to get the largest prime factor of a big number (in this case, 600851475143).
After writing four different methods (2 to show results, and 2 with other calculations), I have written the program class, and tried to run it.
When I run it, the result should appear in the console, but nothing shows up. I tried to make the variable that should be printed public, and just print it manually, but it didn't work. Eventually, I wrote the simplest System.out.print() command in the main method, but nothing appeared in the console.
I have no idea what the problem is. Does anyone here have a clue?
The class:
public class Problem3 {
public float sum1;
public float sum2;
private float num = 600851475143f;
public void methodGuy(){
while(sum1==0){
for(int i=2; i<num/2; i++){
if(num%i==0){
sum1=num/i;
} else {}
}
}
}
public void show1(){
System.out.println("the result of Guys method is: " + sum1);
}
public void methodOr(){
for(int i=2; i<num/2; i++){
for(float x=num/2; x>2; x=x-1){
if(i*x==num){
sum2=x;
}
}
}
}
public void show2(){
System.out.println("the result of Ors method is: " + sum2);
}
}
The program class:
public class Program {
public static void main(String[] args) {
Problem3 x = new Problem3();
x.methodGuy();
x.show1();
x.methodOr();
x.show2();
}
}
methodGuy will never terminate because int's can't get that big.
The largest possible value of an int is 2147483647. If your int is that number, and you add one to it, the number will wrap around and become negative. So after i++, the next value will be -2147483648. Since the loop will continue as long as i is less than 600851475143/2 = 300425237071.5, and since i will always be less than that, your loop is infinite.
Best would be to make both i and num have type long, instead of int or float. Even if you do that, your loop will probably run for a very long time.
In fact, if there are no factors, the loop will be infinite, because sum will never be set to something other than 0, and then since you say while (sum==0), the loop will just start over again and do the same thing infinitely. So aside from the wraparound problem, your algorithm still needs work.
Further note: You definitely do not want to use float for this, because the number 600851475143 cannot be represented exactly. The actual value of num will be 600851480576.
I'm using this basic and crude code below for calculating prime numbers then exporting them to a text file:
import java.util.Scanner;
import java.io.*;
public class primeGenerator{
public static void main(String[] args)throws Exception {
Scanner kb = new Scanner(System.in);
String prime;
long num = kb.nextLong();
long i;
long z=0;
while(z==0){
for (i=2; i < num ;i++ ){
long n = num%i;
if (n==0){
break;
}
}
if(i == num){
writer(num);
}
num=num+2;
}
}
public static void writer(long num) throws Exception {
FileWriter writer = new FileWriter("prime.txt",true);
String prime= ""+ num;
writer.write(prime);
writer.write(" ");
writer.flush();
writer.close();
}
}
I would like to find primes beyond the Primative long's range and apparently big integer is the way to go about it. So how do i alter my code to do so?
Do you really need this? Having numbers bigger than can be handled by long means you want to test numbers bigger than 9223372036854775807. If your for-loop can test a hundred million divisions per second, it will still take it 2923 years to determine if that number is prime - and longer for larger numbers, of course.
A common optimization is to only test divisions up to sqrt(num). If you haven't found anything then, the number is prime.
Well, use BigInteger wherever you've currently got long. Instead of using % you'll use mod, instead of incrementing you'll use i = i.add(BigInteger.ONE), instead of == 0 you'll use equals(BigInteger.ZERO) etc.
Use Scanner.nextBigInteger instead of Scanner.nextLong, too.
Given that this looks like homework of some description (possibly self-set, of course) I won't write out the whole code for you - but if you have specific problems, feel free to ask.