trouble calling a method in the same class java - java

I've been asked to do the following problem:
Implement a method that accepts an array of integers as input and returns the sum of all of the elements in the array as output.
this is what i have(the entire program):
import java.util.*;
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}
every time I try to call the method "sum" in the main method it gives me an error. I have tried every possible way I've seen on the internet to call the method. I'm not sure how I'm supposed to call it or if it is an issue because I have an array passed to the method.
Someone please help! and if you see that i've done something incorrectly, please let me know! thanks

public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
// this works
System.out.println("sum is " + sum(array));
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}

Related

Moving my for loop into a different method and connecting it to main Java

I'm making a program using Java that calculates the sum of the numbers entered; I figured this part out. However, I want to move the for loop into a different method called "Sum", but I keep getting errors and I don't know what to do.
Here is the code thats only in the Main method (it works perfectly fine):
import java.util.Scanner;
public class testing {
public static void main(String args[]){
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
However, when I move the for loop into the method known as print, I get a bunch of errors:
import java.util.Scanner;
public class MPA4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
}
print(sum);
}
public static void print (double []sum){
Scanner in = new Scanner(System.in);
int myArray[] = new int [size];
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
Here are all the errors underlined in red:
I'm not sure what I'm doing wrong, any help would be much appreciated!
I changed it as below and it is working.
import java.util.Scanner;
public class MP4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int[size];
System.out.println("Enter the elements of the array one by one: ");
for (int i = 0; i < size; i++) {
myArray[i] = in.nextInt();
}
print(myArray, size);
}
public static void print(int[] myArray, int size) {
int sum = 0;
Scanner in = new Scanner(System.in);
for (int i = 0; i < size; i++) {
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: " + sum);
}
}

Swapping the numbers in an Array

I am trying to create a method that will accept the users input for the amount of elements they would like in an array, and the numbers to input for the array.
So far I have the main method which accepts the input from the console using the following code, after that I am not 100% sure if the method I need to create should return an int array or should just print out the results.
import java.util.Scanner;
public class Lab {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input amount desired in Array 1");`
int a = input.nextInt();
int [] array1 = new int[a];
for (int i = 0; i < array1.length; i++) {
System.out.println("Input a number");
array1[i] = input.nextInt();}
System.out.println();}
public int swapPairs(int [] array)
Ok, so You just do this:
public void swapPairs(int [] array){
for(int i = 0; i < array.length(); i += 2){
if(i != array.length - 1)
System.out.print(array[i] + " " + array[i+1]);
}
if(array.length % 2 == 1) System.out.print(" " + array[array.length - 1]);
It really depends on what you want to achieve. If you need only to see the results the print is enough but if you return the array you can operate on the one that is changed as you wanted

Using method in System.out wont work?

I am tasked with several objectives in my assignment, I am to read a file, which i believe I did correctly, and from that file of integers, put it into an array. It wont let me compile the code, it comes up with an error at smallest. So, how do I printout the method of the min?
public class jlrogers2 {
public static void reader(int[] arr) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("numbers.txt"));
int i = 0;
while(scanner.hasNextInt())
{
arr[i++] = scanner.nextInt();
}
}
public static int minnimum(int[] arr){
int smallest =arr[0];
for (int i = 1; i>arr.length; i++){
if (arr[i] > smallest)
{
smallest= arr[i];
System.out.println(smallest);
}
}
return smallest;
}
public static void main(String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
System.out.println(minnimum(smallest)) // here is my issue }
}
}
Change for (int i = 1; i>arr.length; i++) to for (int i = 0; i<arr.length; i++)
And also your logic to find smallest is wrong. Actually you are finding the largest.
To find smallest put it as
if(arr[i] < smallest ) inside for loop
Change the main as
public static void main(String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
int arr[] = new int [200];//change this according to the requirement
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
reader(arr);
System.out.println(minnimum(arr));
}
}
There seem to be many problems with your code:-
->First as others have pointed change for (int i = 1; i>arr.length; i++) to for (int i = 1; i<arr.length; i++)
-> variable int smallest used, is not a class level variable and also is never locally declared in main()
-> method minimum() is never called from main, also method reader() seems to be not called
-> close the scanners after use, call scanner.close() at method end
Make some changes hence:-
-> main() would now look like:-
public static void main(String [] args) throws FileNotFoundException
{
int[] arr=new int[100];
reader(arr);//call this to populate arr[]
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
System.out.println(minnimum(arr));
}
in.close();
}
To find smallest element you need to change your loop like this:
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}

How to pass array to a java method

Here is my code:-
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
System.out.println("Please enter your key");
int k =input.nextInt();
int Low=numbers[0];
int H=numbers[4];
Recursion(k,numbers ,Low , H);
}
how can i pass array to a method ?
i got error in the last line
i tried to make the method void and do all those things inside method but i got error ?
Java always passes arguments by values to method. In case of Arrays/Objects it passes by value as well but here in this case its value is a reference.
Following is the code snippet you can use to pass an array to a method and return it back again.
import java.util.HashMap;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int[] numbers = new int[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
System.out.println("Please enter your key");
int k = input.nextInt();
int Low = numbers[0];
int H = numbers[4];
int[] recursiveResult = recursion(k, numbers, Low, H);
}
private static int[] recursion(int k, int[] numbers, int low, int h) {
// TODO Auto-generated method stub
// Some Operation
return numbers;
}
}

Issues with Returning Array

So I was tasked with asking the user to input 10 numbers into an array and then printing the numbers in order and reverse order using a tester class and not just the main.
I'm having problems with how to return the array that has been passed. Here's my code so far:
public class PrintIt
{
static int[] numbers = new int[10];
static int i = 0;
public static int PrintOrder()
{
System.out.println("\nList of numbers in order: \n");
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
return ;
}
public static int PrintReverse()
{
System.out.println("\nList of numbers in reverse order: \n");
for (int i = numbers.length - 1; i >= 0; i--)
{
System.out.println(numbers[i]);
}
return ;
}
}
and the tester class:
import java.util.Scanner;
public class PrintItTester
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
int i = 0;
int[] numbers = new int[10];
System.out.println("\nPlease input " + 10 + " numbers.");
for (i=0; i < numbers.length; i++)
{
PrintIt.numbers[i] = input.nextInt();
}
System.out.print(PrintIt.PrintOrder());
System.out.print(PrintIt.PrintReverse());
}
}
When I run the code with numbers[i] in the return it reads i as being 0 and only outputs the first element in the array. I've looked for a long time and I can't figure this out.
I know, obviously, that there needs to be something returned, but whatever I put doesn't work. For example, when I try to return the array, numbers[i], it only returns the first element because the variable has a value of 0.
You have several problems in your code:
The declaration int[] numbers = new int[10]; in the main is useless. Remove it, and replace numbers.length with PrintIt.numbers.length
Your methods return ints, not arrays. Make them void, and call them without System.out.print.
Remove the unnecessary return statements from the PrintOrder and PrintReverse methods.
This should fix the problem (demo).

Categories