2014-09-18 4 views
1

배열을 저장하는 방법과 위치에 문제가 있습니다. 배열을 저장하는 방법과 위치를 배열 안에 저장하는 여러 사용자 데이터를 수집 할 수 있도록 루프를 배치하는 방법을 알았지 만 배열을 어디에 둘 것인지 알지 못합니다. 제품 번호에 대한 배열, 제품 이름에 대한 배열 및 가격에 대한 배열이 있습니다. 당신이 선험적에게 그들을 위해 길이를 알 수 없기 때문에배열에서 데이터 입력 저장/표시

import java.io.*; 
public class DataInsideArrays 
{ 
public static DataInputStream a = new  DataInputStream(System.in) 
public static void main(String  args[])throws Exception 
{ 
int y = 0; 
for(int x=1;x<=100;x++) 
{       
System.out.println("1 - Maintenance"); 
System.out.println("2 - Transaction"); 
System.out.println(""); 
System.out.print("Enter code: "); 
int code = 
Integer.parseInt(a.readLine()); 
System.out.println(""); 
if(code==l) 
{ 
System.out.print("") ; 
System.out.print("Product number: "); 
System.out.print("Product name: "); 
String prodname = a.readLine(); 
System.out.print("Price: "); 
int price = Integer.parseInt(a.readLine()); 
System.out.println(""); 
} 
else if(code==2) 
{ 
System.out.println("Display List of   Products-Prices") 
System.out.print("Enter product number: 
") ; 
int prodnum 
Integer.parseInt(a.readLine()); 
System.out.println("") 
} 
if(code==3) 
{ 
System.out.println("Invalid");   
System.out.println("Restart"); 
System.out.println(""); 
}}}} 
+0

적절한/관련있는 질문에 태그를 답니다. 자바 질문처럼 보이지만 자바 스크립트에 태그를 추가했습니다. –

+0

@ManjunathDR 죄송합니다. 바로 바 꾸었습니다. 감사. –

+0

코드를 OCR하셨습니까? 구문 오류가 많습니다. – Narmer

답변

0

첫째 : 일반적인 관행은 switch 문으로 목록을 사용할 수 있나요? 이것은 1 (number one)이 아니어야합니까? 또한 0 (zero)이라면 어레이의 색인으로 사용할 수 있으므로 더 좋을 것입니다.

두 번째 것은 무엇입니까? int y = 0'?y은 프로그램의 어느 곳에서나 사용하지 않습니다. 이에

int y = 0; 
for(int x = l; x <= 100; x++) 

변경 :

for(int x = 0; x < 100; x++) 

당신은 3 개 별도의 배열을 갖고 싶어하기 때문에

, 당신은 3 개 별도의 인덱스를 가지고 있어야 그들을 추적 할 수 있습니다.

이제 데이터를 저장할 어레이를 초기화하는 방법을 살펴 보겠습니다. 크기를 클래스 상단 (또는 main())의 변수로 선언해야 나중에 프로그램에서 쉽게 변경할 수 있습니다. 배열에서도 동일한 작업을 수행 할 수 있습니다. 수업 시간 내에 또는 로컬로 main() 안에 신고하십시오. 수업 외 두 가지 방법을 모두 선포하는 방법을 보여 드리지만 연습을 위해 다른 방법으로 시도해야합니다.

배열을 사용할 때 배열을 만들 자마자 미리 배열의 크기를 알아야하며 그 이후에는 크기를 변경할 수 없습니다. 이것은 많은 요소가 배열 안에 들어갈 수 있음을 의미합니다. 가변 크기 구조가 필요하다면 ArrayList으로 응답을 확인하십시오. 당신이 이것을 달성 할 수

public class DataInsideArrays 
{ 
    public static DataInputStream a = new DataInputStream(System.in) 
    public static int size = 100; // now you only change this number and everything works 
    public static int[] productNumbers = new int[size]; 
    public static String[] productNames = new String[size]; 
    public static int[] productPrices = new int[size]; 

    public static void main(String args[]) throws Exception 
    { 

     int prodnumIndex = 0; // index for tracking product numbers 
     int prodnameIndex = 0; // index for tracking product names 
     int prodpriceIndex = 0; // index for tracking product prices 
     for(int x = 0; x < size; x++) 
     {   
     // ... your code... 

     // ... 

     int prodNum = Integer.parseInt(a.readLine()); 
     // check if we didn't reach our maximum size 
     if(prodnumIndex < productNumbers.length) { 
      productNumbers [prodnumIndex] = prodnum; 
      prodnumIndex++; // increment 
     } else { 
      System.out.println("Cannot add product number. Reached maximum amount."); 
     } 


     // ... 

     String prodName = a.readLine(); 
     // check if we didn't reach our maximum size 
     if(prodnameIndex < productNames.length) { 
      productNames [prodnameIndex] = prodName ; 
      prodnameIndex++; // increment 
     } else { 
      System.out.println("Cannot add product name. Reached maximum amount."); 
     } 

     // ... 

     int prodPrice = Integer.parseInt(a.readLine()); 
     // check if we didn't reach our maximum size 
     if(prodpriceIndex < productPrices.length) { 
      productPrices [prodpriceIndex] = prodPrice ; 
      prodpriceIndex++; // increment 
     } else { 
      System.out.println("Cannot add product number. Reached maximum amount."); 
     } 

     // ... 

     }    

또 다른 방법은 당신이 필요로하는 속성을 포함하고 해당 객체의 배열을해야합니다 Product라는 개체를 만드는 것입니다.

class Product { 
    int num; 
    String name; 
    int price; 
    Product(int num, String name, int price) { 
     this.num = num; 
     this.name = name; 
     this.price = price; 
    } 
} 

// ... 

// declare your array of `Product` objects... 
Product[] products = new Product[size]; 

// ... 

// then you can do something like 
System.out.println("Enter product number:"); 
int prodNum = Integer.parseInt(a.readLine()); 
System.out.println("Enter product name:"); 
String prodName = a.readLine(); 
System.out.println("Enter product price:"); 
int prodPrice = Integer.parseInt(a.readLine()); 

products[INDEX] = new Product(prodNum, prodName, prodPrice); 

// ... 

는 또한, 실제 제품의보다 현실적인 표현이기 때문에 제품 가격에 대한 double float (A)의 사용을 고려하십시오.

+0

죄송합니다. 소문자 l을 인식하지 못했습니다. 그것을 바꿔라. 그렇게 좋아하니? 제품 이름과 제품 가격에 2 개의 배열을 더 추가 할 것입니다. 다른 하나는 제품 번호입니다. –

+0

@Axiom_CC 내 편집을 체크 아웃 – nem035

+0

첫 번째 긴 트릭이 트릭을 할 수 있습니다. 나는 이것을 실행하고 아직 실종 된 것을 보게 될 것이다.감사! –

0
public class DataInsideArrays { 
    public static DataInputStream a = new DataInputStream(System.in); 
    List<String> productname=new ArrayList<String>(); 

    public static void main(String args[]) throws Exception { 
     // rest of your code... 
     if(code == 1) { 
      System.out.print("") ; 
      System.out.print("Product number: "); 
      System.out.print("Product name: "); 
      String prodname = a.readLine(); 
      System.out.print("Price: "); 
      int price = Integer.parseInt(a.readLine()); 
      System.out.println(""); 

    ////////////////////////to store data place arraylist here///////////////////////////// 
      productname.add(prod); 

    ///////////////////// //same way use arr to store price and product no 
     } else if(code == 2) { 
      System.out.println("Display List of Products-Prices") ; 
      System.out.print("Enter product number:") ; 
      int prodnum=Integer.parseInt(a.readLine()); 
      System.out.println(""); 
     } 
     if(code == 3) { 
      System.out.println("Invalid");   
      System.out.println("Restart"); 
      System.out.println(""); 
     } 
    } 
} 
+0

나머지 코드 상단에있을 필요는 없습니까? –

+0

상단의 유일한 배열 선언에 있고 내부에 선언 할 경우 – kirti

+0

'arrprodname [i] = prodname; '이라고하면 외부에서 액세스 할 수 없습니다. 배열을 초기화하지 않아 작동하지 않습니다. 또한 크기를 모르기 때문에 작업을 수행 할 수 없습니다. – Narmer

0

당신은 배열 대신 List를 사용해야합니다.

List을 사용하면 요소가 도착하자마자 dinamically 요소를 추가 할 수 있으므로 사용자 입력 아래에 "배열 배치"해야합니다.

List<String> names = new ArrayList<String>(); //<-- do the same for price(Integer) and product number (Integer) 
public static void main(String args[]) throws Exception) { 
//... 
    if(code==1) //<-- This was a l, check again your code. 
    { 
     System.out.print("") ; 
     System.out.print("Product number: "); 
     System.out.print("Product name: "); 
     String prodname = a.readLine(); 

     names.add(prodname); //<-- add value to ArrayList 

     System.out.print("Price: "); 
     int price = Integer.parselnt(a.readLine()); 
     System.out.println(""); 
    } 
//... 
} 

은 그냥 ArrayList를 반복하는 것을 필요로 배열 내용을 인쇄하려면 :

for(String prodname: names) 
    System.out.println(prodname); //<-- This will print all your product names 
+0

배열 대신 목록을 사용하면 내가 추가 한 데이터를 표시 할 수 있습니까? 사용자가 두 번째 코드를 선택했을 때 –

+0

내 편집을 참조하십시오. 목록을 반복하는 내용을 인쇄 할 수 있습니다. – Narmer

+0

네, 그렇지만 어떻게 하나의 데이터 만 표시 할 수 있습니까? 마찬가지로 "제품 번호 2"를 입력하면 두 번째 데이터 만 표시됩니다. –

0

당신이 배열과 문 "경우"를 사용해야합니까? 당신이 당신의 for 루프에서이 l (lowercase L) 값을 얻는 경우, 모든

int[] productArray = new int[100]; 
List<Integer> productList = new ArrayList<Integer>(); 
for(int x=1;x<=100;x++) { 
    switch (code){ 
    case 1: 
     productArray[x-1] = Integer.parseInt(a.readLine()); 
     productList.add(new Integer(a.readLine())); 
     break; 
    default: 
     System.out.println("Invalid") 
     break; 
    } 
} 
+0

그런데 나는 모른다. 스위치 사용 경험이 있지만 내 시나리오를 훨씬 더 복잡하게 만들지 않겠습니까? –

+0

@Axiom_CC'switch'를 사용하면 훨씬 쉽게 사용할 수 있습니다. 매번 많은 옵션을 가지고'if '문을 많이 쓰고 싶을 때 대신'switch'를 사용해야합니다. 코드를보다 명확하게 만들고 실행 속도가 빠릅니다. – nem035

+0

감사합니다. 코드를 변경하고 그것이 내 마음에있는 다른 것들과 함께 작동하는지 확인하겠습니다. –

0

다음은 올바른 출력을위한 코드입니다. 어쩌면 다른 코딩으로이 같은 출력을 얻을 수있는 다른 방법이 있습니까?

import java.io.*; 
import java.util.ArrayList; 
public class DataArrays 
{ 
    public static DataInputStream a = new DataInputStream(System.in); 
    public static void main(String args[])throws Exception 
    { 
     ArrayList<Integer> prodNum = new ArrayList<Integer>(100); 
     ArrayList<String> prodName = new ArrayList<String>(100); 
     ArrayList<Integer> prodPrice = new ArrayList<Integer>(100); 
     ArrayList<Integer> prodPay = new ArrayList<Integer>(100); 

     for(int x=1;x<=100;x++) 
     {  
      System.out.println("1 - Maintenance"); 
      System.out.println("2 - Transaction"); 
      System.out.println(""); 

      System.out.print("Enter code: "); 
      int code = Integer.parseInt(a.readLine()); 
      System.out.println(""); 

      int y = 1; 
      if(code==1) 
      { 
       System.out.print("") ; 
       System.out.println("Product number: "+ x); 
       prodNum.add(x);    //this brings 1st input to array element #0 which is not needed 
       prodNum.add(x); 
       System.out.print("Product name: "); 
       String prodname = a.readLine(); 
       prodName.add(prodname);  //this brings 1st input to array element #0 which is not needed 
       prodName.add(prodname); 
       System.out.print("Price: "); 
       int prodprice = Integer.parseInt(a.readLine()); 
       prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed 
       prodPrice.add(prodprice); 
       System.out.print("Payment: "); 
       int prodpay = Integer.parseInt(a.readLine()); 
       prodPay.add(prodpay);  //this brings 1st input to array element #0 which is not needed 
       prodPay.add(prodpay); 
       System.out.println(""); 
       System.out.println("Start New Transaction:"); 
       System.out.println(""); 
      } 
      else if(code==2) 
      { 
       System.out.println("Display List of Products-Prices"); 
       System.out.print("Enter product number: "); 
       int i = Integer.parseInt(a.readLine()); 
       i = prodNum.get(i);   //this gets the data stored in the arraylist. Assuming it starts with 1 and above 
       prodNum.set(1, i); 
       System.out.println(""); 

       System.out.println("Product name: "+ prodName.get(i)); 
       System.out.println("Product price: "+ prodPrice.get(i)); 
       System.out.println("Product payment: "+ prodPay.get(i)); 
       System.out.println(""); 
       System.out.println("Start New Transaction:"); 
      } 
      else if(code>=3) 
      { 
       System.out.println("Invalid");   
       System.out.println("Restart"); 
       System.out.println(""); 
      } 
      else if(code==0) 
      { 
       System.out.println("Program will end"); 
       break; 
     }}}} 

나를 도와 주셔서 감사합니다. 정말 고맙습니다.