-1

I've made a very simple console calculator using Java with my very limited knowledge.

The program has to perform basic math functions (+,-,*,/) on just two numbers. The program asks for two String values in the beginning, namely inpmode and outmode . The inpmode is the mode in which the user will enter his two numbers (the two modes are "dec" for decimal inputs and "bin" for binary inputs). outmode is the mode in which the user wants his result to be displayed in. This information, ( inpmode and outmode) is written to a text file and stored somewhere, the program then proceeds to ask for the values and display results accordingly. After displaying the results, the user has three options, To exit, To keep working with the same modes, To change the modes. And this goes on until the user chooses To exit.

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

Here's my poor code:

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"); 
        }

    }
}

The exception gets thrown when I chose to change the mode after the first run, so can someone please help me fix this?

Edit: I see the thing about my question being a duplicate of this one. I don't see how that is. I'm stuck in-between a program here while that question merely explains the error I'm getting. I need a solution or a possible suggest to make my code work.

Community
  • 1
  • 1
JavaPilgrim
  • 77
  • 1
  • 6
  • 5
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Fred Larson Sep 16 '16 at 14:16
  • What is the exact error message that is printed? We need the stack trace. – marstran Sep 16 '16 at 14:31
  • [Here's what it is](https://s6.postimg.org/644j4z8cx/Untitled.png) @marstran – JavaPilgrim Sep 16 '16 at 14:35
  • Ok, so that tells you exactly which line the error occurs. Line 58. That is this one: `pw.println(inpmode);`. Can you find out what may cause the error on this line? :) – marstran Sep 16 '16 at 14:38
  • The other question (of which this is a duplicate) explains why NullPointerException occurs, and how to discover exactly which piece of code is causing it. Read the accepted answer fully. – VGR Sep 16 '16 at 16:06

3 Answers3

1

The error happens at line 58 inside the askuser method, because pw hasn't been initialized.

You are initializing pw only if an IOException happens in the main method. However, if you do not get an exception, you may get to the askuser method through the print method anyway. At this point, pw is not initialized, which will cause the NullPointerException.

To fix it, initialize pw and bw also in the non-error case in your main method.

marstran
  • 26,413
  • 5
  • 61
  • 67
0

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

You've put this into a try-catch statement. Which means, unless you get an error, your PrintWriter pw doesn't get initialized. You later called pw.println(inpmode); Since pw is not initialized, you get a nullpointerexception.

Razin
  • 1
  • 2
-1

have you tried catching it?

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

The StackTrace offers very valuable information about where and why you point (reference) to a null-value.

Gewure
  • 1,208
  • 18
  • 31
  • Thanks for looking into it. I added the above try-catch however, the porgram doesn't compile at all now, gives me an error saying "`void` type not allowed here" – JavaPilgrim Sep 16 '16 at 14:24
  • you lack the "static" in front of void main - only exactly one main function is allowed in a java programm. `public static void main(String[] args) {` is the header you need. – Gewure Nov 23 '16 at 09:13