CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Threaded View

  1. #1
    Join Date
    Jan 2018
    Location
    Java 8
    Posts
    16

    Method returning multiple values using an array.

    I've been working through problems I found from when I was in school. Came across this one problem where I am a bit confused. The question states:

    Implement a method named positive. The method accepts 3 integer parameters named: alfa, beta, gama.
    The method returns the number of non-negative integers it received.

    This is what I have so far:

    Code:
    public class MyMethods {
    
    public int[] positive(int alfa, int beta, int gama){
    		int count=0;
    		int[] temp = new int[3];
    		
    		if(alfa > 0){
    			count++;
    			temp[count-1] = alfa;
    		}
    			
    		if(beta>0){
    			count++;
    			temp[count-1] = beta;
    		}
    
    		if(gama>0){
    			count++;
    			temp[count-1] = gama;
    		}
    		
    		int [] value = new int[count];
    		
    		for (int i=0; i<3; i++)
    		{
    			value[i] = temp[i];
    		}
    		
    		return value;
    	}
    }
    In my main method I wrote this code to test it but the array does not print out:

    Code:
    import java.util.Scanner;
    
    public class RunMyMethods {
    
    	public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		MyMethods mm = new MyMethods();
    
    		int a, b, g;
    		System.out.println("Enter 3 integers (positive or negative): ");
    		a = scan.nextInt();
    		b = scan.nextInt();
    		g = scan.nextInt();
    		System.out.println(mm.positive(a, b, g));
         }
    }
    Am i supposed to be using a for loop instead in the positive method? if so how would I use that with the three values alfa, beta, gama? Or am i suppose to create a temporary array in each if statement and then copy and resize the original array? I'm probably over thinking this but I feel like i hit a dead end.
    Last edited by rcheeks23; January 16th, 2018 at 09:09 PM. Reason: updated my code

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured