I am doing an assignment for class which I have to create a brute force password cracker in java.
Write a function using Recursion to crack a password. The password is of unknown length (maximum 10) and is made up of capital letters and digits. (Store the actual password in your program, just for checking whether the string currently obtained is the right password.)
The solution I have is:
import java.util.Arrays;
public class BruteForce {
public static void main(String[] args) {
bruteForce(3);
}
public static String bruteForce(int size) {
int[] password = new int[size];
String[] finalPassword = new String[size];
for (int i = 0; i < size; i++) {
password[i] = 0;
finalPassword[i] = "";
}
String pass = "AAA";
return computePermutations(size, password, 0, pass);
}
private static String computePermutations(int size, int[] password, int position, String pass) {
String testString = "";
String assemble = "";
for (int i = 0; i < 36; i++) {
password[position] = i;
if (position != size - 1) {
testString = computePermutations(size, password, position + 1, pass);
if (testString != "") {
return testString;
}
} else if (position == size - 1) {
for (int j = 0; j < size; j++) {
switch (password[j] + 1) {
case 1:
assemble = assemble + "A";
break;
case 2:
assemble = assemble + "B";
break;
case 3:
assemble = assemble + "C";
break;
case 4:
assemble = assemble + "D";
break;
case 5:
assemble = assemble + "E";
break;
case 6:
assemble = assemble + "F";
break;
case 7:
assemble = assemble + "G";
break;
case 8:
assemble = assemble + "H";
break;
case 9:
assemble = assemble + "I";
break;
case 10:
assemble = assemble + "J";
break;
case 11:
assemble = assemble + "K";
break;
case 12:
assemble = assemble + "L";
break;
case 13:
assemble = assemble + "M";
break;
case 14:
assemble = assemble + "N";
break;
case 15:
assemble = assemble + "O";
break;
case 16:
assemble = assemble + "P";
break;
case 17:
assemble = assemble + "Q";
break;
case 18:
assemble = assemble + "R";
break;
case 19:
assemble = assemble + "S";
break;
case 20:
assemble = assemble + "T";
break;
case 21:
assemble = assemble + "U";
break;
case 22:
assemble = assemble + "V";
break;
case 23:
assemble = assemble + "W";
break;
case 24:
assemble = assemble + "X";
break;
case 25:
assemble = assemble + "Y";
break;
case 26:
assemble = assemble + "Z";
break;
case 27:
assemble = assemble + "0";
break;
case 28:
assemble = assemble + "1";
break;
case 29:
assemble = assemble + "2";
break;
case 30:
assemble = assemble + "3";
break;
case 31:
assemble = assemble + "4";
break;
case 32:
assemble = assemble + "5";
break;
case 33:
assemble = assemble + "6";
break;
case 34:
assemble = assemble + "7";
break;
case 35:
assemble = assemble + "8";
break;
case 36:
assemble = assemble + "9";
break;
}
}
System.out.println(assemble);
if (assemble.equalsIgnoreCase(pass)) {
System.out.println("Password is: " + assemble);
break; //replace this with: return assemble;
} else {
assemble = "";
}
}
}
return "";
}
}
However, when I run the program, the password AAA never seems to work but 998 works just fine, what exactly is wrong?
I think you should use a return statement if a match is found -
if (assemble.equalsIgnoreCase(pass)) {
System.out.println("Password is: " + assemble);
return assemble; // This is missing
}
Your main problem seems to be to break the loop at the right point. Try using a label to break the loop and solve this issue. Find more about labels here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}}
Related
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pointsproblem;
/**
*
*/
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PointsProblem {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
//create new object//
PointsProblem task1 = new PointsProblem();
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + input);
System.exit(0);
}
else {
System.out.println("Successfully opened file: " + input + ".");
}
//read all the lines in the file//
{
while (input.hasNext()) {
String word = input.nextLine();
System.out.println(word);
System.out.println("'" + input + "' is worth " + point + " points");
int point = "";
switch(point) {
case 'a': = "1":
case 'e': = "1";
case 'i': = "1";
case 'l': = "1";
case 'n': = "1";
case 'o': = "1";
case 'r': = "1";
case 's': = "1";
case 't': = "1";
case 'u': = "1";
case 'g': = "2";
case 'g': = "2";
case 'b': = "3";
case 'm': = "3";
case 'c': = "3";
case 'p': = "3";
case 'f': = "4";
case 'h': = "4";
case 'v': = "4";
case 'w': = "4";
case 'y': = "4";
case 'k': = "5";
case 'j': = "8";
case 'x': = "8";
case 'q': = "10";
case 'z': = "10";
return score = point + "";
}//end switch
}//end point calculation loop
public int getScore() {
return score;
}
//public boolean containsLetter(Character letter) {
//return points.contains(letter);//
}
I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.
Looks like a Map<Character, Integer> would fit:
public class PointsProblem {
final Map<Character, Integer> pointsMap = Map.of(
'a', 1,
'e', 1,
//.......
'z', 10
);
Then, in your function, simply use the map to find the corresponding point for each character:
int wordPoints = 0;
for(char c : word.toCharArray())
wordPoints += pointsMap.get(c);
Use a map to store the values:
Map<Character, Integer> charValues = new HashMap();
charValues.put('a', 2);
charValues.put('b', 1);
You can use the chars() and collect as sum
int total = word.chars()
.mapToObj(c -> charValues.get((char)c))
.mapToInt(i -> (int)i)
.sum();
But according to your use case you can count the chars first and then multiply
Map<Character, Integer> counter = new HashMap<>();
while (input.hasNext()) {
String word = input.next();
word.chars().forEach(c -> counter.compute(c, (k, v) -> v == null ? 1 : v + 1));
}
counter.entrySet()
.stream()
.mapToInt(e -> charValues.get(e.getKey())*e.getValue())
.sum();
if you are using switch your code will look like:
int total = 0;
switch (c){
case 'a' : total += 1; break;
case 'b' : total += 2; break;
}
I'm not sure that the code you've shown us will compile. There are a few things you need to change;
1) You're setting a String to an int. You'll want to change that to
int point = 0
2) You aren't setting anything in the switch statement
Change case 'a': = "1": to case 'a': point = 1;
3) You will never set a unique value in the switch statement because you aren't using 'break'
Checkout this page for a good tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Basically without any break statements, your code will go through the of the statements and point will just be assigned to your last case
You want to have something along the lines of
switch(char) {
case 'a': point = 1;
break;
case 'e': point = 1;
break;
// etc.
default: point = 1; // maybe throw an error or add some logging for the default case
break;
}
return point;
I am presuming that you actually have this switch statement in it's own method and not in main as you've shown us above, otherwise the return statement won't help you.
You can also shorten this so that each case simply returns a value (again, if this is in it's own method), i.e.
switch(char) {
case 'a': return 1;
case 'b': return 1;
// etc.
}
edit:
The best way to get the point value of the whole word via a switch statement is:
char[] chars = word.toCharArray();
int point=0;
for (char c: chars) {
switch(c) {
case 'a':
point += 1;
break;
// etc.
}
}
System.out.println("Total point value of word '" + word + "' was " + point);
Instead of assigning individually for each 'case' statement, you can also use the fall through feature of the switch block.
int calcScore(String str)
{
int score = 0;
for(int i=0; i<str.length(); i++)
{
switch(str.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u': score += 1; break;
case 'g': score += 2; break;
case 'b':
case 'm':
case 'c':
case 'p': score += 3; break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y': score += 4; break;
case 'k': score += 5; break;
case 'j':
case 'x': score += 8; break;
case 'q':
case 'z': score += 10; break;
}
}
return score;
}
This function can be called for each word.
Thanks everyone, I ended up with the following code which gives the output I am after;
System.out.println("Points problem");
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + file);
System.exit(0);
} else {
System.out.println("Successfully opened file: " + file + ".");
}
//read all the lines in the file//
while (input.hasNext()) {
String word = input.nextLine();
//System.out.println(word);
int l = word.length();
int point = 0;
for (int x = 0; x < l; x++) {
char c = word.charAt(x);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u':
point += 1;
break;
case 'd':
case 'g':
point += 2;
break;
case 'b':
case 'c':
case 'm':
case 'p':
point += 3;
break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y':
point += 4;
break;
case 'k':
point += 5;
break;
case 'j':
case 'x':
point += 8;
break;
case 'q':
case 'z':
point += 10;
break;
}//end switch*/
}//end point calculation loop
System.out.println(word + "is worth " + point + " points." );
}
it's Java Starter here, so i was Coding my program which makes a Password, i used the Random Object to have a random Number that will choose what Letter comes or What number comes.
I keep getting the Numbers and the Symbols Only.. what i get is something Like this:
"9=9null=99" I don't understand Why there's a null. Java doesn't show me any problems with my code (Doesn't show Null Pointer exception.)
Here's My code:
package project.Secureword.com;
import java.awt.*;
import java.awt.event.*;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.Random;
import javax.swing.*;
public class Main {
private static JFrame start;
private static TextField field;
private static String password;
private static String lastpass;
public static Settings passsettings;
public static Random r;
public static void main(String[] args) {
passsettings = new Settings();
passsettings.setIfDots(true);
passsettings.setIfLowercase(true);
passsettings.setIfNum(true);
passsettings.setIfUpprcase(true);
Settings.changerun();
start();
}
public static void start() {
Font a = new Font(null, Font.BOLD, 0);
Font size = a.deriveFont(20f);
JButton createPass = new JButton();
createPass.setText("<html> Click me to <br> Generate a Password! <html>");
createPass.setPreferredSize(new Dimension(100,100));
JLabel text = new JLabel();
text.setText("<html> Welcome to SECUREPASS! <br> An Extreme Strong Password Generator <br> Developed by OfficialCode");
text.setPreferredSize(new Dimension(150,150));
text.setFont(size);
field = new TextField(20);
field.setSize(new Dimension(50,50));
start = new JFrame("Secureword | Strong password Generator | Coded by OfficialCode");
start.setPreferredSize(new Dimension(390,390));
start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
start.setLocationRelativeTo(null);
start.setLayout(new BorderLayout());
start.getContentPane().add(createPass, BorderLayout.WEST);
start.getContentPane().add(text, BorderLayout.PAGE_START);
start.getContentPane().add(field, BorderLayout.CENTER);
start.pack();
start.setVisible(true);
password = "";
createPass.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field.setText(null);
field.selectAll();
allrandom();
}});
}
public static void allrandom() {
String[] pass = new String[8];
Random r = new Random();
for(int i = 0 ; i < pass.length ; i++) {
int ch = 0;
ch = r.nextInt(3);
switch(ch) {
case 1:
if(passsettings.isIfDots()) {
String newchar = "";
newchar = dotpass();
pass[i] = newchar;
break;
}
case 2:
if(passsettings.isIfNum()) {
String newchar2 = "";
newchar2 = Numpass();
pass[i] = newchar2;
break;
}
case 3:
String newchar3 = "";
newchar3 = charchose();
pass[i] = newchar3;
break;
}
}
for(int i = 0 ; i < pass.length ; i++) {
String newpasschar = "";
newpasschar = pass[i];
password = password + newpasschar;
}
field.setText(password);
// random() end
}
public static String uppercasepass() {
Random r = new Random();
String passletter = "";
int rN3 = 0;
rN3 = r.nextInt(26);
switch(rN3) {
case 1:
passletter = "A";
case 2:
passletter = "B";
case 3:
passletter = "C";
case 4:
passletter = "D";
case 5:
passletter = "E";
case 6:
passletter = "F";
case 7:
passletter = "G";
case 8:
passletter = "H";
case 9:
passletter = "I";
case 10:
passletter = "J";
case 11:
passletter = "K";
case 12:
passletter = "L";
case 13:
passletter = "M";
case 14:
passletter = "N";
case 15:
passletter = "O";
case 16:
passletter = "P";
case 17:
passletter = "Q";
case 18:
passletter = "R";
case 19:
passletter = "S";
case 20:
passletter = "T";
case 21:
passletter = "U";
case 22:
passletter = "V";
case 23:
passletter = "W";
case 24:
passletter = "X";
case 25:
passletter = "Y";
case 26:
passletter = "Z";
}
return passletter;
// uppercase() end
}
public static String lowercasepass() {
Random r = new Random();
String passletter = "";
int rN3 = 0;
rN3 = r.nextInt(26);
switch(rN3) {
case 1:
passletter = "a";
case 2:
passletter = "b";
case 3:
passletter = "c";
case 4:
passletter = "d";
case 5:
passletter = "e";
case 6:
passletter = "f";
case 7:
passletter = "g";
case 8:
passletter = "h";
case 9:
passletter = "i";
case 10:
passletter = "j";
case 11:
passletter = "k";
case 12:
passletter = "l";
case 13:
passletter = "m";
case 14:
passletter = "n";
case 15:
passletter = "o";
case 16:
passletter = "p";
case 17:
passletter = "q";
case 18:
passletter = "r";
case 19:
passletter = "s";
case 20:
passletter = "t";
case 21:
passletter = "u";
case 22:
passletter = "v";
case 23:
passletter = "w";
case 24:
passletter = "x";
case 25:
passletter = "y";
case 26:
passletter = "z";
}
return passletter;
}
public static String Numpass() {
Random r = new Random();
String passletter = "";
int rN = 0;
rN = r.nextInt(9);
switch(rN) {
case 1:
passletter = "1";
case 2:
passletter = "2";
case 3:
passletter = "3";
case 4:
passletter = "4";
case 5:
passletter = "5";
case 6:
passletter = "6";
case 7:
passletter = "7";
case 8:
passletter = "8";
case 9:
passletter = "9";
}
return passletter;
}
public static String dotpass() {
Random r = new Random();
String passletter = "";
int rN5 = 0;
rN5 = r.nextInt(5);
switch(rN5) {
case 1:
passletter = "_";
case 2:
passletter = "]";
case 3:
passletter = "$";
case 4:
passletter = "#";
case 5:
passletter = "=";
}
return passletter;
}
public static String charchose() {
Random r = new Random();
String line = "";
int rN = 0;
rN = r.nextInt(20);
switch(rN) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
if(passsettings.isIfLowercase()) {
line = lowercasepass();
}
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
if(passsettings.isIfUpprcase()) {
line = uppercasepass();
}
}
return line;
}
}
The problem comes from the fact that Random.nextInt(n) return a value between 0-n (exclusive). Your switch case are all wrong by one.
This explain your null since you don't do anything for ch = 0, the String stays at null:
switch(ch){
case 1: ... //symbol
case 2 ... //number
case 3: ... //letter
}
This should be
switch(ch){
case 0: ... //symbol
case 1: ... //number
case 2: ... //letter
}
Some other issues or improvments :
You don't break after a case so you always get the last case executed (well all following case). Resulting in a possibilities of 4 character zZ9= (easy to bruteforce !)
You should use a char[] instead of String[], there is no need of using String to store one character like you do.
Instead of
String s = "a";
you can
char c = 'a';
Reducing the length of the code if you read the next point.
You can reduce your switch by doing some addition like 'a' + r.nextInt(26) to get a value between 'a' to 'z'
For a random symbol, instead of a switch, create a static array of char[] with every character, then get a random value using the size of this array.
Like :
final static char[] symbol = {'#', '#', '-', '\\', '/', '*'};
static getRadomSymbol(){
Random r = new Random();
return symbol[r.nextInt(symbol.length)];
}
Allowing the add of character easily (and reducing again the number of line ;) )
I am trying to create a program that takes input from the user using the command line of 3 octal number, for example 5, 2, 6 or 5,2,6 and convert them into 3 sets of 3 digit binary numbers, like 101 010 110, and also print out those corresponding CHMOD permissions like r-x -w- rw-.
I am having a lot of trouble splicing these numbers apart with substring into 3 separate numbers of 5 2 and 6.
I also need the program to convert from the set of binary digits into 3 numerical digits and permissions. And from the permissions into digits and binary.
Here is what I have so far:
import java.util.Scanner;
class Test {
public static void main(String cheese[]){
Scanner scan = new Scanner(System.in);
String line1 = scan.nextLine();
//String line2 = scan.nextLine();
//String line3 = scan.nextLine();
//String line4 = scan.nextLine();
//String line5 = scan.nextLine();
System.out.println(line12(line1));
}
public static String line12(String line){
String ownerPermissions = "";
String groupPermissions = "";
String otherPermissions = "";
int comma = 0;
int lineLength = line.length();
if (line.indexOf(" ") != -1){
comma = line.indexOf(",");
}else{
comma = 1;
}
String firstNumber = line.substring(0, 1);
line = line.substring(comma + 1, lineLength);
int comma2 = line.indexOf(",");
String secondNumber = line.substring(comma + 1, comma2);
String thirdNumber = line.substring(lineLength);
int firstInt= Integer.parseInt(firstNumber);
int secondInt = Integer.parseInt(secondNumber);
int thirdInt = Integer.parseInt(thirdNumber);
String firstBinary = Integer.toBinaryString(firstInt);
String secondBinary = Integer.toBinaryString(secondInt);
String thirdBinary = Integer.toBinaryString(thirdInt);
switch(firstInt){
case 0:
ownerPermissions = "---";
break;
case 1:
ownerPermissions = "--x";
break;
case 2:
ownerPermissions = "-w-";
break;
case 3:
ownerPermissions = "-wx";
break;
case 4:
ownerPermissions = "r--";
break;
case 5:
ownerPermissions = "r-x";
break;
case 6:
ownerPermissions = "rw-";
break;
case 7:
ownerPermissions = "rwx";
break;
}
switch(secondInt){
case 0:
groupPermissions = "---";
break;
case 1:
groupPermissions = "--x";
break;
case 2:
groupPermissions = "-w-";
break;
case 3:
groupPermissions = "-wx";
break;
case 4:
groupPermissions = "r--";
break;
case 5:
groupPermissions = "r-x";
break;
case 6:
groupPermissions = "rw-";
break;
case 7:
groupPermissions = "rwx";
break;
}
switch(thirdInt){
case 0:
otherPermissions = "---";
break;
case 1:
otherPermissions = "--x";
break;
case 2:
otherPermissions = "-w-";
break;
case 3:
otherPermissions = "-wx";
break;
case 4:
otherPermissions = "r--";
break;
case 5:
otherPermissions = "r-x";
break;
case 6:
otherPermissions = "rw-";
break;
case 7:
otherPermissions = "rwx";
break;
}
String output = firstBinary + " " + secondBinary + " " + thirdBinary + " and " + ownerPermissions + " " + groupPermissions + " " + otherPermissions;
return output;
}
}
You will find it easier if you make your code much simpler. I suggest something like
public static void main(String[] args) {
System.out.println(line12("5, 2, 6"));
}
public static String line12(String line) {
String[] nums = line.trim().split(" *, *");
StringBuilder sb = new StringBuilder();
for (String s : nums) {
if (sb.length() > 0) sb.append(" ");
int num = Integer.parseInt(s);
sb.append((num & 4) == 0 ? '-' : 'r');
sb.append((num & 2) == 0 ? '-' : 'w');
sb.append((num & 1) == 0 ? '-' : 'x');
}
return sb.toString();
}
prints
r-x -w- rw-
Im here again to ask question.
Earlier we have to explain our program in some instructor in my school and Thankfully I explained it well. but the problem is the codes that I used is Hashmapping but this was not yet taught to us
So the professor told me that I can use switch structure instead of using Hashmapping but I dont know how i can translate it in switch method..
Can you show me if its possible to create an Switch in my program..
PS: I Know I can used binary built in.. but this is the requirements
thank you
my code:
import java.util.*;
import java.io.*;
class Jasper {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
HashMap<Character, String> map = new HashMap<Character, String>();
map.put('0', "0000");
map.put('1', "0001");
map.put('2', "0010");
map.put('3', "0011");
map.put('4', "0100");
map.put('5', "0101");
map.put('6', "0110");
map.put('7', "0111");
map.put('8', "1000");
map.put('9', "1001");
map.put('A', "1010");
map.put('B', "1011");
map.put('C', "1100");
map.put('D', "1101");
map.put('F', "1111");
System.out.print("Input your Hex Number here : ");
String userInput = input.readLine();
String x = userInput.toUpperCase();
String resultx = "";
for (int i = 0; i < userInput.length(); i++) {
char hexVal = x.charAt(i);
String binary = map.get(hexVal);
resultx = resultx + "\n" + hexVal + "-" + binary;
}
System.out.println("The Binary of " + x + ":" + resultx);
}
}
Since you want to use a switch let's extract it into a method like,
public static String charToBin(char ch) {
switch (Character.toUpperCase(ch)) {
case '0': return "0000";
case '1': return "0001";
case '2': return "0010";
case '3': return "0011";
case '4': return "0100";
case '5': return "0101";
case '6': return "0110";
case '7': return "0111";
case '8': return "1000";
case '9': return "1001";
case 'A': return "1010";
case 'B': return "1011";
case 'C': return "1100";
case 'D': return "1101";
case 'E': return "1110";
case 'F': return "1111";
}
return "Unknown";
}
Then you can convert a String from hex to binary with a method like,
public static String hexToBinary(String in) {
if (in == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (char ch : in.toCharArray()) {
sb.append(charToBin(ch));
}
return sb.toString();
}
Finally, you can test it with something like
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
String val = Integer.toHexString(i);
String cust = hexToBinary(val);
assert(Integer.parseInt(cust, 2) == i);
}
}
Or you could do it like this:
/*ToDo - use your favourite parser to convert your string to an integer*/
System.out.println(Integer.toBinaryString(x/*x is type int*/));
Very important in software development not to reinvent things. Standard code is also self-documenting.
(Another approach would be to use >> repeatedly and use operators like %, | and ^ to yank out each bit in turn.)
for (int i = 0; i < userInput.length(); i++) {
char hexVal = x.charAt(i);
String binary;
switch (hexVal) {
case '0':
binary = "0000";
break;
case '1':
binary = "0001";
break;
case '2':
binary = "0010";
break;
case '3':
binary = "0011";
break;
case '4':
binary = "0100";
break;
case '5':
binary = "0101";
break;
case '6':
binary = "0110";
break;
case '7':
binary = "0111";
break;
case '8':
binary = "1000";
break;
case '9':
binary = "1001";
break;
case 'A':
binary = "1010";
break;
case 'B':
binary = "1011";
break;
case 'C':
binary = "1100";
break;
case 'D':
binary = "1101";
break;
case 'E':
binary = "1110";
break;
case 'F':
binary = "1111";
break;
}
resultx = resultx + "\n" + hexVal + "-" + binary;
}
As the previous contributors already wrote, you could use several elegant algorithms to provide a proper result, but using a switch() statement a with minimal changes of your code could look like this:
import java.util.*;
import java.io.*;
class Jasper {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Input your Hex Number here : ");
String userInput = input.readLine();
String x = userInput.toUpperCase();
String resultx = "";
String binVal;
for (char hexChar : x.toCharArray()) {
switch (hexChar) {
case('0') : binVal="0000";
break;
case('1') : binVal="0001";
break;
case('2') : binVal="0010";
break;
....
case('F') : binVal="1111";
break;
default : binVal="invalid input";
}
resultx = resultx + "\n" + hexChar + "-" + binVal;
}
System.out.println("The Binary of " + x + ":" + resultx);
}
}
I have a double split up into an int array, however the problem I am facing, is that I need it to fill in from the back, like this:
int[] arrayA = new int[5];
int[] arrayB = new int[5];
x = 23456.08;
//code here
//what im left with:
arrayA [0,2,3,4,5,6];
arrayB [0,8];
Heres how im cutting up the double:
public static void main(System args[])
{
Scanner input = new Scanner(System.in);
String answer = "";
int count = 0;
int thatone = 0;
int[] splitD = new int[5]; //main num
int[] splitDec = new int[1]; //decimal
//Enter the Number
System.out.print("Enter a number to convert: ");
double num = input.nextDouble();
// convert number to String
String convert = num + "";
// split the number
String[] split = convert.split("\\.");
String firstPart = split[0];
char[] charArray1 = firstPart.toCharArray();
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
// the decimal part
if (split.length > 1)
{
String secondPart = split[1];
char[] charArray2 = secondPart.toCharArray();
splitDec = new int[charArray2.length];
for (int i = 0; i < charArray2.length; i++)
{
// convert char to int
splitDec[i] = Character.getNumericValue(charArray2[i]);
}
}
for(int i =0; i<count;i++)
{
if(i ==0) // x00000.00 or 000x00.00
{
if(splitD[0] != "0")
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else
{
answer+= "";
}
}
else if(i ==1)//this goes with i =2 //0x0000
{
if(splitD[i] == 1)
{
switch (splitD[i+1])
{
case 9: answer+="Nineteen"; break;
case 8: answer+="Eighteen"; break;
case 7: answer+="Seventeen"; break;
case 6: answer+="Sixteen"; break;
case 5: answer+="Fifteen"; break;
case 4: answer+="Fourteen"; break;
case 3: answer+="Thirteen"; break;
case 2: answer+="Twelve"; break;
case 1: answer+="ten"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
thatone = 1;
}
else
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirty"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
}
}
else if(i == 2) //00x000
{
if(thatone ==0)
{
switch (splitD[i])
{
case 9: answer+=" Nine"; break;
case 8: answer+=" Eight"; break;
case 7: answer+=" Seven"; break;
case 6: answer+=" Six"; break;
case 5: answer+=" Five"; break;
case 4: answer+=" Four"; break;
case 3: answer+=" Three"; break;
case 2: answer+=" Two"; break;
case 1: answer+=" One"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
}
else
{
}
}
else if(i ==3)
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else if(i ==4) //0000x0
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirdy"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
answer+= " ";
}
else if(i ==5) //00000x
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
}
}
if(splitDec[0] == 0)
{
answer += " and 00/100 Dollars";
}
else if(splitDec[1] == 0)
{
answer += " and " +splitDec[0] + "0/100 Dollars";
}
else
{
answer += " and " +splitDec[0] +splitDec[1] +" /100 Dollars";
}
System.out.println(answer);
}
}
What should I do to make the array add 0 in the appropriate places?
such as if I typed in 54.00 I would get:
int[] SplitD = {0,0,0,0,5,4};
Thanks!
Instead of re-initializing the array:
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
Use the existing (with length = 5), iterating from the back:
if(charArray1.length > 5) // heavy hard-code, would prefer something better
throw new IllegalArgumentException("Maximum 5 digits, on both decimal sides.");
// watch out of ArrayIndexOutOfBoundsException
for (int i = charArray1.length - 1, j = splitD.length -1 ;
i >=0 && j >=0; i--, j--)
{
// convert char to int
splitD[j] = Character.getNumericValue(charArray1[i]);
count++;
}
Recall, int arrays are filled with zeros, at initialization.
Think creating an array of String, one String for each character (including the decimal point), would be a better approach:
String[] chars = String.valueOf(num).split("(?<=.)");
Job done.
Edit:
To use a switch, don't even split:
for (byte b : String.valueOf(num).getBytes()) {
switch(b) {
case '.':
case '1':
}
}