从扫描仪阵列写入的数据 [英] Written data from scanner to arrays

查看:133
本文介绍了从扫描仪阵列写入的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个购物清单的程序,输入名称和产品价格进入它们放入数组,然后打印的什么是错的这个code?

整个列表后,

 进口java.util.Scanner中;
进口java.util.Arrays中;公共类列表{
    公共静态无效的主要(字串[] args){
        扫描仪SC =新的扫描仪(System.in);
        的String [] NAME =新的String [4];
        双[]价格=新的双[4];        的for(int i = 0; I< name.length;我++){
            的System.out.println(名称);
            名称由[i] = sc.nextLine();            的System.out.println(价格);
            价格由[i] = sc.nextDouble();
        }
        的System.out.println(产品:+ Arrays.toString(名)+ Arrays.toString(价格));
    }
}


解决方案

您可以通过使用解决它 nextLine()而不是 nextDouble() 。但是,你需要将它解析为双作为你的价值声明为双:

 扫描仪SC =新的扫描仪(System.in);
的String [] NAME =新的String [4];
双[]价格=新的双[4];的for(int i = 0; I< name.length;我++){
    的System.out.println(名称);
    名称由[i] = sc.nextLine();
    的System.out.println(价格);
    价格由[i] = Double.parseDouble(sc.nextLine());
}
的System.out.println(产品:+ Arrays.toString(名)+ Arrays.toString(价格));

I would like to create a shopping list program, after entering the name and price of product enters them into the arrays and then print the entire list of what is wrong with this code?

import java.util.Scanner;
import java.util.Arrays;

public class List {
    public static void main (String[] args){
        Scanner sc = new Scanner(System.in);
        String [] name = new String[4];
        double [] price = new double[4];

        for (int i =0; i<name.length; i++) {
            System.out.println("name");
            name[i] = sc.nextLine();

            System.out.println("price");
            price[i] = sc.nextDouble();
        }
        System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price));
    }
}

解决方案

You can resolve it by using nextLine() instead of nextDouble(). However, you need to parse it to a double as your value declared as double :

Scanner sc = new Scanner(System.in);
String [] name = new String[4];
double [] price = new double[4];

for (int i =0; i<name.length; i++) {
    System.out.println("name");
    name[i] = sc.nextLine();
    System.out.println("price");
    price[i] = Double.parseDouble(sc.nextLine()) ;
}
System.out.println("your product: " +  Arrays.toString(name) + Arrays.toString(price));

这篇关于从扫描仪阵列写入的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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