adding in array from stdin

浪子不回头ぞ 提交于 2019-12-26 04:21:48

问题


I am new to java, writing a program just for fun. The purpose of the program is to take in an int via std store in the num [] then add 5 to it. Very simple, how ever I am having issues with my code. To clarify, I am having issues with the actual calculation, how to store the stdin in the int array, then pass it through an addNum method. Thank you. Here is my code:

class Array{
public static void main (String [] args) {
    System.out.println(" enter four digits between 0-100");
    Scanner cin = new Scanner(System.in);
    int n = cin.nextInt();

    int [] num = new int[4];
    int num1 = 0;

}
    public int addNum(int [] num, int num1){
        for( int i = 0; i < num1; i++) {
            num[i]+=5;

        }
        return num1;
            }

}

回答1:


As I understand you want to add 5 to every number from stdin. I have modified your code as follows:

public class Array {
 public static void main(String[] args) {
    System.out.println(" enter four digits between 0-100");
    Scanner cin = new Scanner(System.in);

    int n = 4;

    int[] num = new int[n];

    int i = 0;

    while(cin.hasNext() && i < n) {
        num[i] = cin.nextInt();
        i++;
    }

    int num1 = (new Array()).addNum(num, n);

    for(int j : num)
        System.out.println(j);



}

public int addNum(int[] num, int num1) {
    for (int i = 0; i < num1; i++) {
        num[i] += 5;
    }
    return num1;
}

}

You need to read every number from stdin as follows

while(cin.hasNext() && i < n) {
    num[i] = cin.nextInt();
    i++;
}

And after that if you want to run addNum method you need to create object of class Array (because your method isn't static and cannot be run directly from main method). Maybe it is better to use ArrayList to store numbers from stdin. ArrayList can be easily converted to an array by using someArrayList.toArray() method. I hope what I wrote will help you.



来源:https://stackoverflow.com/questions/35499733/adding-in-array-from-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!