Converting Binary to Decimal using a text file - java

I'm creating a program made up of two java files. The first one involves creating a class that accepts a binary from the user and returns its decimal value. The second involves creating a class that reads a list of binary strings from a text file and writes their decimal values to the console. This class should call methods from the first java class in order to achieve its tasks, and should be able to indicate if one of the strings in this file is not binary.
I have the first java class completed, but I'm having difficulty on the second, specifically on how I can get the program to read each individual String from the text file and then either print out their values or declare that they are not a binary. I also need some help on how to call methods from the first class. Could someone help lead me in the right direction?
Here are both codes:
Class 1:
import java.util.*;
public class BinaryDecoder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary: ");
String binary = input.nextLine();
System.out.println("---------------");
boolean isBinary = binaryDetector(binary);
if(isBinary) {
int count = 0;
for(int i=0; i<binary.length(); i++) {
if(binary.charAt(i) != ' ') {
count++;
}
}
int binarySize = Integer.valueOf(count);
System.out.println("Binary size: " + binarySize);
int decimalValue = binaryToDecimal(binary);
System.out.println("Value = " + decimalValue);
}
else {
System.out.println("Not a binary");
}
}
public static boolean binaryDetector(String x) {
int copyOfInput = Integer.valueOf(x);
while(copyOfInput != 0) {
if(copyOfInput % 10 > 1) {
return false;
}
copyOfInput = copyOfInput/10;
}
return true;
}
public static int binaryToDecimal(String n) {
String num = n;
int dec_value = 0;
int base = 1;
int len = num.length();
for(int i = len - 1; i>= 0; i--) {
if(num.charAt(i) == '1') {
dec_value += base;
}
base = base * 2;
}
return dec_value;
}
}
Class 2
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BinaryToDecimalTester {
public static void main(String[] args) throws Exception{
Scanner inFile = new Scanner(new File("Strings.txt"));
while(inFile.hasNext()) {
String inString = inFile.next();
}
}
}
And let's say for reference that the text file has these numbers in it:
1011010011101
1011101110101
1201234000100
1234456000110
1011010100011
Please let me know if you need any more clarification or information. Thank you all very much!

In order to use methods from BinaryDecoder in BinaryToDecimalTester you will have to import them. The best way would be to declare package in each class and import that using it, for example
Decoder class:
package binarynumbers;
import java.util.*;
public class BinaryDecoder {
public static void main(String[] args) { ...
and then import specific ( or all ) methods in BinaryToDecimalTester:
package stackoverflow;
import java.io.File;
import java.util.Scanner;
import static stackoverflow.BinaryDecoder.binaryToDecimal;
public class BinaryToDecimalTester { ...
importing it this way lets you use it normally as you woud expect :
System.out.println(binaryToDecimal(inString));
Concept of packages and imports is more complicated than this and essential to writing programs.
As to reading each individual line as String from the text file and processing it your class is sufficient, FileInputReader is one of another options to read from file. My example would be this:
package binarynumbers;
import java.io.BufferedReader;
import java.io.FileReader;
import static binarynumbers.BinaryDecoder.binaryToDecimal;
import static binarynumbers.BinaryDecoder.binaryDetector;
public class BinaryToDecimalTester {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("Strings.txt"));
String line = "";
while ((line = br.readLine()) != null)
{
System.out.println(binaryDetector(line));
System.out.println(binaryToDecimal(line));
}
}
}
in terms of implementing method detecting binary numbers I can suggest this article

You have to select which class should be your main.
If you keep 2 as your main and then instead of main in 1 you can read both files in 2 and used the static methods you have created in 1 by importing them in 2.
import BinaryDecoder.binaryToDecimal;

I would recommend you do the check for a binary digit as you try to convert the value. Then throw an exception and print the message if the digit is not binary.
There is no need to first check and then convert the value.
Here is an easy way to do the conversion.
public static int binaryToDecimal(String n) {
int val = 0;
for(char c : n.toCharArray()) {
if (c != '1' && c != '0') {
throw new IllegalArgumentException("Number not binary");
}
val = val*2;
val += c-'0';
}
return val;
}
Now all you need to do is read in the values and call the method. In lieu of the exception you could also return an optional.
public static OptionalInt binaryToDecimal(String n) {
int val = 0;
for(char c : n.toCharArray()) {
if (c != '1' && c != '0') {
return OptionalInt.empty();
}
val = val*2;
val += c-'0';
}
return OptionalInt.of(val);
}
Now just check to see if the returned Optional is empty before you print the result. To read in the values from a file, I would recommend using a scanner instance. Here is an example using the data mentioned in your question along with the required imports.
import java.io.File;
import java.io.IOException;
import java.util.OptionalInt;
import java.util.Scanner;
try (Scanner input = new Scanner(new File("f:/numbers.txt"))) {
while (input.hasNextLine()) {
String str = input.nextLine();
OptionalInt op = binaryToDecimal(str);
System.out.printf("%s -> %s%n", str, op.isPresent() ?
op.getAsInt() : "Non binary string");
}
} catch (IOException ie) {
ie.printStackTrace();
}
prints
1011010011101 -> 5789
1011101110101 -> 6005
1201234000100 -> Non binary string
1234456000110 -> Non binary string
1011010100011 -> 5795

Related

How to take whole java code input from console and evaluate it using JShell

Using the bellow commented approach i was only able to evaluate single link code such as int c = 2+3. i want to take the whole java code(multiple lines of code ) from front end or like from user and then in backend i want to evaluate the code and get the output of it
Input must contain a java code eg : - Function<Integer, Double> half = a -> a / 2.0;System.out.println(half.apply(5));
import java.util.*;
import java.util.List;
import jdk.jshell.JShell;
import jdk.jshell.SnippetEvent;
import jdk.jshell.Snippet;
import java.io.ByteArrayInputStream;
import java.io.Console;
import java.util.List;
import jdk.jshell.*;
import jdk.jshell.Snippet.Status;
public class ExpTry {
private static boolean handleEvent(SnippetEvent ste) {
//System.out.println( ste.snippet());
System.out.println(ste.value());
return false;
}
public static void main(String[] args) {
//System.out.println("hi");
JShell js = JShell.create();
String Datatype1 = "int";
String Datatype2 = "double";
Scanner sc= new Scanner(System.in);
System.out.println("Enter a string: ");
String input= sc.nextLine();
//String input = " Function<Integer, Double> half = a -> a / 2.0;
System.out.println(half.apply(5)); ";
if(Datatype1 == "int" && Datatype2 == "double")
{
for (SnippetEvent e :
js.eval(js.sourceCodeAnalysis().analyzeCompletion(input).source())) {
// Report the event, recording failure
handleEvent(e);
}
/*
List<SnippetEvent> events = js.eval(input);
for (SnippetEvent e : events) {
if (e.value() != null) {
System.out.printf("OUTPUT: %s\n", e.value());
}
}*/
}}}

Need help reading in 2 digit numbers in a text file

This is my code for the project currently. I have any number 10 or above it reads each individual digit instead of the whole number. Any help?
Numbers I am using:
1 3
1 1
-1 -5
5 3
45 45
1001001100 1001001100
import java.util.Scanner;
import java.io.*;
import java.io.PrintWriter;
public class comparison_rylan_howard {
public static void main(String[] args) throws IOException {
Scanner reader = new Scanner(new
File("H:\\NetBeansProjects\\Unit1\\comparison.txt"));
try (PrintWriter writer = new PrintWriter("Results.txt")) {
while (reader.hasNext()) {
double first = reader.nextDouble();
double second = reader.nextDouble();
if (first <= -1 || second <= -1) {
writer.println("Error");
}
if (first > second) {
writer.println(">");
writer.println(" ");
}
if (first < second) {
writer.println("<");
writer.println(" ");
} else {
writer.println("=");
writer.println(" ");
}
}
}
}
}
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class comparison_rylan_howard {
public static void main(String[] args) throws IOException {
Scanner reader = new Scanner(new
File("H:\\NetBeansProjects\\Unit1\\comparison.txt"));
try (PrintWriter writer = new PrintWriter("Results.txt")) {
while (reader.hasNext()) {
double first = reader.nextDouble();
double second = reader.nextDouble();
writer.println(first+","+second );
if (first <= -1 || second <= -1) {
writer.println("Error");
writer.println("");
}
else if (first > second) {
writer.println(">");
writer.println("");
}
else if (first < second) {
writer.println("<");
writer.println("");
} else {
writer.println("=");
writer.println("");
}
}
}
}
}
Output:
1.0,3.0
<
1.0,1.0
=
-1.0,-5.0
Error
5.0,3.0
>
45.0,45.0
=
1.0010011E9,1.0010011E9
=
What you could do is split each line by the whitespace and then parse each element as an entire Integer. Something like:
String[] ints = reader.nextLine().split(' ');
double first = Double.parseDouble(ints[0]);
double second = Double.parseDouble(ints[1]);
What that basically does is take the next line, creates an array where each element is split by a space, and then attempts to process the Strings before and after the space as separate doubles.

How to find longest common suffix from a list of strings and return the resulting suffix length in java?

Consider the following in a ArrayList or LinkedList:
[Gloucestershire, Hampshire, Yorkshire, Lancashire]
shire is the longest common suffix of length 5.
The output should be 5
How can I write a method to achieve the above and return length
Try this.
Explanation is in the comments
package javaapplication1;
public class SegmentTree {
public static void main(String[] args) {
String[] array = {"Gloucestershire", "Hampshire", "Yorkshire", "Lancashire"};
int i,j;
int min=10000000;
//reversing the strings and finding the length of smallest string
for(i=0;i<(array.length);i++)
{
if(array[i].length()<min)
min=array[i].length();
StringBuilder input1 = new StringBuilder();
input1.append(array[i]);
array[i] = input1.reverse().toString();
}
//finding the length of longest suffix
for(i=0;i<min;i++)
{
for(j=1;j<(array.length);j++)
{
if(array[j].charAt(i)!=array[j-1].charAt(i))
{
break;
}
}
if(j!=array.length)
break;
}
System.out.println(i);
}
}
What I am doing here is,first checking the last elem of all strings, then 2nd last and so on.
Time Complexity: O(n*m), n=number of strings, m=length of smallest string
Guava has a helper function called Strings.commonSuffix(CharSequence a, CharSequence b) that could be used in your algorithm. I know adding dependency like Guava only to have this function can be overkill - in this case you can take a look at the source code to see how this function is implemented and you can move this implementation to your program. Then your program could look like this:
import com.google.common.base.Strings;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CommonSuffixLengthMain {
public static void main(String[] args) throws IOException {
assert 5 == commonSuffixLength(Arrays.asList("Gloucestershire", "Hampshire", "Yorkshire", "Lancashire"));
assert 2 == commonSuffixLength(Arrays.asList("abc", "dbc", "qebc", "webc"));
assert 0 == commonSuffixLength(Collections.emptyList());
assert 0 == commonSuffixLength(Collections.singletonList("abc"));
assert 0 == commonSuffixLength(Arrays.asList("abc", "def", "zxc"));
}
private static int commonSuffixLength(final List<String> strings) {
int result = 0;
if (strings == null || strings.size() < 2) {
return result;
}
for (int i = 0; i < strings.size() - 1; i++) {
String prefix = Strings.commonSuffix(strings.get(i), strings.get(i + 1));
result = result == 0 ?
prefix.length() :
Math.min(prefix.length(), result);
}
return result;
}
}

Finding largest value in an array from a text file

I'm programming in Java. I'm not good at programming, but I'm trying.
I managed to create a file that generates an array of 10k random (in range 1 through 1 million) numbers into a text file. This class is called 'CreateDataFile'
What I'm trying to do now is read the array from the text file created in 'CreateDataFile' from a completely different class. This new class is called 'ProcessDataFile'
The first thing I thought about doing is 'extends' the class. So both classes communicate.
The thing is, I know how to create a for loop in a program and then find the largest number. I just don't understand how to read this text file, and create a for loop that processes from the text file and finds the max value.
Here's my CreateDataFile class
import java.io.*;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int [] integers = new int[10000];
Random r = new Random();
try{
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i <integers.length; i++) {
int number = r.nextInt(1000000)+1;
p.print(" " + number);
}
p.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Now this generates the numbers I need into a text file called dataset529.
If everything was in one class, I'd just create a for loop.. something like
int max = integers[0];
for(int i = 0; i<integers.length; i++){
if (integers[i] > max)
System.out.println(integers[i]);
}
But as I'm creating my ProcessDataFile class, I'm having a hard time reading the text file created from the CreateDataFile class.
Any ideas on how I can read this text file and run a for loop over it to find the max number like I used above?
Thanks, any help would be appreciated.
First of all, you should write in the file each number on one line so that it's easier when you read the numbers from the file. This can be done just by doing:
p.print(number + "\n");
After that, you can use this code to get the max of all the numbers:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
String fileName = "dataset529.txt";
String temp;
int max = Integer.MIN_VALUE;
int i = 0;
int[] numbers = new int[10000];
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while((temp = br.readLine()) != null) {
if(temp.isEmpty())
break;
numbers[i++] = Integer.parseInt(temp);
}
}
for(i = 0; i < numbers.length; i++)
if(max < numbers[i])
max = numbers[i];
System.out.println(max);
}
Write the content of each number on new line. While reading the file, maintain a max element.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int[] integers = new int[10000];
Random r = new Random();
try {
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i < integers.length; i++) {
int number = r.nextInt(1000000) + 1;
p.print(number + "\n");
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now read the file line by line.
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
int max = Integer.MIN_VALUE;
String line = null;
BufferedReader br = new BufferedReader(new FileReader("dataset529.txt"));
while ((line = br.readLine()) != null) {
int num = Integer.parseInt(line);
if (max < num) {
max = num;
}
}
}
System.out.println(max);
}

Java Scanner issues, Notecard class

I am trying to make a program that is basically virtual notecards. Each notecard has a string for a question and an answer as well as a count for now many times it has been asked. I am using a scanner in many instances and I think i am using it incorrectly, and am not quite sure why. The program will let me answer the first 2 questions, tell me they are incorrect no matter what, and skip letting me answer the last one. Here is the notecard class:
public class Notecard {
public String ans;
public String q;
public int count;
public Notecard(String q, String ans) {
this.q = q;
this.ans = ans;
this.count = 0;
}
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
System.out.println("Correct!");
return true;
} else {
System.out.println("Incorrect! Correct answer:" + this.ans);
count++;
return false;
}
}
public void clearCount() {
this.count = 0;
}
public String getQ() {
return this.q;
}
}
and here is my other file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class CreateNotecard {
int trys;
public static void main(String[] args) {
System.out.println("Get ready to be quizzed \n\n");
ArrayList<Notecard> notecards = makeCards();
quiz(notecards);
}
static ArrayList<Notecard> makeCards() {
ArrayList<Notecard> notecards = new ArrayList<Notecard>();
try {
BufferedReader in = new BufferedReader(new FileReader(
"notecards.txt"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
String[] argg = str.split(",");
notecards.add(new Notecard(argg[0], argg[1]));
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
return notecards;
}
static void quiz(ArrayList<Notecard> notecards) {
ArrayList<Notecard> backupList = notecards;
Scanner sc = new Scanner(System.in);
long seed = System.nanoTime();
Collections.shuffle(notecards, new Random(seed));
int total = notecards.size();
int correct = 0;
for (Notecard x : notecards) {
System.out.println(x.getQ());
String effort = sc.next();
Boolean nailedIt = x.answer(effort);
if (nailedIt) {
correct++;
}
}
System.out.println("Total Notecards: " + total + "\nTotal Correct: "
+ correct);
System.out.println("Accuracy: " + (correct / total));
System.out.println("Do you want to repeat? Put \"y\" or \"n\"");
String choice1 = sc.nextLine();
if (choice1.toUpperCase().equals("Y")) {
System.out.println("Use only cards missed or all? Type \"missed\" or \"all\"");
String choice2 = sc.nextLine();
if (choice2.toUpperCase().equals("MISSED")) {
quiz(notecards);
} else {
quiz(backupList);
}
} else {
return;
}
}
}
I have a text file which I am using for this program, it contains
19-9,10
square root of 4,2
capitol of Missouri,Jefferson City
Blastoise's 1st evolution,squirtle
and my output is
Get ready to be quizzed
square root of 4
2
Incorrect! Correct answer:2
capitol of Missouri
Jefferson City
Incorrect! Correct answer:Jefferson City
Blastoise's 1st evolution
Incorrect! Correct answer:squirtle
Total Notecards: 3
Total Correct: 0
Accuracy: 0
Do you want to repeat? Put "y" or "n"
You are comparing the wrong things:
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
Should be
if (this.ans.toUpperCase().equals(effort.toUpperCase())) {
The problem is that the Scanner class is looking for a delimiter to create tokens with, which is by default whitespace. Since you enter "2", the Scanner.next() finds no delimiters, so no token.
For example, if you enter "Jefferson City", the Scanner found one delimiter, so two tokens. sc.next in that case would be "Jefferson" only (no "City", that's the next token).
Solution? Read the line from stdin and using sc.nextLine()

Categories

Resources