Throwing arrays as objects
Hey everyone, new here. :) I'm a beginner in Java really (started about a month ago)
Need help with this program I'm trying to do...
Basically, it needs to ask me for the size of the array.
So let's say I input '4'
it will ask me 'Enter name' and then 'Enter age' 4 times. Once you've finished inputting data, it will print it out in different lines (since they are arrays after all). I'm using BufferedReader and InputStreamReader as well as functions to print.
I'm really confused with the logic...
here's the code so far:
Code :
import java.io.*;
public class ObjFunc {
int size=3;
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader strbuf=new BufferedReader(in);
void printArr(String strArr[])
{
for(int x=0;x<strArr.length;x++)
{
System.out.println(strArr);
}
}
String [] populateArr(String myArray[])
{
myArray[0]="one";
myArray[1]="two";
myArray[2]="three";
return myArray;
}
int getSizeArray() throws IOException
{
System.out.println("Enter size of the array");
int size=Integer.parseInt(strbuf.readLine());
System.out.println("The size of the array is: "+size);
return size;
}
public static void main(String[] args) throws IOException {
ObjFunc Of=new ObjFunc();
Of.getSizeArray();
System.out.println("Enter name");
String name=Of.strbuf.readLine();
System.out.println("Name is: "+name);
System.out.println("Enter " + name + "'s age");
int age=Integer.parseInt(Of.strbuf.readLine());
System.out.println("Age is: "+age);
String nameArr[];
nameArr=new String [Of.size];
String newArray[]=Of.populateArr(nameArr);
Of.printArr(newArray);
}
}
I basically jsut need guidelines on what to do next...
thanks
Re: Throwing arrays as objects
For beginning programmers (and plain lazy programmers like me), I'd recommend using the Scanner class for user input.
FYI: you can't throw arrays as objects, but via polymorphism you can view arrays as objects, and they can be passed to methods by reference.
Code :
public static void main(String[] args)
{
// read from the console
Scanner reader = new Scanner(System.in);
// get size of array from the user
System.out.println("How many do you want to read in?");
int num = reader.nextInt();
// create the array
Object[] array = new Object[num];
for (int i = 0; i < array.length; i++)
{
// read in anything you want for your array here
System.out.println("Input an integer: ");
array[i] = new Integer(reader.nextInt());
}
}