从标准输入中添加数组 [英] adding in array from stdin

查看:61
本文介绍了从标准输入中添加数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,只是为了娱乐而编写程序。该程序的目的是通过num []中的std存储区获取一个int,然后将其加5。很简单,我的代码遇到了什么问题。为了澄清,我在实际计算上有问题,如何将stdin存储在int数组中,然后将其通过addNum方法传递。谢谢。
这是我的代码:

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;
            }

}


推荐答案

据我了解,您希望将stdin的每个数字加5。
我修改了您的代码,如下所示:

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;
}

}

您需要按以下方式从stdin中读取每个数字

You need to read every number from stdin as follows

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

之后,如果要运行addNum方法,则需要创建对象类Array(因为您的方法不是静态的,并且不能直接从main方法运行)。也许最好使用ArrayList存储来自stdin的数字。可以使用someArrayList.toArray()方法将ArrayList轻松转换为数组。
希望我写的内容能对您有所帮助。

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.

这篇关于从标准输入中添加数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆