2013-11-04 4 views
-2

내가 잘못하고있는 것을 이해하는 사람이 누구인지 궁금합니다. 저는 Java에서 OutputStreams 및 BufferedWriters를 사용하는 방법을 배우는 중입니다. 제대로 수행하고 있는지 잘 모르겠습니다. 한 OutputStream 및 BufferedWriter 사용하는 방법을 알고 있지만 내 문제는 한 클래스에서 두 사용하려고합니다.Java에서 두 개의 OutputStreams 및 BufferedWriter 사용

지금 당장 발생하는 주요 오류는 LowerAndUpper 클래스에 있으며 try/catch 문과 if/else 문 사이에 있으며 내가 잘못하고있는 것이 확실하지 않습니다. 따라서 여러분이이 문제에 관해 도움을 줄 수있는 도움을 주시고,이 두 가지 항목을 한 번에 사용하는 방법을 이해하도록 도와 주시면 감사하겠습니다.

내가지고있어 오류이며, 나는 일반적으로 자바 여전히 초보자이야 이후 정확히 여기 무슨 일이 일어나고 있는지 이해가 안 :

라인 40 오류 : ')'(경우 예상 creditsEarned> 60 writerUpper.write) {

라인 에러 40 :하지 문 경우 (creditsEarned> 60 writerUpper.write) {

라인 에러 40 ';' 예상 경우 (creditsEarned> 60 writerUpper.write) {

라인 43 오류 : '다른'다른 (writerLower.write) {

라인 (43) 오류 '의 경우'없이 : 아니 성명 다른 을 (writerLower .write) {

라인 43 오류 : ';' 모든 도움에 미리

import java.nio.file.*; 
import java.io.*; 
import static java.nio.file.StandardOpenOption.*; 
import java.nio.file.attribute.BasicFileAttributes; 
import java.nio.file.attribute.FileTime; 
import java.util.InputMismatchException; 
import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class LowerAndUpper { 


public static void main(String[] args) { 
    Path file1 = 
      Paths.get("C:/temp/lowerclassman.txt"); 
    Path file2 = 
      Paths.get("C:/temp/upperclassman.txt"); 
    String s = ""; 
    String delimiter = ","; 
    int id; 
    String name; 
    double creditsEarned; 
    final int QUIT = 999; 
    try { 
     OutputStream output = new BufferedOutputStream(Files.newOutputStream(file1)); 
     BufferedWriter writerUpper = new BufferedWriter(new OutputStreamWriter(output)); 
     OutputStream output2 = new BufferedOutputStream(Files.newOutputStream(file2)); 
     BufferedWriter writerLower = new BufferedWriter(new OutputStreamWriter(output2)); 
     while (true) { 
      id = Validate.collectInt("Enter student ID number or " + QUIT 
        + " to quit >> "); 
      if (id == QUIT) { 
       break; 
      } 
      name = Validate.collectString(2, "Enter student name " 
        + id + " >> "); 
      creditsEarned = Validate.collectWage("Enter credit hours >> "); 
      s = id + delimiter + name + delimiter + creditsEarned; 
      if (creditsEarned>60 writerUpper.write){ 
       System.out.println("Student is a Lowerclassman"); 

      else (writerLower.write){ 
System.out.println("Student is an Upperclassman"); 
} 
     } 
      writerUpper.write(s, 0, s.length()); 
      r.newLine(); 

     } //end while 


     writer.close(); 
     writer2.close(); 
    } catch (Exception e) { 
     System.out.println("Message: " + e); 
    } 

} 
} 


// ************************************************************************** 

class Validate { 

public static int collectInt(String messageIn) { 
    Scanner input = new Scanner(System.in); 
    int intOut = 0; 
    boolean valid = true; 

    System.out.println(messageIn); 
    while (valid) { 
     try { 
      intOut = input.nextInt(); 
      valid = false; 
     } catch (InputMismatchException ie) { 
      input.nextLine(); 
      System.out.println("You must enter a whole number"); 
     } //end catch 
    } //end while 

    return intOut; 

}//end collectInt method 

//************************************************************************* 
public static String collectString(int strLen, String messageIn) { 
    Scanner input = new Scanner(System.in); 
    String strOut = ""; 
    boolean valid = true; 

    System.out.println(messageIn); 
    while (valid) { 
     try { 
      strOut = input.nextLine(); 
      if (strOut.length() < strLen) { 
       throw new Exception(); 
      } 
      valid = false; 
     } catch (Exception e) { 
      System.out.printf("You must be at least %s characters\n", 
        strLen); 
     } //end catch 
    } //end while 

    return strOut; 
} //end collectString method 

//************************************************************************* 
public static String collectZipcode(String messageIn) { 
    Scanner input = new Scanner(System.in); 
    String strOut = ""; 
    boolean valid = true; 

    System.out.println(messageIn); 
    while (valid) { 
     try { 
      strOut = input.nextLine(); 
      Integer.parseInt(strOut); 
      if (strOut.length() != 5) { 
       throw new Exception(); 
      } 
      valid = false; 
     } catch (NumberFormatException ne) { 
      System.out.println("Please enter a valid zip code"); 
     } catch (Exception e) { 

      System.out.printf("A zip code should be 5 numbers long"); 
     } //end catch 
    } //end while 

    return strOut; 
}//end collectZipcode method 

//************************************************************************* 
public static String collectEmail(String messageIn) { 
    String expression = "^[\\w\\.-][email protected]([\\w\\-]+\\.)+[A-Z]{2,4}$"; 
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); 

    Scanner input = new Scanner(System.in); 
    String strOut = ""; 
    boolean valid = true; 

    System.out.println(messageIn); 
    while (valid) { 
     try { 
      strOut = input.nextLine(); 
      CharSequence emailChk = strOut; 
      Matcher matcher = pattern.matcher(emailChk); 
      if (!matcher.matches()) { 
       throw new Exception(); 
      } 
      valid = false; 
     } catch (Exception e) { 
      System.out.printf("Please try again with a valid email " 
        + "address\n"); 
     } //end catch 
    } //end while 

    return strOut; 

}//end collectEmail method 

//************************************************************************* 
public static Double collectWage(String messageIn) { 

    Scanner input = new Scanner(System.in); 
    double dblOut = 0; 
    boolean valid = true; 

    System.out.println(messageIn); 
    while (valid) { 
     try { 
      dblOut = input.nextDouble(); 
      valid = false; 
     } catch (InputMismatchException ie) { 
      input.nextLine(); 
      System.out.println("You must enter a whole number "); 
     } //end catch 
    } //end while 

    return dblOut; 

}//end collectInt method 

//************************************************************************* 
public static String collectPhone(String messageIn) { 
    String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$"; 
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); 

    Scanner input = new Scanner(System.in); 
    String strOut = ""; 
    boolean valid = true; 

    System.out.println(messageIn); 
    while (valid) { 
     try { 
      strOut = input.nextLine(); 
      CharSequence phoneChk = strOut; 
      Matcher matcher = pattern.matcher(phoneChk); 
      if (!matcher.matches()) { 
       throw new Exception(); 
      } 
      valid = false; 
     } catch (Exception e) { 
      System.out.printf("Please try again with a valid phone " 
        + "number\n"); 
     } //end catch 
    } //end while 

    return strOut; 

}//end collectPhone method 

//************************************************************************* 
public static String collectSsn(String messageIn) { 
    String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$"; 
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); 

    Scanner input = new Scanner(System.in); 
    String strOut = ""; 
    boolean valid = true; 

    System.out.println(messageIn); 
    while (valid) { 
     try { 
      strOut = input.nextLine(); 
      CharSequence ssnChk = strOut; 
      Matcher matcher = pattern.matcher(ssnChk); 
      if (!matcher.matches()) { 
       throw new Exception(); 
      } 
      valid = false; 
     } catch (Exception e) { 
      System.out.printf("Please try again with a valid social security " 
        + "number\n"); 
     } //end catch 
    } //end while 

    return strOut; 

}//end collectSsn 
} //end Validate Class 

감사 : 다른 (writerLower.write) {

을 기대하는 것은 여기 내 코드입니다.

BufferedWriter writerUpper = new BufferedWriter(new OutputStreamWriter(output)); 

을하지만 다른 두 varible 이름 사용 :

+0

스택 트레이스.(오류 메시지 표시) –

+1

다양한 소스의 코드를 복사하여 붙여 넣은 것처럼 보이며 작동하는 것으로 가정합니다. 이 코드를 읽을 수없는 임의의 변수 이름이 많이 있습니다. – frogmanx

+0

실제로 클래스의 경우 이전 할당에서 이전 코드 (예 : 변수 클래스)의 이전 코드를 사용하기를 원했습니다. 내가 아는 부분은 내가 필요한 것을 위해 일합니다. 내가 겪고있는 주된 문제는 스트림이있는 실제 UpperAndLower 클래스에 있습니다. – user2926750

답변

0

첫째, 당신은 초기화 한

writer.close(); 

과 :

r.newLine(); 
의 BufferedWriter의 올바른 사용이에서 찾을 수 있습니다

문서 : http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html

if 및 else 문에 대해서는 코드의 형식을 올바르게 지정해야합니다. if 문의 일반 사용이 조건을 가지고있다 :

if(condition) 
{ 
    //do something 
} 
else 
{ 
    //do something else 
} 

즉 귀하의 상황에 대해 : 당신은 같은 변수를 사용하여 확인 후

if (creditsEarned> 60){ 
    writerUpper.write(s, 0, s.length()); 
    writerUpper.newLine(); 
} 
else 
{ 
    writerLower.write(s, 0, s.length()); 
    writerLower.newLine(); 
} 

그리고 :

if (creditsEarned>60 writerUpper.write){ 
      System.out.println("Student is a Lowerclassman"); 

     else (writerLower.write){ 
System.out.println("Student is an Upperclassman"); 
} 
} 

는이어야한다 처음 초기화 할 때 사용한 이름 :

writerLower.close(); 
writerUppder.close(); 
+0

Frogmanx 대단히 고맙습니다. 매우 도움이되었습니다. 불행히도 내가 사용하고있는 클래스의 책은 일반적인 코드를 제공하고 명확하게 설명하지 않기 때문에 일이 어떻게 수행되는지에 대해서는 분명하지 않습니다. 그래서 고맙습니다. – user2926750

+0

그래, 코드를 단계별로 실행하고 각 행이 무엇을하고 있는지 알아 내려고한다. 연습이 필요하지만 코드를 많이 작성할수록 더 능숙 해집니다. – frogmanx

관련 문제