I am a beginner in Java and I am wondering if there is a way to use one input from the user in more than one method? I am making a program that is supposed to take some inputs (integers) from the user and control the inputs, then calculate the average and lastly count the occurrence of the inputs?
I have one main method + 3 different methods (one calculates the average etc). I have tried a lot of different things, but haven't seemed to understand the point with parameters and how they work.
So this is just a quick overview.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int value = sc.nextInt(); //Number of how many elements the user want to enter
int[] input = new int[value]; //An array with all the values
}
public int secureInt(int number, int[] input, int value) {
if (!Integer.parseInt(number)) {
System.out.println("Invalid input");
} else {
for (int i = 0; i < value; i++) { //Add all the inputs in the array
input[i] = sc.nextInt();
}
}
public double averageCalculator (int value, int[] in){
double average; // The average
double sum = 0; // The total sum of the inputs
if (int i = a; i < value; i++) {
sum = sum + in[i];
}
average = sum / value;
return average;
}
//Count the occurence of inputs that only occure once
public static int countOccurence(//what parameter should i have here?) {
int count = 0;
}
}
Here is some code that may be helpful to you. The idea is to try to emulate or imitate the style & best practices in this excerpt:
import java.util.Scanner;
public class ArrayFiller {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int input_element_count = sc.nextInt(); //Number of how many elements the user want to enter
int element_count = input_element_count;
int[] array = new int[element_count]; //An array with all the values
enter_elements_of_array(array, element_count, sc);
double average = averageCalculator(array, element_count);
printArray(array);
System.out.println("The average of the entered numbers is " + average);
}
public static void printArray(int[] array) {
System.out.print("The array you entered is : [");
for (int element : array) {
System.out.print(" " + element + " ");
}
System.out.print("]" + "\n");
}
public static void enter_elements_of_array( int[] array, int element_count, Scanner sc) {
for (int i = 0; i < element_count; i++) { //Add all the inputs in the array
System.out.println("Please enter element " + (i+1) + " of " + element_count + ":");
array[i] = sc.nextInt();
}
}
public static double averageCalculator ( int[] array, int element_count){
double average; // The average
double sum = 0; // The total sum of the inputs
for (int i = 0; i < element_count; i++) {
sum = sum + array[i];
}
average = sum / element_count;
return average;
}
//Count the occurence of inputs that only occur once
public static int countOccurence(int[] array) {
int count = 0;
// algorithm for counting elements with cardinality of 1
return count;
}
}
Related
I'm trying to create a program that will take a user input, input that data into an dynamic array, and then recursively finds the average. The first part of my code works. This allows the newly created array to be passed to the method.
public static void main(String args[])
{
int i = 0;
int sum = 0;
double runningTotal = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
}
findAverage();
for (i=0; i < newClassSize.length; i++){
sum = sum + newClassSize[i];
}
System.out.println(Arrays.toString(newClassSize));
keyboard.close();
}
}
This is where I'm getting confused and confusing myself however. How would I pass the newly created array to the findAverage() method? I would then need to also have that be saved to an accumulator and then devided. Is there a better way to do this? This is my current findAverage() method but I'm confusing myself on my implementation.
public double findAverage(int classAverage, int baseCase, double runningAverage)
{
runningAverage = 0;
int sum = 0;
if (newClassSize.length - 1 > baseCase)
runningAverage = newClassSize.length;
return findAverage();
System.out.println("The class average is " + classAverage);
}
Hopefully I understood your question correctly but heres how to do it below.
The basic idea is that when the index reaches the length of the array in the
recursive function that's the base case. So all you have to do is add to the sum at each index point in the array, and just keep passing in the updated index and sum into the recursive function.
class Main {
public static void main(String[] args) {
int newClassSize[] = {1,2,3}; // User Input let say
double average = findAverage(newClassSize);
System.out.println(average);
}
public static double findAverage(int[] arr){
// Avoid division by zero error
if (arr.length==0){
return 0;
}
return findAverageHelper(arr,0,0);
}
public static double findAverageHelper(int[] arr, int index,int sum){
if (index==arr.length){ // Base Case
return (double) sum/arr.length;
}
// Increase index and add current value at index to sum
return findAverageHelper(arr,index+1,sum+=arr[index]);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Well, the program that follows, when run, will let me ‘roll a pair of dice’ n-times (i.e.
generate a number between 1 and 6), where n is a positive integer entered. The
program then outputs the pair of numbers (‘rolled dice’), as well as the sum of the numbers
(each pair of dice). The pairs of numbers are stored in a 2-dimensional array, and the sum
of each pair are stored in a single-dimensional array.
import java.util.Scanner;
import java.util.Random;
public class diceProblem{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of times a pair of dice will roll: ");
int times = input.nextInt();
int[][]dicePairs = rollDicePairs(times);
System.out.println("The rolled pairs of numbers are: ");
printDicePairs(dicePairs);
int[][]dicePairsSums = addDicePairs(dicePairs);
System.out.println("The sum of each pairs of numbers are: ");
printDicePairsSums(dicePairsSums);
}
public static int[][]rollDicePairs(int times){
int[][]dice = new int[times][2];
Random die = new Random();
for(int x=0;x<times;x++){
for(int y=0;y<2;y++){
dice[x][y] = 1+die.nextInt(6);
}
}
return dice;
}
public static void printDicePairs(int[][]dicePairs){
for(int[]pair: dicePairs){
for(int roll: pair){
System.out.print(roll+" ");
}
System.out.println("");
}
}
public static int[][]addDicePairs(){
int[]pairSums = new int[dicePairs];
for(int x=0;x<pairSums.length;x++){
int sum = 0;
for(int y=0;y<dicePairs[x].length;y++){
sum += dicePairs[x][y];
}
pairSums[x] = sum;
}
return pairSums;
}
public static void printDicePairsSum(int[]dicePairsSums){
for(int sum: dicePairsSums){
System.out.print(sum+" ");
}
}
}
The problem is there are too many errors with this program and it doesn't run or output the pairs of number and the sum
You code does not compile. Below is the corrected code that does compile and it also produces the correct results when you run it. Compare it to your code so as to spot the differences.
import java.util.Random;
import java.util.Scanner;
public class DiceProb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of times a pair of dice will roll: ");
int times = input.nextInt();
int[][] dicePairs = rollDicePairs(times);
System.out.println("The rolled pairs of numbers are: ");
printDicePairs(dicePairs);
int[] dicePairsSums = addDicePairs(dicePairs);
System.out.println("The sum of each pairs of numbers are: ");
printDicePairsSum(dicePairsSums);
}
public static int[][] rollDicePairs(int times) {
int[][] dice = new int[times][2];
Random die = new Random();
for (int x = 0; x < times; x++) {
for (int y = 0; y < 2; y++) {
dice[x][y] = 1 + die.nextInt(6);
}
}
return dice;
}
public static void printDicePairs(int[][] dicePairs) {
for (int[] pair : dicePairs) {
for (int roll : pair) {
System.out.print(roll + " ");
}
System.out.println("");
}
}
public static int[] addDicePairs(int[][] dicePairs) {
int[] pairSums = new int[dicePairs.length];
for (int x = 0; x < pairSums.length; x++) {
int sum = 0;
for (int y = 0; y < dicePairs[x].length; y++) {
sum += dicePairs[x][y];
}
pairSums[x] = sum;
}
return pairSums;
}
public static void printDicePairsSum(int[] dicePairsSums) {
for (int sum : dicePairsSums) {
System.out.print(sum + " ");
}
}
}
I am trying to use a set to find the unique numbers and get the sum from user entered numbers. I heard that arrays are easier but a set might just do for me. I don't know much about sets or what they do so any input would be fantastic. Much appreciated everybody!
import java.util.Scanner;
public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);
public double go()
{
double a = 0
counter = 10;
int total = 0;
for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}
System.out.println("the total is ";
return a;
}
}
java.util.HashSet stores unique values. Made minor changes to your program to use Set to store unique values and calculate sum of unique values using for loop
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);
public int go() {
int a = 0;
int n = 0;
counter = 10;
Set<Integer> unValues = new HashSet<Integer>();
while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}
int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}
public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality
I used here (HashSet).
import java.util.Scanner;
public class quiz_assignment
{
int counter;
Scanner scan = new Scanner(System.in);
Set<Integer> ditinctSet = new HashSet<Integer>();
public int go()
{
int a=0;
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(!ditinctSet.contains(newInteger)){
ditinctSet.add(newInteger);
}
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
a=a+newInteger;
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("Distinct numbers are: ");
System.out.println(ditinctSet);
return n;
}
}
And here a link to start knoing more about sets.
Hashsets are useful because they don't store duplicate entries. You can use them to store your set of unique numbers that the user inputs. I also removed the variable "a" from your code because its purpose seemed identical to variable n's.
import java.util.Scanner;
public class quiz_assignment{
int counter;
Scanner scan = new Scanner(System.in);
public int go()
{
HashSet<Integer> distinctNumbers = new HashSet<>();
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
distinctNumbers.add(newInteger);
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
int size = distinctNumbers.size();
System.out.println("The sum of all ten integers is: " + n);
System.out.println("You inputed " + size + " numbers.");
System.out.println("Your numbers are:");
for(Integer i: distinctNumbers){
System.out.println(i);
}
return n;
}
}
I am new to java programming. I am trying to convert an string variable with array to an int variable array
but i have 2 errors and have no idea to fix it,
any help would be great, thanks..
This is my source code :
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int sum=0;
for(x=0;x<=1;x++)
{
System.out.print("input number : ");number[x]=in.next();
int value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum+number[x];
}
for(x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
This is what the errors look like
when you convert an array of stirngs to an array of integers,
we should have an array of integers declared
and in the code that you posted there are some syntax errors because you didnt declare integer array before use(int value[x])
and try the below code which will convert string array of numbers(string number[]) into an ineger array of numbers(int value[])
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100]; // here I declared an array of integers with the name value
int sum=0;
for(int x= 0;x <= 1; x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum + value[x];
}
for(int x=0; x<=1; x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
Use in.nextInt() method.
Scanner in = new Scanner(System.in);
int number[] = new int[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {`enter code here`
System.out.print("input number : ");
number[x] = in.nextInt();
sum = sum + number[x];
}
System.out.println("Sum :\t " + sum);
in.close();
}
Create a int array, then use it. int value[x]= Integer.parseInt(number[x]); is an error because your are trying to assign an integer to an array.
Correct one may be...
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100];
int sum=0;
for(int x=0;x<=1;x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]);
sum=sum+value[x];
}
for(int x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
There seems problem with declaration and usage of variable in you sample code.
Variable x is not initialzed
An integer value is assigned to and array declaration.
Try the below code to solve your issues.
import java.util.Scanner;
public class stringtoint {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {
System.out.print("input number : ");
number[x] = in.next();
int value = Integer.parseInt(number[x]);
sum = sum + value;
}
for (int x = 0; x <= 1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
in.close();
}
}
public static void main(String args[]) {
String[] exampleOfStringArray = {"11", "22", "33"/*, "ab", "cd", "ef", "", null*/};
int[] intArray = getIntArray(exampleOfStringArray);
int sum = getSumOf(exampleOfStringArray);
}
private static int[] getIntArray(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).toArray();
}
private static int getSumOf(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).sum();
}
Try below code, it is working.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
int noOfInputs = 2;
int value[] = new int[noOfInputs];
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.print("input number : ");
number[x] = in.next();
value[x] = Integer.parseInt(number[x]);
sum = sum + value[x];
}
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
}
Note: Just a practice problem, not for marks.
This is a practice problem given in a first year Java course:
Design and implement an application that reads an arbitrary number of integers, by the user, that are in the range 0 to 50 inclusive, and counts how many occurrences of each are entered. After all the input has been processed, print all of the values (with the number of occurrences) that were entered one or more times.
In addition, write a method that returns no value which would compute the average of the occurrences of all numbers entered by the user.
This is what I have (I have skipped the "average occurrence" part until I clean this up):
import java.util.Scanner;
public class Main
{
public static Scanner scan = new Scanner(System.in);
public static int[] userIntegers() // this method will build the array of integers, stopping when an out-of-range input is given
{
System.out.println("Enter the number of integers to be recorded: ");
int numInts = scan.nextInt();
int[] userArray = new int[numInts];
int i = 0;
while(i < numInts)
{
System.out.println("Enter an integer between 1-50 inclusive: ");
int userInteger = scan.nextInt();
if(isValidInteger(userInteger))
{
userArray[i] = userInteger;
i++;
}
else if(isValidInteger(userInteger) == false)
{
System.out.println("Try again.");
}
}
return userArray;
}
public static void occurrenceOutput(int[] input) // this method will print the occurrence data for a given array
{
int[] occurrenceArray = new int[51];
int j = 0;
while(j < 51) // iterates through all integers from 0 to 50, while the integer in the array is equal to integer j, the corresponding occurance array element increments.
{
for(int eachInteger : input)
{
occurrenceArray[j] = (eachInteger == j)? occurrenceArray[j]+=1: occurrenceArray[j];
}
j++;
}
int k = 0;
for(int eachOccurrence : occurrenceArray) // as long as there is more than one occurrence, the information will be printed.
{
if(eachOccurrence > 1)
{
System.out.println("The integer " + k + " occurrs " + eachOccurrence + " times.");
}
k++;
}
}
public static boolean isValidInteger(int userInput) // checks if a user input is between 0-50 inclusive
{
boolean validInt = (51 >= userInput && userInput >= 0)? true: false;
return validInt;
}
public static void main(String[] args)
{
occurrenceOutput(userIntegers());
}
}
Can someone point me in a more elegant direction?
EDIT: Thanks for the help! This is where I am at now:
import java.util.Scanner;
public class simpleHist
{
public static void main(String[] args)
{
getUserInputAndPrint();
getIntFreqAndPrint(intArray, numberOfInts);
}
private static int numberOfInts;
private static int[] intArray;
private static int[] intFreqArray = new int[51];
public static void getUserInputAndPrint()
{
// The user is prompted to choose the number of integers to enter:
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Integers: ");
numberOfInts = input.nextInt();
// The array is filled withchInteger = integer; integers ranging from 0-50:
intArray = new int[numberOfInts];
int integer = 0;
int i = 0;
while(i < intArray.length)
{
System.out.println("Enter integer value(s): ");
integer = input.nextInt();
if(integer > 50 || integer < 0)
{
System.out.println("Invalid input. Integer(s) must be between 0-50 (inclusive).");
}
else
{
intArray[i] = integer;
i++;
}
}
// Here the number of integers, as well as all the integers entered are printed:
System.out.println("Integers: " + numberOfInts);
int j = 0;
for(int eachInteger : intArray)
{
System.out.println("Index[" + j + "] : " + eachInteger);
j++;
}
}
public static void getIntFreqAndPrint(int[] intArray, int numberOfInts)
{
// Frequency of each integer is assigned to its corresponding index of intFreqArray:
for(int eachInt : intArray)
{
intFreqArray[eachInt]++;
}
// Average frequency is calculated:
int totalOccurrences = 0;
for(int eachFreq : intFreqArray)
{
totalOccurrences += eachFreq;
}
double averageFrequency = totalOccurrences / numberOfInts;
// Integers occurring more than once are printed:
for(int k = 0; k < intFreqArray.length; k++)
{
if(intFreqArray[k] > 1)
{
System.out.println("Integer " + k + " occurs " + intFreqArray[k] + " times.");
}
}
// Average occurrence of integers entered is printed:
System.out.println("The average occurrence for integers entered is " + averageFrequency);
}
}
You are actually looking for a histogram. You can implement it by using a Map<Integer,Integer>, or since the range of elements is limited to 0-50, you can use an array with 51 elements [0-50], and increase histogram[i] when you read i.
Bonus: understanding this idea, and you have understood the basics of count-sort
To calculate occurences, you can do something like this:
for(int eachInteger : input) {
occurrenceArray[eachInteger]++;
}
This will replace your while loop.