How to return string array?

Xerf Source
  1. Design a copy machine template: CopyMachine.java with

    • Public static variable int totalNoOfCopy, which records the total number of copies made from all the copy machines

    • method with signature: public String[] copy(String strText, int intNos), which will update totalNoOfCopy value and return a String array with all its element value being strText and array size being intNos.

  2. Design a program UseCopyMachine.java:

    • Create object canon and fujistu from CopyMachine.javab
    • Copy 6 "Flying!" on canon machine and copy 8 "High!" on fujitsu machine
    • Show all the copies’ content from the 2 copy machines to user and print out the total number of copies from the 2 copy machines.

Totally new to java and here is my progress, some advice what to do next?

public class CopyMachine {

    static int totalNoOfCopy;

    public String[] copy(String strText, int intNos)
    {
        String[] ac= new String[intNos];
        totalNoOfCopy += intNos;
        return ac;
    }
}

public class UseCopyMachine {
    CopyMachine canon = new CopyMachine();
    CopyMachine fujitsu = new CopyMachine();
 }
javaarraysstring

Answers

answered 10 months ago Sridhar #1

From my understanding I think you need something like,

You have to iterate over the array using loop to insert and retrieve the elements.

public class CopyMachine {

    public static int totalNoOfCopy;

    public String[] copy(String strText, int intNos) {
        String[] ac= new String[intNos];
        for (int i=0; i< intNos; i++) {
            ac[i] = strText;
        }
        totalNoOfCopy += intNos;
        return ac;
    }

    public static void main(String[] args) {
        CopyMachine canon = new CopyMachine();
        String[] canonCopys = canon.copy("Flying!", 6);
        CopyMachine fujitsu = new CopyMachine();
        String[] fujitsuCopys = fujitsu.copy("High!", 8);

        System.out.println("Copies from Canon");
        for(String str: canonCopys) {
            System.out.println(str);
        }

        System.out.println("Copies from fujitsu");
        for(String str: fujitsuCopys) {
            System.out.println(str);
        }

        System.out.println("Total copies:" + CopyMachine.totalNoOfCopy);
    }
}

Prints,

Copies from Canon
Flying!
Flying!
Flying!
Flying!
Flying!
Flying!
Copies from fujitsu
High!
High!
High!
High!
High!
High!
High!
High!
Total copies:14

comments powered by Disqus