Good morning
I am very new to
java, I am trying to read a binary value from a text file to assign it to a variable in java, to then convert it to its decimal number equivalent.
I can read a local text file using the code down below:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInput {
public static void main(
String[] args) {
File file = new File("C:\\temp\\h12-2\\test.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can perform my calculation of binary to decimal using the code down below:
public class test2
{
public static void main(String args[])
{
String bin = "1111111111111111111111111";
double ctr=1, decimal=0;
for (double i = bin.length()-1; i>=0; i--)
{
if(bin.charAt((int) i)=='1')
decimal+=ctr;
ctr*=2;
}
System.out.println ("Decimal: "+decimal);
}
}
However I cannot succeed to put the two together successfully.
I'm thinking that it would have to be done with a variable in place of the ones String bin = "1111111111111111111111111";, I was thinking:
String Convert;
Convert = (dis.readLine());
String bin = "Convert";
It didn't work, my decimal result was 0.0 instead of obtaining the conversion of the binary numbers contained in the text file.
So I thought that perhaps I was using the wrong type and changed my String to an "int" but I receive an error message in netbeans telling me "incompatible types
Found: java.lang.string
Required: int"
I have done quite a bit of reading on accessing files but I couldn't find what I needed.
I would really appreciate your guidance on how to approach this problem.
Thank you for your time,
John