I want ask a little question about my program.
This is my code sample:
public static void main(String[] args) {
int q;
int p;
int thelargest;
int thesmallest;
Scanner input = new Scanner(System.in);
System.out.println("Enter the list of number : ");
String input2 = input.nextLine();
String[] numbers = input2.split(" ");
int[] result = new int[numbers.length];
for (p = 0; p < numbers.length; p++) {
result[p] = Integer.parseInt(numbers[p]);
}
for (q = 0; q < result.length; q++) {
System.out.print("");
System.out.println(result[q]);
}
System.out.println("Largest Number : " + LargestNumber(result));
System.out.println(" Smallest Number : " + SmallestNumber(result));
thelargest = LargestNumber(result);
thesmallest = SmallestNumber(result);
System.out.println("The Arithmetic Mean : "
+ AirthmeticMean(result, thesmallest, thelargest));
}
public static int SmallestNumber(int[] series) {
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int LargestNumber(int[] series) {
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
public static float AirthmeticMean(int[] result, int thesmallest,
int thelargest) {
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum += result[i];
}
sum -= thesmallest;
sum -= thelargest;
return (float) sum / result.length;
}
How can I convert this code sample to the ConsoleProgram (which is in the ACM library)?
Which parts must I change or add?
I started with:
public class ArithmeticMean extends ConsoleProgram {
}
But I do not know what to do next.
In acm library no main method though you need to use instead the following construction:
public void run() {}
Here is an API of this library http://jtf.acm.org/javadoc/student/
Select acm.program package ConsoleProgram class and find appropriate methods
see also acm.io / class IOConsole
e.g. System.out.println() --> println()
Scanner (String input) --> readLine(String prompt) etc.
the rest is the same as you in your code.
Ok, here you are your code in acm: (a bit ugly but works fine:)
import acm.program.ConsoleProgram;
public class StackOverflow extends ConsoleProgram
{
private static final long serialVersionUID = 1L;
public void run()
{
int q;
int p;
int thelargest;
int thesmallest;
String input2 = "";
String[] numbers = null;
println("Enter the list of number : ");
while (true) {
String input = readLine();
if (input.equals(""))
break;
input2 += input + " ";
}
numbers = input2.split(" ");
int[] result = new int[numbers.length];
for (p = 0; p < numbers.length; p++) {
result[p] = Integer.parseInt(numbers[p]);
}
for (q = 0; q < result.length; q++) {
print("");
println(result[q]);
}
println("Largest Number : " + LargestNumber(result));
println(" Smallest Number : " + SmallestNumber(result));
thelargest = LargestNumber(result);
thesmallest = SmallestNumber(result);
println("The Arithmetic Mean : "
+ AirthmeticMean(result, thesmallest, thelargest));
}
public static int SmallestNumber(int[] series)
{
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int LargestNumber(int[] series)
{
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
public static float AirthmeticMean(int[] result, int thesmallest,
int thelargest)
{
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum += result[i];
}
sum -= thesmallest;
sum -= thelargest;
return (float) sum / result.length;
}
}
And Run as JavaApplet
Related
I am going to include just the necessary code here. I have indicated the problem area, about 8 lines in. I am wanting to use the containSameElements method with these inputs, k and n. I know that the problem is that it is not in the right data type (array) but i'm not sure where to change it/ what to change. I've been messing with this for some time now and I just can't seem to figure it out
import java.util.Scanner;
class Lottery
{
public static double jackpotChance(int k, int n, int m)
{
double jackpotChance = 0;
System.out.println(factorial(n)); //factorial
return jackpotChance;
}
public static double factorial(int n)
{
double result = 1;
for (int i = 1; i <= n; i++) //counter i
{
result *= i;
}
return result;
}
public static int[] enterNumbers(int k, int n)
{
System.out.println();
Scanner s = new Scanner(System.in);
System.out.println("Enter k.");
k = s.nextInt();
System.out.println("Enter n.");
n = s.nextInt();
final int SIZE = k;
int enterNumbers[]= new int[SIZE];
System.out.println("Enter " + k + " integers between 1 and " + n + ".");
int i=SIZE;
for (i = 0; i < enterNumbers.length; i++) //counter i
{
System.out.println("Enter the next number");
Scanner ss = new Scanner(System.in);
int p = ss.nextInt();
if (p >= 1 && p <= n)
{
enterNumbers[i] = p;
}
else
{
System.out.println("Invalid input, please try again.");
i--;
}
}
System.out.println();
System.out.println("Your chosen numbers are: ");
for (i = 0; i < enterNumbers.length; i++)
{
System.out.print(enterNumbers[i] + " ");
}
System.out.println();
System.out.println("Enter m.");
int m = s.nextInt();
jackpotChance(k,n,m);//jackpot
drawNumbers(k,n);
return enterNumbers;
}
public static int[] drawNumbers(int k, int n)
{
int drawNumbers[]= new int[k];
int randNumber;
int i=k;
for (i = 0; i < drawNumbers.length; i++)
{
randNumber = (int) (Math.random()*n + 1); // random draw number
drawNumbers[i] = randNumber; }
System.out.println();
System.out.println("Your drawn numbers are: ");
for (i = 0; i < drawNumbers.length; i++) //counter i
{
System.out.print(drawNumbers[i] + " ");
}
return drawNumbers;
}
public static void main (String[] args)
{
System.out.println("Welcome to the Tennessee Lottery");
System.out.println("----------------------------");
int k = 0;
int n = 0;
enterNumbers(k,n);
if(containSameElements(a,b)==true)
System.out.println("Winner!");
else
System.out.println("Loser.");
}
public static boolean containSameElements(int[] a, int[] b)
{
int len1 = a.length;
int len2 = b.length;
if(len1!=len2)
return false;
else
{
int flag = 0;
for(int i=0;i<len1;i++)
{
for(int j=0;j<len2;j++)
{
if(a[i]==b[j])
{
flag = 1;
break;
}
}
if(flag==0)
return false;
else
flag = 0;
}
}
return true;
}
}
Simplify your testing code.
public class ArrayOps {
static private final int SIZE = 10;
public static void main(final String[] args) {
System.out.println("Welcome to the Tennessee Lottery");
System.out.println("----------------------------");
final int[] k = new int[SIZE];
final int[] n = new int[SIZE];
enterNumbers(k, n);
if (containSameElements(k, n) == true) //PROBLEM AREA
System.out.println("Winner!");
else System.out.println("Loser.");
}
private static void enterNumbers(final int[] pK, final int[] pN) {
for (int i = 0; i < SIZE; i++) {
pK[i] = (int) (Math.random() * SIZE);
pN[i] = (int) (Math.random() * SIZE);
}
}
public static boolean containSameElements(final int[] pK, final int[] pN) {
if (pK.length != pN.length) return false;
// mandatory check
for (final int k : pK) {
if (!arrayContains(pN, k)) return false;
}
// optional check, only if arrays have to contain EXACTLY the same elements
for (final int n : pN) {
if (!arrayContains(pK, n)) return false;
}
return true;
}
static private boolean arrayContains(final int[] pArray, final int pLookForNumber) {
for (final int i : pArray) {
if (i == pLookForNumber) return true;
}
return false;
}
public static int[] drawNumbers(final int k, final int n) {
final int drawNumbers[] = new int[k];
int randNumber;
int i = k;
for (i = 0; i < drawNumbers.length; i++) {
randNumber = (int) (Math.random() * n + 1); // random draw number
drawNumbers[i] = randNumber;
}
System.out.println();
System.out.println("Your drawn numbers are: ");
for (i = 0; i < drawNumbers.length; i++) //counter i
{
System.out.print(drawNumbers[i] + " ");
}
return drawNumbers;
}
}
How can I get this to calculate properties about arrays of doubles. If everything else is an int inside, would that still as an array of doubles? Or is it still an array of doubles anyway because of the method type? Here is my class. Thanks so much!
import java.util.*;
import java.lang.Math;
public class Statistics {
private double min;
private double max;
private double mean;
private double median;
private double deviation;
private double mode;
public static double findMin(int[] array){
int min = array[0];
for(int i=1;i<array.length;i++){
if(array[i] < min){
min = array[i];
}
}
return min;
}
public static double findMax(int[] array){
int max = array[0];
for(int i=1;i<array.length;i++){
if(array[i]>max){
max=array[i];
}
}
return max;
}
public static double calcMean(int[] n){
int sum=0;
for (int i=0; i<n.length; i++){
sum+= n[i];
}
return sum/n.length;
}
public static double calcMedian(int[] n){
int middle = n.length/2;
if (n.length%2==1){
return n[middle];
} else {
return (n[middle]+n[middle])/2;
}
}
public static double calcDeviation(int[] n){
int mean = (int)calcMean(n);
int squareSum = 0;
for (int i = 0; i < n.length; i++) {
squareSum += Math.pow(n[i] - mean, 2);
}
return Math.sqrt((squareSum) / (n.length - 1));
}
public static double calcMode(int n[]){
int value=0; int max=0;
for (int i=0;i<n.length;++i){
int count=0;
for (int j=0; j<n.length; ++j){
if (n[j]==n[i]) ++count;
}
if (count>max){
max=count;
value=n[i];
}
}
return value;
}
}
Here is my main method.
import java.util.*;
public class StatisticsTester {
public static void main(String[] args) {
Statistics test = new Statistics();
Scanner input = new Scanner(System.in);
//Read user input.
System.out.print("How many numbers do you want to enter?: ");
int num = input.nextInt();
double array[] = new double[num];
System.out.println("Enter the " + num + "numbers now.");
for (int i = 0; i < array.length; i++ )
{
array[i] = input.nextInt();
}
System.out.print("Here is the minimum, ");
System.out.print("maximum, mean, median, ");
System.out.println("mode, and standard deviation: ");
System.out.print(test.findMin(num) +", " + test.findMax(num));
System.out.print(", "+ test.calcMean(num) +", ");
System.out.print(test.calcMedian(num) +", ");
System.out.print(test.calcMode(num) +", ");
System.out.print(test.calcDeviation(num));
}
}
These are the errors when it compiles.
StatisticsTester.java:25: findMin(int[]) in Statistics cannot be applied to (int)
System.out.print(test.findMin(num) +", " + test.findMax(num));
^
StatisticsTester.java:25: findMax(int[]) in Statistics cannot be applied to (int)
System.out.print(test.findMin(num) +", " + test.findMax(num));
^
StatisticsTester.java:26: calcMean(int[]) in Statistics cannot be applied to (int)
System.out.print(", "+ test.calcMean(num) +", ");
^
StatisticsTester.java:27: calcMedian(int[]) in Statistics cannot be applied to (int)
System.out.print(test.calcMedian(num) +", ");
^
StatisticsTester.java:28: calcMode(int[]) in Statistics cannot be applied to (int)
System.out.print(test.calcMode(num) +", ");
^
StatisticsTester.java:29: calcDeviation(int[]) in Statistics cannot be applied to (int)
System.out.print(test.calcDeviation(num));
^
6 errors
There are two errors :
First : When you do this - test.findMin(num) you are trying to pass parameter num. But num is not array! It is a number. You probably want to do this : test.findMin(array)
Second : You can implicitly convert integer to double, because you can be sure that it remains same. But you cant convert double to integer implicitly, because you cant convert for example 2,7 to integer. And for arrays, even the "implicit" conversion does not work.
Solution for you, change this line double array[] = new double[num]; to int array[] = new int[num]; and then change all your parameters which looks like this test.findMin(num) to this test.findMin(array)
For working with doubles this would compile (does not know if it works as expected) :
import java.util.*;
public class StatisticsTester {
public static void main(String[] args) {
Statistics test = new Statistics();
Scanner input = new Scanner(System.in);
//Read user input.
System.out.print("How many numbers do you want to enter?: ");
int num = input.nextInt();
double array[] = new double[num];
System.out.println("Enter the " + num + "numbers now.");
for (int i = 0; i < array.length; i++) {
array[i] = input.nextDouble();
}
System.out.print("Here is the minimum, ");
System.out.print("maximum, mean, median, ");
System.out.println("mode, and standard deviation: ");
System.out.print(test.findMin(array) + ", " + test.findMax(array));
System.out.print(", " + test.calcMean(array) + ", ");
System.out.print(test.calcMedian(array) + ", ");
System.out.print(test.calcMode(array) + ", ");
System.out.print(test.calcDeviation(array));
}
}
import java.util.*;
import java.lang.Math;
public class Statistics {
private double min;
private double max;
private double mean;
private double median;
private double deviation;
private double mode;
public static double findMin(double[] array) {
double min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
public static double findMax(double[] array) {
double max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
public static double calcMean(double[] n) {
int sum = 0;
for (int i = 0; i < n.length; i++) {
sum += n[i];
}
return sum / n.length;
}
public static double calcMedian(double[] n) {
int middle = n.length / 2;
if (n.length % 2 == 1) {
return n[middle];
} else {
return (n[middle] + n[middle]) / 2;
}
}
public static double calcDeviation(double[] n) {
int mean = (int) calcMean(n);
int squareSum = 0;
for (int i = 0; i < n.length; i++) {
squareSum += Math.pow(n[i] - mean, 2);
}
return Math.sqrt((squareSum) / (n.length - 1));
}
public static double calcMode(double n[]) {
double value = 0;
int max = 0;
for (int i = 0; i < n.length; ++i) {
int count = 0;
for (int j = 0; j < n.length; ++j) {
if (n[j] == n[i]) {
++count;
}
}
if (count > max) {
max = count;
value = n[i];
}
}
return value;
}
}
My question is about discarding the largest and smallest number when my program calculates an arithmetic mean.
This is my code sample:
public static void main(String[] args) {
int k;
int r;
int thelargest;
int thesmallest;
Scanner input = new Scanner(System.in);
System.out.println("Enter the list of number : ");
String input2 = input.nextLine();
String[] numbers = input2.split(" ");
int[] result = new int[numbers.length];
for (r = 0; r < numbers.length; r++) {
result[r] = Integer.parseInt(numbers[r]);
}
for (k = 0; k < result.length; k++) {
System.out.print("");
System.out.println(result[k]);
}
System.out.println(" LargestNumber : " + TheLargestNumber(result));
System.out.println(" SmallestNumber : " + TheSmallestNumber(result));
thelargest = TheLargestNumber(result);
thesmallest = TheSmallestNumber(result);
System.out.println("The Arithmetic Mean : " + AirthmeticMean(result));
}
public static int TheSmallestNumber(int[] series) {
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int TheLargestNumber(int[] series) {
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
public static float AirthmeticMean(int[] result) {
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum += result[i];
}
return (float) sum / result.length;
}
I tried to find the way and I wrote this sample but I don't know how to embed this code sample:
for (int i = 0; i < result.length; i++) {
if (series[i] != thesmallest && series[i] != thelargest) {
total = total + seriess[i];
}
}
Will this code sample be helpful to me?
Just before your
System.out.println("The Arithmetic Mean : " + AirthmeticMean(result));
write
thenewmean = (AirthmeticMean(result)*result.length - thesmallest - thelargest)/(result.length-2)
and then print thenewmean
System.out.println("The Arithmetic Mean : " + thenewmean);
You don't need to write your
for (int i = 0; i < result.length; i++) {
if (series[i] != thesmallest && series[i] != thelargest) {
total = total + seriess[i];
}
}
code anywhere. Even then if you wish to use your own code,
then use it in your AirthmeticMean() function
Need to keep track of count as well as sum if removing highest and smallest
public static float AirthmeticMean(int[] result, int theSmallest, int theLargest) {
int sum = 0;
int cnt = 0;
for (int i = 0; i < result.length; i++) {
if (result[i] != theSmallest && result[i] != theLargest) {
sum += result[i];
cnt++;
}
}
return (float) sum / cnt;
}
The code sample you've got:
for (int i = 0; i < result.length; i++) {
if (series[i] != thesmallest && series[i] != thelargest) {
total = total + seriess[i];
}
}
is almost OK. Almost, because you retrieve the length of the array named result in the for-loop and access elements of array series.
You can use this code in the following way. Extend AirthmeticMean with two parameters theSmallest and theLargest and keep track of the number of summed elements:
public static float AirthmeticMean(int[] result, int theSmallest, int theLargest) {
int sum = 0;
int numElements = 0;
for (int i = 0; i < result.length; i++) {
if (result[i] != theSmallest && result[i] != theLargest) {
sum += result[i];
numElements++;
}
}
return (float) sum / numElements;
}
EDIT: added numElements.
I write a code sample about calculate the aritmetic mean,i did lots of thing but some parts are missing/incorrect.
This is my code sample :
public static void main(String[] args) {
int i;
int j;
int thelargest;
int thesmallest;
Scanner input = new Scanner(System.in);
System.out.println("Enter the list of number : ");
String input2 = input.nextLine();
String[] numbers = input2.split("\\s+");
int[] result = new int[numbers.length];
for (j = 0; j < numbers.length; j++) {
result[j] = Integer.parseInt(numbers[j]);
}
for (i = 0; i < result.length; i++) {
System.out.print("");
System.out.println(result[i]);
}
System.out.println("The Largest Number : "
+ findTheLargestNumber(result));
System.out.println("The Smallest Number : "
+ findTheSmallestNumber(result));
thelargest = findTheLargestNumber(result);
thesmallest = findTheSmallestNumber(result);
float arithmeticMean = (float) (result[i + j])// result.length;
System.out.println("The Arithmetic Mean : " + arithmeticMean);
/*There is a mistake and I tried to solve it but I didn't find any way to solve it.I want my programme to sum the results(numbers) and divide into number of result.(For example :10+20+30=60 and the aritmetic mean is 60/3=20.)Lastly,I think the mistake is about (float)(result[i+j]).
*/
}
public static int findTheSmallestNumber(int[] series) {
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int findTheLargestNumber(int[] series) {
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
}
Thanks for everbody which gonna help to me .
public static float getAirthmeticMean(int[] result){
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum+=result[i]);
}
return (float)sum/result.length;
}
Your instinct is correct. The result[i+j] line doesn't make sense. How about another function?
public static float calculateMean(int[] series) {
int sum = 0;
for(int i = 0; i < series.length; i++) {
sum = sum + series[i];
}
return ((float)sum) / series.length;
}
Just add all the numbers in the array together in a for loop, and then divide by the length of the array.
Ok, the title might be deceiving. All i want to do is take my Bingo program and when the second bingo card is printed, i want to replace all the "0"'s with "X"'s. I was thinking i would have to go and change the array to an string, but i'm not surer where to start.
Here is the Bingo program:
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Bingo
{
public static final int ROWS = 5;
public static final int COLS = 5;
public static final int VERTICAL = 1;
public static final int DIAGONAL = 2;
public static final int HORIZONTAL = 3;
public static int winFound;
public static int currPick = 0;
public static int randomPick = 0;
public static int WinFound;
public static void main(String[] args)
{
int Totcards;
int[][] card = new int[ROWS][COLS];
int[] picks = new int[25];
fillCard (card);
printCard(card);
playGame(card);
printCard(card);
finalCard(card);
}
private static void fillCard (int[][] card)
{
// FileReader fileIn = new FileReader("Bingo.in");
// Bufferreader in = new Bufferreader(fileIn);
try {
Scanner scan = new Scanner(new File("bingo.in"));
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
card[i][j] = scan.nextInt();
}
}
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
}
private static void printCard (int[][] card)
{
System.out.println("\n\tYOUR BINGO CARD : ");
System.out.println("\n\tB I N G O");
System.out.println("\t----------------------");
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
System.out.print("\t" + card[i][j]);
}
System.out.print("\n");
}
}
private static void playGame (int[][] card)
{
int numPicks = 0;
System.out.println("\n\tBINGO NUMBERS PICKED AT RANDOM FROM BIN: ");
while (true)
{
markCard (card); // Generate a random num & zero-it out
winFound = checkForWin(card); // Look for zero sums
numPicks++;
if (winFound != 0)
{
if (winFound == 1)
{
System.out.print("\n\n\tYOU WIN WITH A VERTICAL WIN AFTER " + numPicks + " PICKS\n");
}
else if (winFound == 2){
System.out.print("\n\n\tYOU WIN WITH A DIAGONAL WIN AFTER " + numPicks + " PICKS\n");
}
else if (winFound == 3){
System.out.print("\n\n\tYOU WIN WITH A HORIZONTAL WIN AFTER " + numPicks + " PICKS\n");
}
announceWin (numPicks);
return;
}
}
}
private static void markCard (int[][] card)
{
int randomPick = (int) (Math.random() * 74) + 1;
for (int j = 0; j < ROWS; j++){
for (int k = 0; k < COLS; k++){
if (card[j][k]==randomPick)
card[j][k] = 0;}
}
System.out.print("\t " + randomPick + " ");
System.out.print("");
}
private static int checkForWin(int[][] card)
{
int sum=0;
for (int i = 0; i < ROWS; i++)
{
sum = 0;
for (int j = 0; j < COLS; j++)
sum += card[i][j];
if (sum == 0)
return HORIZONTAL;
}
for (int j = 0; j < COLS; j++)
{
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][j];
if (sum == 0)
return VERTICAL;
}
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][ROWS-i-1];
if (sum == 0)
return DIAGONAL;
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][i];
if (sum == 0)
return DIAGONAL;
return WinFound;
}
private static void makeCard(int[][] card, int[] picks)
{
int count = 100;
int currPick = 0;
for (int i=0; i<count; i++){
currPick = (int)(Math.random() * 74) + 1;
System.out.print(" " + currPick + "\n");
picks[i] = currPick;
}
}
private static void announceWin(int numPicks)
{
}
private static boolean duplicate (int currPick, int[] picks, int numPicks)
{
for (int i = 0; i < numPicks; i++){
if (picks[i] == currPick){
return true;}
}
return false;
}
private static void finalCard (int[][] card)
{
Arrays.sort(card);
final String stringRep = Arrays.toString(card);
final String[] out =
stringRep.substring(1, stringRep.length() - 1).split("\\s*,\\s*");
System.out.println(Arrays.toString(out));
}
}
Try this:
System.out.print("\t" + (card[i][j] == 0 ? "X" : card[i][j]))
Why don't you just use a String[][] for the fields from the beginning? You can still compare String values with ints (with Integer.valueOf for instance) and this way you don't have to switch types runtime...