-1

Java Shopping Cart App을 만들었습니다. 나는 그것을 위해 InputStreamReader 클래스를 사용했다. 그러나 그 이상한 행동을 보여줍니다. 이미 스캐너 클래스와 데이터 입력 스트림 클래스를 사용해 보았습니다. 하지만 그들은이 응용 프로그램에 적합하지 않은 것 같습니다.여기에 InputStreamReader에 문제가 있습니까?

누구나이 수업에서 잘못된 점을 지적 해주세요.

또한 이미 설명한 바와 같이 스캐너 클래스와 DIS 클래스는 ISR 클래스를 사용하는 동안 여기에서와 마찬가지로 사용자 입력을 건너 뛸 수 있습니다 (출력 : 비율 참조). 나는 모든 Java 사용자 입력 유틸리티 클래스를 시도하고 코드를 몇 번이고 수정하는 것에 지쳐있다.

import java.util.ArrayList; 
//import java.util.InputMismatchException; 
import java.util.Iterator; 
import java.util.Scanner; 
import java.io.DataInputStream; 
import java.io.InputStreamReader; 
import java.io.IOException; 
import java.lang.Throwable; 


public class NewShop { 


protected ArrayList<NewItem> ItemList; 
ArrayList<NewItem> cartList ; 

    // public DataInputStream dis = new DataInputStream(System.in); 
    // private Scanner sc = new Scanner(System.in); 
    private InputStreamReader isr = new InputStreamReader(System.in); 

public void addItem() { 

    long aCode = 0; 
    String aName =""; 
    double aRate = 0; 
    int aQuantity = 0; 
    NewItem foundItem; 

    System.out.println("Enter Item code:"); 
    /* try{ 
    String adddisString = dis.readLine();} 
     catch(IOException e){e.printStackTrace();} */ 

    try{ 
    aCode = isr.read(); 
     System.out.println("code entered is : " + aCode); 
     } 
     catch(IOException e){e.printStackTrace();} 

    foundItem = search(aCode); 
    if (foundItem == null) { 
     System.out.println("Item name : "); 
     try{ 
     aName = dis.readLine(); 
      } 
      catch(IOException e){e.printStackTrace();} 
     System.out.println("Rate : "); 
     try{ aRate = isr.read(); } 
      catch(IOException e){e.printStackTrace();} 

     System.out.println("Quantity : "); 
     try{aQuantity = isr.read();} 
     catch(IOException e){e.printStackTrace();} 


        NewItem aItem = new NewItem(aName, aRate, aCode, aQuantity); 
        ItemList.add(aItem); 
        } 
        else { 
        System.out.println("Item exists"); 
        } 


    } 

} 

출력 :

[email protected]:~/NewJava$ java NewShoppingCart 
    New Shop for Items created. 
    -----ITEM------ 
1. Display all items 
2. Search items 
3. Add items to list 
4. Add items to cart 
5. Issue item 
6. Exit 
Choice: 
3 
Enter Item code: 
1 
code entered is : 49 
Item name : 
apple 
Rate : 
Quantity : 
30 
1. Display all items 
2. Search items 
3. Add items to list 
4. Add items to cart 
5. Issue item 
6. Exit 
Choice: 
1 
     code   name   rate   quantity 

     49   apple   10.0   51 

           ************ 
1. Display all items 
2. Search items 
3. Add items to list 
4. Add items to cart 
5. Issue item 
6. Exit 
Choice: 
+0

예상되는 결과는 무엇입니까? – procrastinator

+0

코드를 조금씩 작성하여 [mcve]를 제공해 주시겠습니까? (일부 데이터 포함) – AxelH

+0

"출력"섹션을 참조하십시오. 나는 예상되는 결과가 확실하다고 생각한다. –

답변

2

InputStreamReaderint을주는 read을 사용하여 문자 당 스트림 문자를 읽을 수 있습니다. int

은 당신이 아마 여기에 사용하려는 어떤이 ASCII table

에서

'0' = 48 
'1' = 49 
... 

더는 Scanner 그래서, 다수의 char 표현, 가치 당신의 생각되지 않습니다 이는 귀하의 경우에 더 간단하거나 String에 전체 라인을 얻을 수있는 가능성을 제공하는 BufferedReader입니다.

Scanner sc = new Scanner(System.in); 
int i = sc.nextInt(); //This will get the next number an parse it in an integer (or throw an exception) 
//careful, the <ENTER> is still in the buffer, flush with sc.nextLine(); if needed 
sc.close(); 

일부 입력이 Scanner 위이다 사용을 건너 뛰었있어 이유, 특정 유형을 읽을 때 버퍼에 남아 있도록 (readInt를 같은)에는 키가 읽을 수 없습니다되는의 다음 전화를 "입력" nextLine을 읽습니다. 올바른 값을 얻기 전에 해당 입력을 제거해야합니다. 당신이 Reader의를 사용하는 경우

int i = sc.nextInt(); 
sc.nextLine(); //clear <enter> 
String s = sc.nextLine(); //next input 
+0

'Reader'는 "byte per byte"가 아니라 "char by char"를 읽습니다. ... –

+0

@UsagiMiyamoto 실제로 문자는 1 바이트 이상일 수 있습니다. 감사. Corrected – AxelH

+0

도움이 많이 필요함. 감사! 하지만 사용자 입력을 요구하지 않더라도 '10 .0 '값을'평가 '에 할당하는 위치를 알려주시겠습니까? –

-1

당신은 수행

당신에게 지능 값을 반환
aCode = isr.read(); 

당신은 넣어 첫 번째 문자의 (Ascii-Table 참조) 을 따라서 "1. "라고 입력하면 Ascii 코드"1 "이 나오며 49가됩니다.

If

InputStreamReader isr = new InputStreamReader(System.in) 
int c; 
String input = ""; 
while((c = isr.read()) != -1){ 
     input+= (char) c; 
} 

그러나 당신은 당신이 물건을 이런 종류의 스캐너를 사용하는 경우 더 쉽게 결과를 얻을 이에 대한 @AxelH 답변을 볼 것입니다 : 당신은 문자열이 InputStreamReader로는 다음과 같이 수행 할 수 있습니다 읽고 싶어.

+0

약'input : 30'? – AxelH

+0

첫 번째 문자가 "3"의 경우 "51"인 Int로 반환됩니다. – TheRealHypo

+0

그게 문제입니다 ...;) – AxelH

1

당신은 어떤 문자열이 아닌 자신의 가치를 변환해야합니다. DataInput은 사용자 입력에 적합하지 않은 이진 형식을 사용합니다.

따라서 당신의 가장 쉬운 해결책은 Scanner, 그래서 이런 식으로 뭔가를 시도 할 것입니다 : 어떤 값이 잘못된 경우, 나중에 작동하지 않을로

public class NewShop 
{ 
    protected ArrayList<NewItem> ItemList; 
    ArrayList<NewItem> cartList ; 
    private Scanner in = new Scanner(System.in); 
    public void addItem() 
    { 
    long aCode = 0; 
    String aName =""; 
    double aRate = 0; 
    int aQuantity = 0; 
    NewItem foundItem; 
    System.out.println("Enter Item code:"); 
    try 
    { 
     aCode = in.nextLong(); // this reads the to the first char that is not part of the 
     in.nextLine();   // long value, so we need to read till the end of the line... 
     System.out.println("code entered is : " + aCode); 
     foundItem = search(aCode); 
     if (foundItem == null) 
     { 
     System.out.println("Item name : "); 
     aName = in.nextLine(); 
     System.out.println("Rate : "); 
     aRate = in.nextDouble(); 
     in.nextLine(); 
     System.out.println("Quantity : "); 
     aQuantity = in.nextInt(); 
     in.nextLine(); 
     NewItem aItem = new NewItem(aName, aRate, aCode, aQuantity); 
     ItemList.add(aItem); 
     } 
     else 
     { 
     System.out.println("Item exists"); 
     } 
    } 
    catch(IOException e) 
    { 
     e.printStackTrace(); 
    } 
    } 
} 

는 또한 내부 try-catch ES를 제거 ...

+0

아, 처음에는 코멘트가 없습니까? –

+0

글쎄, "라인의 끝"은 "다음 라인의 시작"이되어야합니다 ... –

+0

코멘트 :) 나는 전체 코드를 읽을 수 없으므로 (특히 큰 코드가있는) 그것을 볼 수는 없지만 나는 이것이 초보자에게 충분할 것이라고 생각한다. – AxelH

관련 문제