2017-10-16 69 views
-2

两个空格分隔的值与每个项目的价格和数量相对应。输入是基于N(行项目计数)设置为字符串字符串拆分并分配给Java中的数组

120.98 7

151.99 8

141.39 4

137.71 7

121.27 6

187.29 11

如何在数组中存储pric e和数量分开打印。

+1

你有什么这么远吗? – wumpz

+0

看起来像一个功课 –

回答

0

可以使用的StringTokenizer的令牌

Scanner sc=new Scanner(System.in); 
String input=sc.nextLine(); 
StringTokenizer st=new StringTokenizer(input); 
double price=Double.parseDouble(st.nextToken()); 
int qty=Integer.parseInt(st.nextToken()); 

分开,现在你可以存储阵列priceqty

0

您可以使用split()方法splitUp该字符串。

public class MainClass{ 
    public static void main(String args[]) { 
     List<Double> priceList = new ArrayList<>(); 
     List<Integer> qtyList = new ArrayList<>(); 
     Scanner sc=new Scanner(System.in); 
     String input=sc.nextLine(); 
     if(input != null) { 
      String[] arr = input.split(" "); 
      priceList.add(Double.parseDouble(arr[0])); 
      qtyList.add(Integer.parseInt(arr[1])); 
     } 
    } 
} 
0

存储和打印的简单方法如下。

只需创建两个字符串数组。一个用于存储价格,另一个用于存储数量。读取用户输入的每一行后,使用split函数分割字符串。完整的代码如下:

import java.io.DataInputStream; 
import java.util.ArrayList; 


public class TestArr { 
public static void main(String args[]) throws Exception 
{ 
DataInputStream din = new DataInputStream(System.in); 
int N=0; 
String price[] = new String[100]; 
String quantity[] = new String[100]; 
//To get the value for N 
N = Integer.parseInt(din.readLine()); 

//To get each line item and store the values 
for(int i=0;i<N;i++) 
{ 
    String str = din.readLine(); 
    price[i] = str.split(" ")[0]; 
    quantity[i] = str.split(" ")[1]; 
} 

//To display the price and quantity 
for(int i=0;i<N;i++) 
System.out.println("Price: "+price[i]+" Quantity: "+quantity[i]); 

} 
} 

专业方法如下。

为具有两个变量的项目创建一个类。一个用于存储价格,另一个用于存储数量。并在ArrayList中使用该Item类。完整的代码如下:

import java.io.DataInputStream; 
import java.util.ArrayList; 

//Item class for storing each item 
class Item 
{ 
float price; 
int quantity; 
public Item(float price, int quantity) 
{ 
    this.price = price; 
    this.quantity = quantity; 
} 
} 

//Main Class 
public class TestArr { 
public static void main(String args[]) throws Exception 
{ 
//Input stream to read inputs from user 
DataInputStream din = new DataInputStream(System.in); 

//To store count of line items 
int N=0; 
//Arraylist to store each of the line items 
ArrayList<Item> arr = new ArrayList<Item>(); 
System.out.println("Enter count of Line Items:"); 
N = Integer.parseInt(din.readLine()); 
for(int i=0;i<N;i++) 
{ 
    String st = din.readLine(); 
    Item item = new Item(Float.parseFloat(st.split(" ")[0]),     
Integer.parseInt(st.split(" ")[1])); 
} 
//To print the line items 
for(Item item : arr) 
{ 
    System.out.println("Price: "+item.price+" Quantity: "+item.quantity); 
} 

} 
} 
相关问题