Java Array从数组输入获取数字和编号

时间:2015-11-06 20:28:53

标签: java arrays indexoutofboundsexception digits

reset()

问题:用户将输入位数,程序将从中输入一个我自己编写代码的数字,但它似乎无法正常工作。

运行程序时:

  1. 输入似乎工作正常。我试图测试
  2. 的输出
  3. 没有第二个循环计算的数组,似乎工作 但随着计算似乎暗恋:

    import java.util.Scanner; public class Tar0 { static Scanner in = new Scanner (System.in); public static void main(String[] args) { int d, i = 0, a = 0, f = 1; System.out.println("Enter How many Digits you want?"); d = in.nextInt(); int num[] = new int[d]; for(i = 0; i < d; i++) { System.out.println("Enter Single Digit"); num[i] = in.nextInt(); } for(i = d; i > 0; i--) { a = a + (num[i] * f); f = f * 10; } System.out.println("The Number is: " + a); } }

  4. 这笔交易是什么?

2 个答案:

答案 0 :(得分:0)

Java数组从0开始并从那里继续。您的代码的格式化现在正在丢失一个值,因此您的数组太小而无法保存值。 如上所述的一个选项是递减d值,以便我们在循环中使用正确的数组大小。这将是首选方式,因此我删除了上面的其他代码以用于其他选项。

import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
    int d,i=0,a=0,f=1;
    System.out.println("Enter How many Digits you want?");
    d=in.nextInt();
    int num[] = new int[d];
    for(i=0;i<d;i++)
    {
        System.out.println("Enter Single Digit");
        num[i]=in.nextInt();
    }
    for(i =  d - 1; i >0 ; i--)
    {
        a=a+(num[i]*f);
        f=f*10;

    }
    System.out.println("The Number is: "+a);
 }

答案 1 :(得分:0)

如果您修改了以下代码,它将起作用。

//this is a wrapper function.  simply adds display none inline.  for ease of use
$("#div1").hide();
//prop is used to manipulate any property on the object.  hidden is a property.  so it doesn't stop you from doing it.
$("#div2").prop("hidden", true);
//css is a wrapper for the style attribute.  display is a valid css property so it won't stop it
$("#div3").css("display","none");
//this one seems odd.  i thought it would be hidden="hidden"  but anyway.  attr() is used to change the attributes on the markup.  hidden is a valid attribute so it doesn't stop you
$("#div4").attr("hidden", true);

数组索引值将从0开始。因此将数组从num [i]更改为num [i-1]