From 64ed383fe3f53a6fc710a4c5f0f075bc2a1b2606 Mon Sep 17 00:00:00 2001 From: fdai6499 Date: Fri, 10 Feb 2023 13:40:33 +0100 Subject: [PATCH] binary to int --- src/main/java/src/TasksFrame.java | 59 ++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 20 deletions(-) diff --git a/src/main/java/src/TasksFrame.java b/src/main/java/src/TasksFrame.java index 9e166cd..d449b2d 100644 --- a/src/main/java/src/TasksFrame.java +++ b/src/main/java/src/TasksFrame.java @@ -114,7 +114,7 @@ public class TasksFrame extends JFrame { } private void setupAtoi(){ - JPanel jPanel = setupPanel("atoi"); + JPanel jPanel = setupPanel("Interger / Binary Parsing"); JLabel jLabel = new JLabel(); jLabel.setVisible(true); @@ -132,9 +132,9 @@ public class TasksFrame extends JFrame { output.setBounds(5, 60, 200, 30); jPanel.add(output); - JButton jButton = new JButton("iton"); + JButton jButton = new JButton("int to binary"); jButton.setVisible(true); - jButton.setBounds(210, 30, 100, 30); + jButton.setBounds(210, 30, 160, 30); jPanel.add(jButton); jButton.addActionListener(new ActionListener() { @Override @@ -142,30 +142,49 @@ public class TasksFrame extends JFrame { String text = input.getText(); int value = Integer.valueOf(text); - String binary = calcAtoi(value); + String binary = calcItoB(value); + + output.setText(""); output.setText(binary); } }); -// JButton jButton2 = new JButton("ntoi"); -// jButton2.setVisible(true); -// jButton2.setBounds(210, 30, 100, 30); -// jPanel.add(jButton2); -// jButton2.addActionListener(new ActionListener() { -// @Override -// public void actionPerformed(ActionEvent e) { -// String text = output.getText(); -// int value = Integer.valueOf(text); -// -// String binary = calcAtoi(value); -// output.setText(binary); -// -// } -// }); + JButton jButton2 = new JButton("binary to int"); + jButton2.setVisible(true); + jButton2.setBounds(210, 60, 160, 30); + jPanel.add(jButton2); + jButton2.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String text = output.getText(); + int value = Integer.valueOf(text); + + String binary = calcBinaryToInt(value); + + input.setText(""); + input.setText(binary); + + } + }); + } + + public String calcBinaryToInt(int value) { + + LinkedList integers = new LinkedList<>(); + + int sum = 0; + int i = 0; + while (value > 0) { + int rest = value % 10; + sum += rest * Math.pow(2, i++); + value/=10; + } + + return String.valueOf(sum); } - public String calcAtoi(int value) { + public String calcItoB(int value) { return Integer.toBinaryString(value); }