2016-09-16 4 views
-1

아주 제한된 지식으로 Java를 사용하여 매우 간단한 콘솔 계산기를 만들었습니다.프로그램 실행 중에 NullPointerException이 throw 됨 Java

프로그램은 두 개의 숫자로만 기본 수학 함수 (+, -, *, /)를 수행해야합니다. 프로그램에서 처음에 두 개의 String 값을 묻습니다. 즉 inpmodeoutmode입니다. inpmode은 사용자가 두 개의 숫자를 입력하는 모드입니다 (두 개의 모드는 10 진수 입력의 경우 "dec"이고 2 진 입력의 경우 "bin"입니다). outmode은 사용자가 결과를 표시하고자하는 모드입니다.이 정보 (inpmodeoutmode)는 텍스트 파일에 쓰여지고 어딘가에 저장되면 프로그램은 값을 묻고 그에 따라 결과를 표시합니다. 결과를 표시 한 후 사용자는 끝내려면, 같은 모드로 계속 작업하려면, 모드를 변경하려면 세 가지 옵션이 있습니다. 그리고 이것은 사용자가 종료하기를 선택할 때까지 계속됩니다.

Here's a simple flowchart I made for the purpose.

여기 불쌍한 내 코드입니다 : 내가 처음 실행 후 모드를 변경하기로 결정했습니다 때 예외가 발생됩니다

import java.io.*; 
import java.util.*; 

class FileTry { 
    Scanner sc=new Scanner(System.in); 
    String inpmode=""; 
    String outmode=""; 
    FileWriter fw; 
    BufferedWriter bw; 
    PrintWriter pw; 
    String n1,n2; 
    FileReader fr; 
    BufferedReader br; 
    String read; 
    String arr[]=new String[2]; 
    int nu2,res,i=0; 
    String op; int nu1=nu2=res=0; 


    void main(){ 
     try { 
      fr=new FileReader("C:\\Users\\dell pc\\Desktop\\tryer.txt"); 
      askdata(); 

     } 

     catch (IOException e) { 
      try 
      { 
       System.out.println("File needs to be created first"); 
       fw=new FileWriter("C:\\Users\\dell pc\\Desktop\\tryer.txt"); 
       bw=new BufferedWriter(fw); 
       pw=new PrintWriter(bw); 
       askuser(); 
      } 
      catch(IOException a){ 
       System.out.println("Error"); 
      } 
     } 

    } 

    void askuser() 
    { 

     System.out.println("Input mode?"); 
     inpmode=sc.nextLine(); 
     System.out.println("Output mode?"); 
     outmode=sc.nextLine(); 
     modewriter(); 
    } 

    void modewriter() 
    { 

     try 
     { 
      pw.println(inpmode); 
      pw.println(outmode); 
      pw.close(); 
      bw.close(); 
      fw.close(); 
     } 

     catch(IOException b) 
     { 
      System.out.println("error"); 

     } 
     askdata(); 
    } 

    void askdata() 
    { 

     System.out.println("Enter num 1"); 
     n1=sc.nextLine(); 
     System.out.println("Enter num 2"); 
     n2=sc.nextLine(); 
     System.out.println("Enter the operation"); 
     op=sc.nextLine(); 
     reader(); 
    } 

    void reader() 
    { 

     int i=0; 
     try 
     { 
      Scanner fileScanner=new Scanner(new File("C:\\Users\\dell pc\\Desktop\\tryer.txt")); 
      while (fileScanner.hasNextLine()){ 
       arr[i]=fileScanner.nextLine(); 
       i++; 
      } 

     } 

     catch (IOException x) 
     { 
      System.out.println("errer"); 
     } 

     caller(); 
    } 

    void caller(){ 

     if (arr[0].equals("bin")&&arr[1].equals("bin")) 
     { 
      todec(); 
      operate(); 
      tobin(); 
      print(); 
     } 

     else if(arr[0].equals("bin")&&arr[1].equals("dec")) 
     { 
      todec(); 
      operate(); 
      print(); 
     } 

     else if(arr[0].equals("dec")&&arr[1].equals("dec")) 
     { 
      nu1=Integer.parseInt(n1); 
      nu2=Integer.parseInt(n2); 
      operate(); 
      print(); 
     } 
     else if(arr[0].equals("dec")&&arr[1].equals("bin")) 
     { 
      nu1=Integer.parseInt(n1); 
      nu2=Integer.parseInt(n2); 
      operate(); 
      tobin(); 
      print(); 
     } 
     else System.out.println("kk"); 
    } 

    void todec() 
    { 

     int decimal = 0; 
     int power = 0; 
     int binary=Integer.parseInt(n1); 
     while(true){ 
      if(binary == 0){ 
       break; 
      } else { 
       int tmp = binary%10; 
       decimal += tmp*Math.pow(2, power); 
       binary = binary/10; 
       power++; 
      } 
     } 
     nu1=decimal; 
     decimal = 0; 
     power = 0; 
     binary=Integer.parseInt(n2); 
     while(true){ 
      if(binary == 0){ 
       break; 
      } else { 
       int tmp = binary%10; 
       decimal += tmp*Math.pow(2, power); 
       binary = binary/10; 
       power++; 
      } 
     } 
     nu2=decimal; 


     System.out.println(nu1+" "+nu2); 
    } 

    void operate() 
    { 

     switch(op.charAt(0)) 
     { 
     case '+' : 
     { res=nu1+nu2; 
     break;} 
     case '-': 
     { res=nu1-nu2; 
     break;} 
     case '/': 
     { res=nu1/nu2; 
     break;} 
     case '*': 
     { res=nu1*nu2; 
     break;} 
     default: 
      System.out.println("Errorr"); 
     } 
    } 

    void tobin() 
    { 

     String temp=""; 
     i=res; 
     while(i>0) 
     { 
      temp=(i%2)+temp; 
      i=i/2; 
     } 
     temp=i+temp; 
     res=Integer.parseInt(temp); 
    } 

    void print() 
    { 

     System.out.println(res); 
     System.out.println("n for another operation"); 
     System.out.println("m to change the modes"); 
     System.out.println("e to exit"); 
     char c=sc.nextLine().charAt(0); 
     switch (c) 
     { 
     case 'n' : 
     { 
      askdata(); 
      break; 
     } 

     case 'm' : 
     { 
      askuser(); 
      break; 
     } 

     case 'e' : 
     { 
      System.out.println("Bye"); 
      break; 
     } 

     default: System.out.println("errreeer"); 
     } 

    } 
} 

, 그래서 누군가가 나에게이 문제를 해결 도와주세요 수 있습니까?

편집 : 내 질문에 대한 것이 this one.의 복제본 인 것을 봅니다. 어떻게 보이지 않습니다. 그 질문이 단지 내가 얻고있는 오류를 설명하는 동안 나는 프로그램 사이에 끼어있다. 내 코드를 작동 시키려면 해결책이나 가능한 제안이 필요하다.

+5

[NullPointerException이란 무엇이며 어떻게 수정합니까?] (http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix -it) –

+0

정확한 오류 메시지는 무엇입니까? 스택 추적이 필요합니다. – marstran

+0

[여기 있네요] (https://s6.postimg.org/644j4z8cx/Untitled.png) @marstran – JavaPilgrim

답변

1

pw이 초기화되지 않았기 때문에 askuser 메서드 내부의 줄 58에서 오류가 발생합니다.

main 메서드에서 IOException이 발생하는 경우에만 pw을 초기화합니다. 그러나 예외가 발생하지 않는 경우 메서드를 통해 askuser 메서드를 사용할 수 있습니다. 이 시점에서 pw은 초기화되지 않았으므로 NullPointerException이 발생합니다.

는, 그것을 해결 또한 main 방법의 오류가 아닌 경우 pwbw를 초기화합니다.

-1

시도해 보았습니까?

try { /* code part that throws exception */ } catch (NullPointerException e) { e.printStackTrace();} 

StackTrace는 Null 값을 가리키는 (참조) 위치와 이유에 대한 매우 중요한 정보를 제공합니다.

+0

찾아 주셔서 감사합니다. 위의 try-catch를 추가했지만 porgram이 지금 컴파일되지 않습니다. "void 형식이 여기에 허용되지 않습니다."라고 말하는 오류가 발생합니다. – JavaPilgrim

+0

void main 앞에 "static"이 없습니다. 하나의 주요 기능은 자바 프로그램에서 허용됩니다. 'public static void main (String [] args) {'필요한 헤더입니다. – Gewure

0

fw=new FileWriter("lol.txt"); bw=new BufferedWriter(fw) pw=new PrintWriter(bw);

당신은 시도 - catch 문이 점을 넣었습니다. 즉, 오류가 발생하지 않으면 PrintWriter pw가 초기화되지 않습니다. 나중에 pw.println(inpmode);을 호출했습니다. pw가 초기화되지 않았기 때문에 nullpointerexception이 발생합니다.

관련 문제