import java.util.Scanner;
public class hh {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int numbers = input.nextInt();
// Declare an array called numbers with a size of 10
int[] numbers1 = new int[numbers];
insertRandomNumbers(numbers1);
// Print size of numbers
System.out.println("Initial Array: ");
for (int i = 0; i < numbers1.length; i++) {
System.out.print(numbers1[i] + " ");
}
System.out.println("");
//Print First and Last Elements
System.out.println();
System.out.println("First and Last Elements");
int [] lastStep = lastStep(numbers1);
for (int i = 0; i < lastStep.length; i++) {
System.out.print(lastStep[i] + ", ");
}
} // end main
public static int[] lastStep(int[] numbers1) {
//to get first
int [] firstElement= numbers1.get(0);
//last number
int [] lastElement= numbers1.get(numbers1.size()-1);
}
return lastStep;
public static void insertRandomNumbers(int[] x) {
for (int i = 0; i < x.length; i++) {
x[i] = random();
// System.out.print(x[i] + " ");
}
// System.out.println();
}
public static int random() {
int r = 0 + (int) (Math.random() * (101 - 0)) + 0;
return r;
}
My program ask the user to enter a number, then if 10 is entered 10 random numbers are created. With those 10 numbers I need to get the first and last numbers. The way I have my method right now I am getting ERROR: Cannot invoke get(int) on the array type int[]
WHEN I USE
public static int[] lastStep(int[] numbers1) {
//to get first
int [] firstElement= numbers1.array[0];
//last number
int [] lastElement= numbers1.array[numbers1.size()-1];
}
return lastStep;
I get that array cannot be resolved or is not a field
That's because you're using an Array not an ArrayList. Try using numbers1[0] and numbers1[numbers.length - 1]
You should consider changing your lastStep function. From what I can see, it does nothing, because the return statement is outside the function braces. There is also no variable lastStep inside the function that can be returned. Try the following:
public static string firstAndLast(int[] numberArray)
{
return numberArray[0] + ", " + numberArray[numberArray.length - 1];
}
Then just call it like:
System.out.println(firstAndLast(numbers1));
You can't use .get(0) on an array, you have to use array[0].
In your case it would be: numbers1[0]
Use Array List for to add random numbers , then print the last and first one.
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]);
}
}
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;
}
}
What I’m attempting to do is search “gradePsd” array find the highest grade and if there are two grades that are the same value print the name (s) of the students to console.
The problem I’m having is that this method is taking the first index value of the array and printing it because it IS the high value at the first pass and if the second value is larger than the first then it will also print and so on.
So my question is how can I get it to just print the student (s) with the high grade.
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
String nameRtn = "";
int num = gradePsd[0];
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
for (int i = 0; i < gradePsd.length; i++)
{
if (gradePsd[i] >= num)
{
num = gradePsd[i];
nameRtn = NamePsd[i];
}
System.out.print(nameRtn + ", ");
}
}
first find the highest number
then print the students with that number
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
String nameRtn = "";
int num = gradePsd[0];
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
//find the highest number
for (int i = 0; i < gradePsd.length; i++){
if (gradePsd[i] >= num){
num = gradePsd[i];
}
//print students with that number
for (int j = 0; j < NamePsd.length; j++){
if (gradePsd[j] == num)
{
nameRtn = NamePsd[j];
System.out.print(nameRtn + ", ");
}
}
one of possible 1000 solutions.
Initialize num with -1 and take the System.out out of the for loop. But you can only determine one student with your code. You need nameRtn to be a Collection if you want to store more than one name.
Something like this:
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) {
Collection<String> namesRtn = new ArrayList<String>();
int num = -1;
for (int i = 0; i < gradePsd.length; i++) {
if (gradePsd[i] > num) {
num = gradePsd[i];
namesRtn.clear(); // clear name list as we have a new highest grade
namesRtn.add(NamePsd[i]); // store name in list
} else if (gradePsd[i] == num) {
namesRtn.add(NamePsd[i]); // if a second student has the same grade store it to the list
}
}
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are: " + namesRtn);
}
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.
I am working on a large number adding program (without using biginteger class). I thought I had this understood but for some reason I am getting an ArrayIndexOutOfBoundsException for my add method:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at LargeInteger.add(LargeInteger.java:50)
at testLargeInteger.main(testLargeInteger.java:32)
main:
import java.util.Scanner;
public class testLargeInteger
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1;
String string2;
int exp =0;
System.out.print("Enter the first integer: ");
//Store up the input string “string1” entered by the user from the keyboard.
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.print("Enter the second integer: ");
string2 = input.next();
//Store up the input string “string2” entered by the user from the keyboard.
LargeInteger secondInt = new LargeInteger(string2);
System.out.print("Enter the exponential integer: ");
//Store up the input integer “exp” entered by the user from the keyboard.
exp = input.nextInt();
LargeInteger sum = firstInt.add(secondInt);
System.out.printf ("First integer: %s \n", firstInt.display());
System.out.println("Second integer: " + secondInt.display());
System.out.println(" Exponent: " + exp);
System.out.printf (" Sum = %s \n", sum.display());
}
}
LargeInteger class:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
public LargeInteger( int[] array ) {
intArray = array;
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
//get first array
public int[] getIntArray() {
return intArray;
}
public LargeInteger add(LargeInteger secondInt){
int[] otherValues = secondInt.getIntArray();
int maxIterations = Math.min(intArray.length, otherValues.length);
int currentResult; //to store result
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
int needToAdd = 0; //to store result should be added next step
for(int i = 0; i < maxIterations; i++) {
currentResult = intArray[i] + otherValues[i];
resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer
needToAdd = currentResult / 10; //this is what you need to add on next step
}
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
return new LargeInteger( resultArray );
}
}
Here you declare the array with length:
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
and here you access it using the same length:
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
In Java (and computer languages generally), the array indices begin at 0 and end at length - 1. So if you declare an array 10 elements long, then the indices are 0-9. Therefore you must substract one:
resultArray[Math.max(intArray.length, otherValues.length)] = needToAdd;
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
arrays in java starts from 0, and your allocated space is exactly the same ammount of elements:
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
So, you get an out of index, since you access one element out of the array.