I made a simple program that calculate the Mean and Median value of given array from command-line.
import java.util.Arrays;
public class EdankJaya {
public static void main(String args[]) {
double sum = 0;
double d;
if(args.length < 1) {
System.out.println("Usage : java EdankJaya <Number1> <Number2> ..");
System.exit(1);
}
//Mean
for(String s : args) {
d = Double.parseDouble(s);
sum = sum+d;
}
double mean = sum/args.length;
System.out.println("Mean: " + mean);
//Median
Arrays.sort(args);
int med = args.length/2;
if((args.length % 2) == 0) {
double median1 = Double.parseDouble(args[med-1]);
double median2 = Double.parseDouble(args[med]);
System.out.println("Median :"+(median1+median2)/2);
} else {
double median = Double.parseDouble(args[med]);
System.out.println("Median :"+median);
}
}
}
Technique that i used for Median value is divide args.length by 2 and store it in med. If args.length value is even, it'll be args[med-1] + args[med], no problem for even number. And for odd args.length value, it'll just be args[med], which is works fine on the paper since integer will not produce fraction(11/2 gonna be 5), but here's what happened:
Everything's good until i inputted 1-10, the value turned back to the result when i inputted 1-8, and 1-11 just like 1-7, and so on.
What could be the issue here.
Thanks.
Your array has strings in it, not numbers, so they are not sortting in numerical order. They're probably sorting in ASCII order. Since you're already iterating over the array and converting them to numbers, build a second array with them and sort that one.
Related
import java.util.*;
import java.lang.*;
public class MyClass
{
String[] getdata()
{
Scanner in=new Scanner(System.in);
System.out.print("Enter numbers to calculate their average (choose 5 to 10 numbers only : ");
String[] a=in.nextLine().split(" ");
return a;
}
double average(String[] num)
{
double avg;
int tot=0;
int[] numbers = new int[num.length];
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+numbers[j];
}
avg=tot/l;
return avg;
}
void results(String[] arr,double avg)
{
int[] numbers1=new int[arr.length];
int ll=arr.length;
System.out.print("The average of the numbers ");
for(int i=0;i<ll;i++)
{
numbers1[i]=Integer.parseInt(arr[i]);
System.out.print(numbers1[i]+" ");
}
System.out.print("is ");
System.out.printf("%.2f",avg);
}
public static void main(String args[])
{
MyClass obj=new MyClass();
String[] x=obj.getdata();
double y=obj.average(x);
obj.results(x,y);
}
}
The code is running successfully but for any given output the average is showing as 0.00.
The code takes in integers with space between them and calculates the average and displays it
Help me fix it. Thanks
You do not initialize your numbers array inside average() method.
Instead of tot=tot+numbers[j]; do the following
tot = tot + Integer.parseInt(num[j]);
And to avoid integer deletion change calculation if avg to the following
avg = 1.0 * tot / l; //this will cast intermediate result of 1.0 * tot to double.
There are several issues with your code:
The only thing int[] numbers shares with String[] num input is length. All items of the array remain zero, which in itself is sufficient to explain zero result
Even though avg is double, tot/l is an int. It could be truncated down to zero, depending on the values inside num.
You need to modify your code to parse Strings from num, and compute total as double. After that the division would return the correct result.
Further, you can avoid multiple parses of strings if you return int[] from getdata() method. Given the small number of inputs, this one is not critical for performance of your code.
You never copy the values from String[] num to your int[] numbers, so when you loop through the whole array numbers, you are going to be summing the default value 0, l times.
You need to use parseInt() on all the values in num to convert it to ints and store them in numbers, then make sure you do float(tot)/l to cast it to a float during the division. This avoids truncation due to integer division.
In the average method you create an empty array called numbers. You're calculating the average based on that array which is empty.
Hope this helps
Your numbers array is wrong in the average function. Please find the corrected code below,
double average(String[] num)
{
double avg;
int tot=0;
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+Integer.parseInt(num[j]);
}
avg=tot/l;
return avg;
}
Change the data types as you need.
I'd recommend printing a from getdata() to ensure that your numbers are getting entered correctly. My best guess is taht something in the split command is not working right.
Your problem is your average function. You initializes the array of int[] num, but you did not write the int value in it. You can do that as in the same way as in void results(String[] arr,double avg).
Another problem is, that you get the average avg = tot/l; where tot and l are int values. When you divide 2 integer values the result is an int too and the int value will be written into 'avg'. If the average is a floiting point number (example input "1 2", then the floiting part get cutoff and your programm returns the avg = 1. Therefore the division needs at least one variable, which is double.
This one should work:
double average(String[] num)
{
double avg;
double tot=0;
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+Integer.parseInt(num[j]);
}
avg= tot/l;
return avg;
}
In your code you are not initializing the numbers[] array .
double average(String[] num)
{
double avg;
double tot=0;
int[] numbers = new int[num.length];
for(int i=0;i<num.length;i++)
{
numbers[i]=Integer.parseInt(num[i]);
}
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+numbers[j];
}
avg=tot/l;
return avg;
}
If you are using > Jdk8 . you can use
double average(String[] num) {
OptionalDouble tot = Arrays.stream(num).mapToInt(s -> Integer.parseInt(s)).average();
return tot.orElse(0.0);
}
}
I have written this code to get Fibonacci numbers by inputting the size.
The results i am getting is correct but only thing i am concerned about is the negative sign for some values for higher range of size input.
1- I am unable to find the flaw in the code, how can i get rid of the negative values in the output.?
2- Why after some negative values there are positive values.
3- First negative value is -1323752223 then a positive number follows.
Thank you.
Here is the code:
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a, c = 0;
int result = 0;
int b = 1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the Number to display Fibonacci Series");
a = scan.nextInt();
System.out.println("Fibonacci Seriers is as follows");
for (int i = 1; i <= a; i++) {
System.out.print(" "+result+" ");
result = c + b;
b = c;
c = result;
}
}
}
Depending on the input value, you likely exceeding the max value that an integer can hold.
Integers are limited to 2^31-1, or 2,147,483,647. Once you reach that threshold, the number will wrap around and start with the minimum value, -2^31, or -2,147,483,648.
Also see Integer.MAX_VALUE.
Well, you can use 'if' for System.out.print to check if result is negative or positive. The reason why you are getting negative values is because int is "only" 32-bit long.
You can use long instead of int, which would make it a little bit better for Fib. sequence, but it won't solve your actual problem - negative numbers.
Here is the code:
for( int i = 1; i <= a; i ++ ) {
if( result >= 0 ) {
System.out.print(" " + result + " ");
}
result = c + b;
b = c;
c = result;
}
try to modify type of variables from 'int' to 'long int' or ' unsigned int'. Maybe high value modify the bit of sign.
I am working at a programm right now where I need to sort an array of numbers ranging from 0 to 99999. In order to do so, one part of the task is to extract the digits from every number of the array, and that can be accomplished by
i = number / digit.
For example, for the number 23456, I am supposed to start by extracting the number 2, which can be done by using
digit = 10000
and calculating
i = 23456 / 10000 = 2.
A recursive call is then supposed to look at the next digit, so in this case we want to get
i = 23456 / digit = 3
and so on. I know that there are certain methods for this, but how can this be done with using only primitves? I already tried to play around with modulo and dividing the digit, but it's not giving any desired result.
Basic Formula
The n-th digit of a non-negative, integral, decimal number can be extracted by the following formula:
digit = ((num % 10^n) / 10^(n-1))
where % represents modulo division, / represents integer division, and ^ represents exponentiation in this example. Note that for this formula, the number is indexed LSD->MSD starting from 1 (not 0).
This formula will also work for non-decimal numbers (e.g. base 16) by changing 10 to the desired base. It will also work for negative numbers provided that absolute value of the final digit is taken. Finally, it can even function to extract the integer digits (but not fractional digits) of a floating point number simply by truncating and casting the floating-point number to an integral number before passing it to this formula.
Recursive Algorithm
So, to recursively extract all of the digits of a number of a certain length in order MSD->LSD, you can use the following Java method:
static public void extractDigits(int num, int length) {
if (length <= 0) { // base case
return;
}
else { // recursive case
int digit = (num % (int)Math.pow(10,length)) / (int)Math.pow(10,length-1);
/* do something with digit here */
extractDigits(num, length-1); // recurse
}
}
This method will never divide by zero.
Note: In order to "do something with digit here," you may need to pass in an additional parameter (e.g. if you want to add the digit to a list).
Optimization
Since your goal is to extract every digit from a number, rather than only one specific digit (as the basic formula assumes), this algorithm may be optimized to extract digits in order LSD->MSD so as to avoid the need for exponentiation at each step. (this approach original given here by #AdityaK ...please upvote them if you use it)
static public void extractDigits(int num) {
if (num == 0) { // base case
return;
}
else { // recursive case
int digit = num % 10;
/* do something with digit here */
extractDigits(num / 10); // recurse
}
}
Note: Any negative number should be converted to a positive number before passing it to this method.
Here's the code to recursively extract numbers from an integer. It will be in reverse order.
import java.util.*;
public class HelloWorld{
static void extractNumbers(int n, List<Integer> l) {
if(n==0)
return;
else {
l.add(n%10);
extractNumbers(n/10, l);
}
}
public static void main(String []args){
List<Integer> result = new ArrayList<Integer>();
extractNumbers(456789,result);
System.out.println(result);
}
}
Hope it helps.
I would do something like this:-
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int num=23456;
int numSize=5;
rec(num,numSize);
}
public static void rec(int num, int numSize){
if(numSize==0)
return;
int divideBy=(int)Math.pow(10,(numSize-1));
int out=(int)(num/divideBy);
System.out.println(out);
rec((num-out*divideBy),(numSize-1));
return;
}
See the output from here: http://ideone.com/GR3l5d
This can be easily done by using the for loop by converting the array elements into string.
var arr = [234, 3456, 1234, 45679, 100];
var compare = function(val1, val2) {
return val1 - val2;
};
arr.sort(compare); //sort function
var extract = function(value, index) {
var j = "";
var element = value + "";
for (var i in element) {
var val = element[i];
console.log(parseInt(val)); // this prints the single digits from each array elements
j = j + " " + val;
}
alert(j);
};
arr.forEach(extract); //extract function..
Prompt: You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. In each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
Here is the code I have so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer.");
int x = in.nextInt();
boolean even;
for (int i = 0; i == 5; i++) {
if ((x / 2) * 2 == x) {
even = true;
System.out.println(x + " is even.");
}
if ((x / 2) * 2 != x) {
even = false;
System.out.println(x + " is odd.");
}
}
}
Not looking for a solution, just some help as to what I need to do. Really confused about the whole Boolean thing.
This seems to be like your homework.
Seems like your 'boolean even' is not even being used, I would suggest that you don't declare nor use it. Use x = x%2 to get the number if it is even or odd is better. If it is even x should be 0, if it is odd x should be 1. % is equivalent to MOD
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
int even = 0; // keep tracks the number of even
int odd = 0; // keep tracks the number of odd
for (int i = 0; i < 5; i++) {
System.out.println("Enter an integer.");
x = in.nextInt();
if (x % 2 == 0) {
even++;
System.out.println(x + " is even.");
}
if (x % 2 == 1) {
odd++;
System.out.println(x + " is odd.");
}
}
System.out.println("Done");
System.out.println("Evens: " + even "\nOdds: " + odd);
}
This code should be the answer for your homework requirement. Your in.nextInt() should be inside the for loop since you need to request the user 5 times. Not only that, your loop should be < 5 as it will loop 5 times from 0, 1, 2, 3, 4
Well, your loop won't fire; i == 5 is always going to be false every time you reach the loop.
What you may want to change your loop statement to be would be:
for (int i = 0; i <= 5; i++) {
// code
}
Further, by virtue of the way Java evaluates branches, the variable even may not have been initialized. You need to instantiate it with a value.
boolean even = false;
Finally, the most straightforward way to tell if a number is even is to use the modulus operator. If it's divisible by two, it's even. Otherwise, it's odd.
if (x % 2 == 0) {
// even, do logic
} else {
// odd, do logic
}
You are missing a requirement from the assignment - that is, the ability to keep a running tally of the number of odd and even numbers, but I leave that as an exercise to the reader.
The part that you're missing is keeping track of how many even and how many odd numbers have been encountered. You'll want two separate int variables for this, which you'll declare before your main loop.
int numEvens = 0;
int numOdds = 0;
Then, in the branches where you work out whether the entered number is odd or even, you'll increment one or other of these numbers.
Lastly, at the end of your program, you can print them both out in a message.
if you want to do this with java boolean..i think this might help you
package stackOverFlow;
public class EvenOddNumber {
public boolean findEvenOdd(int num) {
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num;
EvenOddNumber e = new EvenOddNumber();
System.out.print("Enter a number:");
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
System.out.println( num+" is even number?: " + e.findEvenOdd(num));
}
}
A simpler way to find even and odd values is to divide number by 2 and check the remainder:
if(x % 2 == 0) // remainder is 0 when divided by 2
{
//even num
}
else
{
//odd num
}
Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
A method that accepts two integer parameters and returns their average.
A method that accepts three integer parameters and returns their average.
A method that accepts two integer parameters that represent a range.
Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
Implement the class and write a program to test its methods and submit your source code (.java files).
I am stuck on part three, I don't even really understand the stipulation. Will I be using a floating point / double? Here is the program I have thus far:
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
int numb1, numb2, numb3, userInput;
System.out.println("Enter '2' if you wish to average two numbers enter '3' if you wish to average 3.");
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
if (userInput == 2){
System.out.println("Enter two numbers you'd like to be averaged.");
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
Average ave = new Average();
System.out.println("The average is: " + ave.average(numb1, numb2));
System.exit(1);
}
if(userInput == 3){
System.out.println("Enter three numbers you'd like to be averaged.");
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
numb3 = keyboard.nextInt();
Average ave = new Average();
System.out.println("The average is: " + ave.average(numb1, numb2, numb3));
System.exit(1);
}
}
public static int average (int num1, int num2) {
return (num1 + num2) / 2;
}
public static int average (int numb1, int numb2, int numb3){
return (numb1 + numb2 + numb3) / 3;
}
}
Please don't re-ask the same question as you just asked here: http://stackoverflow.com/questions/19507108/java-averaging-program
Rather update your other post to reflect your new code / questions.
Now onto your question:
A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive). Implement the class and write a program to test its methods and submit your source code (.java files).
Lets start by declaring our method and we'll declare it as static to conform to your program (since you're not creating your own objects). Then we want to check if the parameters follow the assignment instructions and return values accordingly.
public static int getRange(int firstValue, int secondValue)
{
int range;
if (firstValue > secondValue)
range = firstValue - secondValue;
else
{
range = 0;
System.out.println("Error!");
}
return range;
}
**To promote your understanding it's up to you to find the average of the integers in the range!
Not really here to do your homework, but since I'm already here, the range is the difference between the largest and smallest number.
public int returnRange(int first, int second) {
if(first > second)
return first-second;
else
return second-first;
}
To make things easier though...
public double returnAverage(int...numbers) {
for(int i = 0; i < numbers.length(); i++) {
total += numbers;
}
return total/numbers.length();
}
public int returnRange(int...numbers) {
int holder = 0;
int highest;
int lowest;
for(int i = 0; i < numbers.length(); i++) {
if(numbers[i] > holder) {
holder = numbers[i];
}
highest = holder;
for(int i = 0; i < numbers.length(); i++) {
if(numbers[i] < holder) {
holder = numbers[i];
}
}
lowest = holder;
return highest-lowest;
}
Last 2 methods are un-tested, but from experience, should work fine. These methods have arrays for the parameters, so you can do as many numbers as you'd like.
In your main method check for -1 and return error when first value is greater than second
public double avgRange(int a, int b){
if(a>b){
return -1;
}
else{
double total=0;
for(int x=a; x<=b; x++){
total = total + x;
}
return total/(b-a+1);
}
}
the method should return the average of the integers in that range (inclusive).
You're asked to return the average of all integers in the range bounded by the two parameters.
For example, if parameters were 5 and 10, the method should return the average of 5, 6, 7, 8, 9, and 10, which is 7.5. (5 and 10 are included because the question says the range should be "inclusive".)
To find the average, use a for loop to sum each integer in the range, then divide by the number of integers.
Will I be using a floating point / double?
The return value should be a float or double, since the average isn't always a whole number.