0

Okay here's a Java assignment I've been having trouble with. I asked earlier about this and got some good comments and advice, but have since understood the assignment more clearly and the issue has changed a bit. So here's the assignment:

                                        ***

Your task is to complete the program below by writing three methods (askInfo, copyInfo and setArray). Program should ask for integers (max 100 integers) until the users types in zero. Integers can vary from one to one hundred and they are stored in an array that has 100 elements. Numbers are asked for with the askInfo method, which receives the array with numbers as parameter. Method returns the number of integers. The number zero is not saved in the array; it is merely used to stop giving input. The given numbers are then copied to another array which size is the amount of given numbers. Copying is done with copyInfo method which receives both arrays as parameters. After this the elements of the new array are put in ascending order with setArray method and printed on screen with printArray method.

Program to complete:

import java.util.*;

public class RevisionExercise {

public static void main(String[] args) {



    int[] tempArray = new int[100];

    System.out.println("Type in numbers. Type zero to quit.");

    int amountOfNumbers = askInfo(tempArray);



    int[] realArray = new int[amountOfNumbers];

    copyInfo(realArray, tempArray);



    setArray(realArray);



    printArray(realArray);

}


// Your code here


public static void printArray(int[] realArray ) {

    System.out.println("\Ordered array: ");

    for(int i = 0; i < realArray .length; i++) {

        System.out.println(realArray [i]);

    }

}

Example print:

Type in numbers. Type zero to quit. 1. number: 3 2. number: 8 3. number: 5 4. number: 6 5. number: 9 6. number: 0

Ordered array: 9 8 6 5 3


I'm struggling with the askInfo method. So far I've written this but it returns only zeroes. Here's my askInfo method:

public static int askInfo(int[] tempArray) { //askinfo-metodi

    Scanner reader = new Scanner(System.in);

int i;

    for (i = 0; i < tempArray.length; i++) {

        System.out.print((i+1) + ". number: ");
        tempArray[i] = reader.nextInt();

    if (tempArray[i] == 0) {
    return tempArray[i];    
    }


    }

    return tempArray[i];

}   



                       ***

How can I make it to register the input and get the amount of numbers to be passed to the next method in the assignment as described in the assignment.

4

1 回答 1

2

您永远不会将整luku数值存储在数组中,因此您的数组永远不会从全零的默认初始化整数值更改。在您的循环中,您需要添加一个

tempA[i] = luku;

在 if 语句确认luku不是之后0。总而言之:

if (luku == 0) {
    return i;   
}
tempA[i] = luku;
于 2013-08-19T18:40:15.207 回答