I know i can't pass arrays the way I'm doing it. Would I need to pass by reference if so how? The question is at the bottom for reference.
import java.util.Scanner;
public class MethodsArrays {
public static int[] fillArray() {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int array[] = new int[size];
int pos=0;
for(int i=0; i<array.length; i++) {
pos=i+1;
System.out.println("Enter element " + pos);
array[i]=scan.nextInt();
}
return array;
}
public static int sumArray(int [] array) {
int sum=0;
for(int i=0; i<array.length-1; i++) {
sum=array[i]+array[i+1];
}
return sum;
}
public static int avgArray(int [] array) {
int avg=0;
int sum = sumArray(array);
avg = sumArray(array)/array.length-1;
return avg;
}
public static void printArray(int [] array) {
for(int i=0; i<array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
fillArray();
System.out.println("Sum=" + sumArray(array));
System.out.println("Average=" + avgArray(array));
printArray(array);
}
}
Write a Java program, called MethodsArrays that has 4 static methods
called fillArray(), sumArray(), avgArray(), and printArray(). The
fillArray() method should be called from the main method. The
fillArray() method should use a Scanner to take in a number
representing the length of the array and then read in numbers to fill
the array. The sumArray() method should take an int array as its input
parameter and returns an integer value that is the sum of all the
elements in the array. The avgArray() method should take an int array
as its input parameter and returns an integer value that is the
average of all the elements in the array. The printArray() method
should take an int array as its input parameter and has no return
value. It should then print out the elements of the array on the same
line separated by a space (“ “). All methods should work for integer
arrays.
Your code looks OK. You just need to assign the result of fillArray() to a variable, in order to use this result for further methods.
It would look like:
int[] array = fillArray();
System.out.println("Sum=" + sumArray(array));
System.out.println("Average=" + avgArray(array));
printArray(array);
Related
My code will not compile and I can not figure out how to fix the error. It is a compile time run error I think. My error is in my method to print out array. Then, it says that there is something wrong with my closing bracket for the class. I am using a scanner class and I did import it, it is just not shown. Any help?
My code:
public static void main (String[] args){
int[] getArray; //reference to an int array of type and takes no parameters
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
int[] nums; //reference to nums array of type int
nums = new int[size]; /* new array of type int. assigned to nums.
size, to specify number of elements array will have */
for(int i=0; i<nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt(); //storing user input into array
return nums;
}//closing for loop
int[] minimumValue;
min = scan.nextInt();
min = nums[0]; //assigning min value to first element in array
return min;
for(int i=0; i<min.length; i++){
if(i<min){
min = nums[0];
}
}
return min;
public static void printArray (int[] getArray){ //method to print out array
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length); //print out array
}
}
public static void printArrayInReverse(int[] getArray){ //method for arrayInReverse
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
int[] numbers = getArray();// calling getArray method
public static void main (String[] args){
System.out.print("************");
printArray(numbers); //calling printArray method and passing numbers through it
printArrayInReverse(numbers);// calling printArrayInReverse method and passing numbers through it
System.out.print(minimumValue(numbers)); /* calling minVal through print statement and passing
numbers through it*/
}
}
}
It is very hard to tell what you are trying to accomplish here from your code. There is no class here which means your program will not even compile, please remember to post all applicable code to your question as it makes it easier for people to help you.
Firstly, you can only have one entry point (ie. main(String[] args) for each class. This is better explained here Can there exist two main methods in a Java program?.
Within this main method, you cannot have any other methods, you can only call other methods and perform operations ad such.
The variable "scan" cannot ever do anything if it is not instantiated prior to use. The variable getArray is being used as a method, which it is not.
Please take a look at Simple Java array program where it shows more in-depth how to use arrays.
Take a look at this as see if it even accomplishes what you want to do, which is still somewhat unclear. I shortened everything so that it is simpler, with a program this small multiple methods are not needed unless there is some logic to denote when to print the array or when to print the array reversed.
import java.util.Scanner;
public class CLASSNAME {
static Scanner scan = new Scanner(System.in);
static int[] nums;
public static void main(String[] args){
// Get Size Of Array
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
nums = new int[size];
// Fill Array
for(int i = 0; i < nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt();
}
// Set 0th Number To
System.out.println("Enter 0th Number");
int min = scan.nextInt();
nums[0] = min;
// Print Array
System.out.println("\n" + "Printing Array Index 0 -> ArraySize");
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length);
}
// Print Array Reversed
System.out.println("\n" + "Printing Array Index ArraySize -> 0");
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
}
you need to create a Scanner object to use it
you can't create more than one main method
you must create methods outside the main method
Example:
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//code here
}
public static void method_name() {
//code here
}
//If you want to return integer value for example
public static int method_name() {
//code here
}
}
minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}
so my program is supposed to access a text document then do all that jazz that currently works. The only problem that I can't figure out is how to shuffle the contents of an array without having them end up on top of each other. Both internets and multiple tries with random and for loops have been unfruitful. here is my code:
import java.io.*;
import java.util.*;
public class lab_6 {
public static void main(String[] args)throws FileNotFoundException {
Scanner input = new Scanner(System.in); //reads from keyboard
System.out.println("What is the name of your file. ");
String name = input.nextLine();
Scanner reader = new Scanner(new File(name));// Open text file
System.out.println("how many names are in your array");
int num = input.nextInt();
String[] names = new String[num];
for (int index = 0; index< names.length; index++)
{
names[index] = reader.nextLine();// Gets a line while there is one
}
System.out.println("\nOriginal List");
printList(names);
System.out.println("\nShuffled List");
shuffle(names);
printList(names);
System.out.println("\nSorted List");
Arrays.sort(names); // this is a built in method
printList(names);
System.out.println("What name are you looking for");
Scanner input1 = new Scanner(System.in); //reads from keyboard
String find = input1.nextLine();
int index = search(names,find);
if(index == -1)
System.out.println("The name was not there");
else
System.out.println(find+" was found at position "+index);
System.out.println("The average length of all the names is "+averageLength(names));
}
public static void printList(String[] array) // print the list of names numbered
{
for (int i=0; i<array.length; i++)
{
System.out.println((i+1)+") "+ array[i]);
}
}
public static void shuffle (String[] array) // mix-up the array
{
}
public static int search(String[] array, String find)
{
for(int i=0; i<array.length; i++) {
if (array[i].equals(find) ) return i;
}
return -1;
}
public static double averageLength(String[] array) //return the average length of the names
{
int sum=0;
for (int i=0; i<array.length; i++)
{
int l= array[i].length();
sum +=l;
}
int average = sum/(array.length);
return average;
}
}
String[] names = ...;
Collections.shuffle(Arrays.asList(names));
// done
Note that Arrays.asList() returns a modifiable (but fixed-length) list, backed by the array, and not a copy of the array. So the array will be shuffled.
Just use the Fisher-Yates shuffle (Knuth algorithm P):
private Random rand = new Random();
public static void shuffle(String[] array) { // mix-up the array
for (int i = array.length - 1; i > 0; --i) {
int j = rand.nextInt(i + 1);
String temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
See:
Knuth, D. 1969, 1998: Seminumerical Algorithms 1st & 3rd Eds. The Art of Computer Programming Series, Volume 2, p. 125.
Fisher, Ronald A.; Yates, Frank (1948) [1938]. Statistical tables for biological, agricultural and medical research (3rd ed.). London: Oliver & Boyd. pp. 26–27.
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
https://stackoverflow.com/a/1520212/636009
You can use the Collections class, with the shuffle method. The documentation is available here.
Example
int[] values = {1,2,3,4,5};
List<Integer> valuesList = Arrays.asList(values);
Collections.shuffle(valuesList);
// valuesList is shuffled.
import java.util.Scanner;
import java.io.*;
public class practice3
{
public static void main(String[] args) throws IOException
{
int[] array = new int [99];
array = inputData();
for(int i=0; i<array.length; i++)
System.out.printf("%d",array[i]);
}
public static int[] inputData() throws IOException
{
final int MAX= 100;
int[] nums = new int[MAX];
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.print("Enter input file name: ");
String input = kb.nextLine();
File file = new File(input);
if(!file.exists())
{
System.out.println("The file entered is not found");
System.exit(0);
}
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && count < nums.length)
{
nums[count] = inputFile.nextInt();
count++;
}
inputFile.close();
return nums;
}
public static void printArray(int[] array, int counter)
{
System.out.println("Original array: ");
System.out.printf("%,12\n", array);
}
}
I don't know why these zeroes are printed after the array values I test from opening a file. I want to print the array itself and not the rest of the numbers. I tried messing with the MAX variable, but I dont know what to do.
The for loop in you main() iterates over the length of the array, which is 100 elements. The elements that you did not overwrite default to 0.
To solve this, pass the array as an argument to your inputData() and have it return how many elements it put into the array like:
public static int inputData(int[] input) {
// ...
input[count] = whatever;
// ...
return count;
}
Refactor arrays from int to Integer (0 -> null)
Add this before printing, it'll remove nulls from Integer (not int) array. (if int there will be zeroProblem)
int count = 0;
for (Integer i : array) {
if (i != null) {
count++;
}
}
Integer[] newArray = new Integer[count];
int index = 0;
for (Integer i : array) {
if (i != null) {
newArray[index++] = i;
}
}
Aim is to get an array and arrange it accending, and print
package habeeb;
import java.util.*;
public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[10];
int i, count=0, m;
System.out.println("Enter the integers, with 0 to end the array" );
for( i=0; i<num.length; i++){
num[i]= input.nextInt();
Zero breaks the array here
if(num[i]==0)
break;
count++;
Calling the function here\
}
Sorting(num, count);
The function sorting is here
}
public static void Sorting(int[] sort, int con){
if(con<0)
return;
int j, max=0, coun=0, temp;
for(j=0; j<con; j++){
if(sort[j]>max)
max=sort[j];
coun=j;
}
here am swaping the last value in the array for any index thats the highest
temp=sort[con];
sort[con]=sort[coun];
sort[coun]=temp;
Calling the function again here(recursive)
Sorting(sort, con-1);
Here am printing, why is it not printing
for(j=0; j<con; j++){
System.out.println(sort[j]);
}
}
}
Is there a reason not to use Arrays.sort() ?
All you have to do is call
Arrays.sort(num);
Be careful since this will modify your array and will not create a sorted coyp of it!