I am facing some problems in Eclipse using Java. My code generates license plate numbers for cars in Germany, such as B-AC 7687 B is for Berlin, so as you can see, 3 chars and 4 integer numbers, both together is a String ( you will see this in my code). It generates one license randomly. I used math.random for this. If the user inputs "2" it means, one wants 2 licence plate numbers that are different not same! So here is the problem, it always generates the same license plate number although I used random principle. If the user inputs 2 there should be 2 different licences, for this, I have to start the generate method 2 times, or even more (depends on the input of the user). How can I start user-input depended methods? Here is my code:
import java.util.*;
public class Kennzeichen {
char[] alphabet = new char[26];
char[] nummern = new char[10];
String teilstring;
String teilnummern1, teilnummern2, teilnummern3, teilnummern4, teilnummern;
String finale;
int zahl = (int) ((Math.random()) * 25 + 1);
int zahl1 = (int) ((Math.random()) * 25 + 1);
int nummer1 = (int) (Math.random() * 9 + 1);
int nummer2 = (int) (Math.random() * 9 + 1);
int nummer3 = (int) (Math.random() * 9 + 1);
int nummer4 = (int) (Math.random() * 9 + 1);
char a = 65; //ascii
char b = 48; // asci
int zahler = 0;
Scanner s = new Scanner(System.in);
int eineZahl = s.nextInt();
public void arrayalphabet() { // generates an array alphabet A-Z
for (int i = 0; i < alphabet.length; i++, a++) {
alphabet[i] = a;
}
}
public void arraynummern() { //generates numbers between 0 and 9
for (int i = 0; i < nummern.length; i++, b++) {
nummern[i] = b;
}
}
public String generierekennzeichen() { // first char must be B therefore alphabet[1]
return(teilstring = alphabet[1] + "" + alphabet[zahl] + "" + alphabet[zahl1]);
}
public String generierenummern() { // 4 numbers are generated and returned as total
teilnummern1 = nummern[nummer1] + "";
teilnummern2 = nummern[nummer2] + "";
teilnummern3 = nummern[nummer3] + "";
teilnummern4 = nummern[nummer4] + "";
return(teilnummern = teilnummern1 + teilnummern2 + teilnummern3 + teilnummern4 + "");
}
public void print() { //prints the total license such as B-AD 7645
System.out.println(finale = teilstring + "-" + teilnummern);
}
public void erzeugestack() { //using stack, not that important(just practise
Stack<String> s = new Stack<String>();
s.push(finale);
}
public void Abfrage() { // eineZahl is the input of the user, e.g 2
for(int i=0; i<eineZahl;i++){
generierekennzeichen();
generierenummern();
print();
}
}
public static void main(String[] args) {
Kennzeichen kennzeichen = new Kennzeichen();
kennzeichen.arrayalphabet();
// kennzeichen.generierekennzeichen();
kennzeichen.arraynummern();
// kennzeichen.generierenummern();
kennzeichen.Abfrage();
kennzeichen.erzeugestack();
}
}
It looks like you are initializing the numbers nummer1, nummer2 ... when you create the class. Therefore they don't change each time you call the method. if you just used
nummern[(int) (Math.random() * 9 + 1)]
instead of the nummern[nummer1], nummern[nummer2] then eeach number should be different.
public String generierenummern() { // 4 numbers are generated and returned as total
teilnummern1 = nummern[(int) (Math.random() * 9 + 1)] + "";
teilnummern2 = nummern[(int) (Math.random() * 9 + 1)] + "";
teilnummern3 = nummern[(int) (Math.random() * 9 + 1)] + "";
teilnummern4 = nummern[(int) (Math.random() * 9 + 1)] + "";
return(teilnummern = teilnummern1 + teilnummern2 + teilnummern3 + teilnummern4 + "");
Then you should also do the same thing with the letters.
The indexes you are using for generating the plate are assigned once (The time you instace your class) so they are the same for all calls to plate-generating methods. Instead initializing those variables in the first place, try locating them within the methods generierekennzeichen() and generierenummern() as follows:
import java.util.*;
public class Kennzeichen {
char[] alphabet = new char[26];
char[] nummern = new char[10];
String teilstring;
String teilnummern1, teilnummern2, teilnummern3, teilnummern4, teilnummern;
String finale;
char a = 65; //ascii
char b = 48; // asci
int zahler = 0;
Scanner s = new Scanner(System.in);
int eineZahl = s.nextInt();
public void arrayalphabet() { // generates an array alphabet A-Z
for (int i = 0; i < alphabet.length; i++, a++) {
alphabet[i] = a;
}
}
public void arraynummern() { //generates numbers between 0 and 9
for (int i = 0; i < nummern.length; i++, b++) {
nummern[i] = b;
}
}
public String generierekennzeichen() { // first char must be B therefore alphabet[1]
int zahl = (int) ((Math.random()) * 25 + 1);
int zahl1 = (int) ((Math.random()) * 25 + 1);
return(teilstring = alphabet[1] + "" + alphabet[zahl] + "" + alphabet[zahl1]);
}
public String generierenummern() { // 4 numbers are generated and returned as total
int nummer1 = (int) (Math.random() * 9 + 1);
int nummer2 = (int) (Math.random() * 9 + 1);
int nummer3 = (int) (Math.random() * 9 + 1);
int nummer4 = (int) (Math.random() * 9 + 1);
teilnummern1 = nummern[nummer1] + "";
teilnummern2 = nummern[nummer2] + "";
teilnummern3 = nummern[nummer3] + "";
teilnummern4 = nummern[nummer4] + "";
return(teilnummern = teilnummern1 + teilnummern2 + teilnummern3 + teilnummern4 + "");
}
public void print() { //prints the total license such as B-AD 7645
System.out.println(finale = teilstring + "-" + teilnummern);
}
public void erzeugestack() { //using stack, not that important(just practise
Stack<String> s = new Stack<String>();
s.push(finale);
}
public void Abfrage() { // eineZahl is the input of the user, e.g 2
for(int i=0; i<eineZahl;i++){
generierekennzeichen();
generierenummern();
print();
}
}
public static void main(String[] args) {
Kennzeichen kennzeichen = new Kennzeichen();
kennzeichen.arrayalphabet();
// kennzeichen.generierekennzeichen();
kennzeichen.arraynummern();
// kennzeichen.generierenummern();
kennzeichen.Abfrage();
kennzeichen.erzeugestack();
}
Related
I need a function that takes in a equation in the form of a String,
for example: "a * b + 5 * a + 5 + a + 6" and simplifies it in for example:
"a * b + 6 * a +11".
but I can't make my own class work and I can't find a library for it.
I hoped people you could help me
With the Symja library you can solve your problem like in this snippet:
package org.matheclipse.core.examples;
import org.matheclipse.core.eval.ExprEvaluator;
import org.matheclipse.core.expression.F;
import org.matheclipse.core.interfaces.IExpr;
import org.matheclipse.parser.client.SyntaxError;
import org.matheclipse.parser.client.math.MathException;
public class SimplifySO55169181 {
public static void main(String[] args) {
try {
ExprEvaluator util = new ExprEvaluator();
IExpr result = util.eval("a * b + 5 * a + 5 + a + 6");
// print: 11+6*a+a*b
System.out.println(result.toString());
} catch (SyntaxError e) {
// catch Symja parser errors here
System.out.println(e.getMessage());
} catch (MathException me) {
// catch Symja math errors here
System.out.println(me.getMessage());
}
}
}
I do not believe there is a standard library for what you ask. However, here are some pointers:
1) Validity check:
Remove all spaces(looping through each character adding it to a String if not space)
Make sure all values are * or + or [letter] or [number]
2) Counting variables:
Create a hashmap who's key is the variable and the value is the sum of the number of letters by looping through the string.
3) Counting variables based on multiplying (such as 6 * a). Loop through, see if variable as follows: [number][variable] or [variable][number]. Add the number - 1 (it was already counted once in step 2.
4) Count constants. Same as 3 except it would be [number]+[number].
5) Print it out in order you see fit.
I changed the pattern slightly. Additionally, for the program to work properly, variables must be lowercase and single characters. Division and subtraction have not been implemented although it would be fairly similar to most of the code. Lastly, the system expesct integers only to function properly.
package com.Bif.MathCondenser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class MathCondenser {
public static void main(String[] args) {
//input equations
String equation = "a * b + 10 * 3 + 50 * a + c * 3 * b * a * 4 * 3";
String equation_temp = "";
//constant character lists
ArrayList<String> alphabet = new ArrayList<String>();
ArrayList<String> numbers = new ArrayList<String>();
ArrayList<String> functions = new ArrayList<String>();
//equation separated into a list of products
ArrayList<String> products = new ArrayList<String>();
//variable definitions of each product
ArrayList<String> definitions = new ArrayList<String>();
ArrayList<String> definitionsDuplicate = new ArrayList<String>();
//collected constants for each product
ArrayList<String> multipliers = new ArrayList<String>();
//reduced terms for the equation
ArrayList<String> terms = new ArrayList<String>();
//fill alphabet arrayList
for(char character = 'a'; character <= 'z'; ++character){
alphabet.add(character-'a', character + "");
}
//fill numbers arrayList
for(int k = 0; k < 10; k++) {
numbers.add("" + k);
}
//fill functions arrayList
functions.add("*");
functions.add("+");
//remove spaces from equation
for(int k = 0; k < equation.length(); k++) {
if(equation.charAt(k) == ' ')
continue;
equation_temp += equation.charAt(k);
}
equation = equation_temp;
System.out.println("Equation: " + equation);
//validate allowed characters; exit if not a-z, 0-9, or *,+
for(int k = 0; k < equation.length(); k++) {
if(!alphabet.contains(equation.charAt(k) + "") && !numbers.contains(equation.charAt(k) + "") && !functions.contains(equation.charAt(k) + "")) {
System.out.println("Valid Characters: false, exiting");
System.exit(0);
}
}
System.out.println("Valid Characters: true, continuing");
//parse the equation into sets of products
Scanner scan = new Scanner(equation);
scan.useDelimiter("\\+");
while(scan.hasNext()) {
products.add(scan.next());
}
System.out.println("Product set:" + products);
//fill definition such that (2 * b * a * 3 * c) -> (abc)
String productAtLocationK;
for(int k = 0; k < products.size(); k++) {
productAtLocationK = products.get(k);
String definition = "";
for(int j = 0; j < productAtLocationK.length(); j++) {
//if it is a letter add it to definition
if(alphabet.contains(productAtLocationK.charAt(j) + "")) {
definition += productAtLocationK.charAt(j);
}
}
//alphabetizes definition
char[] tempDef = definition.toCharArray();
Arrays.sort(tempDef);
definitions.add(new String(tempDef));
definitionsDuplicate.add(new String(tempDef));
}
System.out.println("Definition set: " + definitions);
//fill multiplier set such that (2 * b * a * 3 * c) -> (6)
for(int k = 0; k < products.size(); k++) {
//get the product; default multiplier = 1; character at Location in product;
productAtLocationK = products.get(k);
int multiplier = 1;
String letterInProduct;
//set up scanner for every product in products array with * separator
scan = new Scanner(productAtLocationK);
scan.useDelimiter("\\*");
//loop through product, if (not letter -> number) then update multiplier
while(scan.hasNext()) {
letterInProduct = scan.next();
if(!alphabet.contains(letterInProduct)) {
multiplier *= Integer.parseInt(letterInProduct);
}
}
multipliers.add(multiplier + "");
}
System.out.println("Multiplier set: " + multipliers);
//combine duplicate definitions
int indexOfMultiplier = 0;
while(!definitionsDuplicate.isEmpty()) {
//sum of the constant and its duplicates to combine terms
int constantSum = Integer.parseInt(multipliers.get(indexOfMultiplier++));
String definition = definitionsDuplicate.remove(0);
//check for duplicates, add them to sum
while(definitionsDuplicate.contains(definition)) {
constantSum += Integer.parseInt(multipliers.get(definitionsDuplicate.indexOf(definition)));
definitionsDuplicate.remove(definitionsDuplicate.indexOf(definition));
}
//ignore constant if 1
if(constantSum != 1)
terms.add(constantSum + definition);
else
terms.add(definition);
}
System.out.println("Terms Set: " + terms);
//Format equation
String reducedEquation = "";
for(String term : terms) {
reducedEquation += term + " + ";
}
if(reducedEquation.length() > 1) {
reducedEquation = reducedEquation.substring(0, reducedEquation.length() - 2);
}
System.out.println("Reduced Equation: " + reducedEquation);
//cleanup
scan.close();
}
}
So I have here my code implementing Three Address Code in arithmetic expression.
class ThreeAddressCode {
private static final char[][] precedence = {
{'/', '1'},
{'*', '1'},
{'+', '2'},
{'-', '2'}
};
private static int precedenceOf(String t)
{
char token = t.charAt(0);
for (int i=0; i < precedence.length; i++)
{
if (token == precedence[i][0])
{
return Integer.parseInt(precedence[i][1]+"");
}
}
return -1;
}
public static void main(String[] args) throws Exception
{
int i, j, opc=0;
char token;
boolean processed[];
String[][] operators = new String[10][2];
String expr="", temp;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter an expression: ");
expr = in.readLine();
processed = new boolean[expr.length()];
for (i=0; i < processed.length; i++)
{
processed[i] = false;
}
for (i=0; i < expr.length(); i++)
{
token = expr.charAt(i);
for (j=0; j < precedence.length; j++)
{
if (token==precedence[j][0])
{
operators[opc][0] = token+"";
operators[opc][1] = i+"";
opc++;
break;
}
}
}
System.out.println("\nOperators:\nOperator\tLocation");
for (i=0; i < opc; i++)
{
System.out.println(operators[i][0] + "\t\t" + operators[i][1]);
}
//sort
for (i=opc-1; i >= 0; i--)
{
for (j=0; j < i; j++)
{
if (precedenceOf(operators[j][0]) > precedenceOf(operators[j+1][0]))
{
temp = operators[j][0];
operators[j][0] = operators[j+1][0];
operators[j+1][0] = temp;
temp = operators[j][1];
operators[j][1] = operators[j+1][1];
operators[j+1][1] = temp;
}
}
}
System.out.println("\nOperators sorted in their precedence:\nOperator\tLocation");
for (i=0; i < opc; i++)
{
System.out.println(operators[i][0] + "\t\t" + operators[i][1]);
}
System.out.println();
for (i=0; i < opc; i++)
{
j = Integer.parseInt(operators[i][1]+"");
String op1="", op2="";
if (processed[j-1]==true)
{
if (precedenceOf(operators[i-1][0]) == precedenceOf(operators[i][0]))
{
op1 = "t"+i;
}
else
{
for (int x=0; x < opc; x++)
{
if ((j-2) == Integer.parseInt(operators[x][1]))
{
op1 = "t"+(x+1)+"";
}
}
}
}
else
{
op1 = expr.charAt(j-1)+"";
}
if (processed[j+1]==true)
{
for (int x=0; x < opc; x++)
{
if ((j+2) == Integer.parseInt(operators[x][1]))
{
op2 = "t"+(x+1)+"";
}
}
}
else
{
op2 = expr.charAt(j+1)+"";
}
System.out.println("t"+(i+1)+" = "+op1+operators[i][0]+op2);
processed[j] = processed[j-1] = processed[j+1] = true;
}
}
}
Sample Output
Input : a * b / c
t1 = a * b
t2 = t1 / c
What the program does is evaluate the arithmetic expression and shows them step by step by operators.
Can you help me to include parenthesis in the priorities? and achieve an output like this
Sample Output
Input : a * ( b + c )
t1 = b + c
t2 = a * t2
Right now, the parenthesis is treated like an operand.
I did not use any of your code. Sorry.
This was a fun one to think about. I have never considered how you would do something like this. It does not follow all of the best practices to a "T", but the question inspired me to consider how you would do this in a rudimentary way.
You could make much of this code smaller by using more Java Frameworks, but it was enjoyable to strictly try to work this out logically.
This code is missing most validation (i.e. The user inputs an erroneous expression)
It does however check if there are an equal number of open and close parenthesis.
Lastly, I had to wrap things up so I did not extend into expressions with nested parenthesis.
Example a * ( b * ( c / d ) - e ) >> this code does not handle this scenario, and would have to be enhanced to accommodate for this.
Otherwise, it should give a pretty good idea as to one way you could go about building a program to work through parenthesis.
I hope it helps
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MathPriority {
public static void main(String[] args) {
String expression = "a * (b * c) + (d / e)"; //You can work out how you want input to com in
List<String> priorityList = getPriorityList(expression);//Find parenthesis and sets priority.
expression = expression.replace(" ", "").replace("(", "").replace(")", "");//Take out any spaces and parenthesis
for (int i = 0; i < priorityList.size(); i++) {//Replaces the piece in parenthesis with var and outputs var
expression = expression.replace(priorityList.get(i), "t" + (i + 1));
System.out.println("t" + (i + 1) + " = " + priorityList.get(i));
}
System.out.println("t" + (priorityList.size() + 1) + " = " + expression);//pushes final variable set
}
//You can use this to build a List of indexes of a character within a String
public static List<Integer> getAllOccurencesOfChar(List<String> expression, String indexO) {
List<Integer> parIndexList = new ArrayList<>();
for (int i = 0; i < expression.size(); i++) {
if (expression.get(i).contains(indexO)) {
if (!parIndexList.contains(i) && i > 0) {
parIndexList.add(i);
}
}
}
return parIndexList;
}
//Outputs a list of substrings. They can later be used to parse through the inital string
public static List<String> getPriorityList(String expression) {
List<String> priorityList = new ArrayList<>();
expression = expression.replace(" ", "");
String[] eParts = expression.split("");
List<String> expressionParts = new ArrayList<>();//Get expression into single chars
for (String e : eParts) {//If you change this to an Array.List, it will not work. This type of list is fixed in size
expressionParts.add(e);
}
List<Integer> parIndexList = getAllOccurencesOfChar(expressionParts, "(");//find all open paranthesis
List<Integer> rParIndexList = getAllOccurencesOfChar(expressionParts, ")");//find all close paranthesis
if (parIndexList.size() != rParIndexList.size()) {
System.out.println("Your Equation does not have an equal number of open and close parenthesis");
System.exit(0);
}
//Work out the parenthesis
int loopIterator = parIndexList.size();//This will change as we iterate
for (int pars = loopIterator - 1; pars >= 0; pars--) {
int start = parIndexList.get(pars); //Define a start
int end = 0; //and End
//int end = rParIndexList.get(pars);
for (int contemplate = 0; contemplate < loopIterator; contemplate++) {//contemplate where given parenthesis starts and where its closing tag is
if (parIndexList.get(pars) < rParIndexList.get(contemplate)) {
end = rParIndexList.get(contemplate);//find first occurence and set true end
break;//then stop
}
}
String expre = "";
for (int concat = start + 1; concat < end; concat++) {
expre += expressionParts.get(concat);//put the priorityList's subExpression together
}
priorityList.add(expre);//add that subExpression to the list
expressionParts.subList(start, end + 1).clear();//remove these expressionParts
/*Re-establish where the parenthesis are, since we removed parts of the expression in the list*/
parIndexList = getAllOccurencesOfChar(expressionParts, "(");//find all open paranthesis
rParIndexList = getAllOccurencesOfChar(expressionParts, ")");//find all close paranthesis
loopIterator = parIndexList.size();//resize the forLoop
}
return priorityList;
}
public static List<Integer> getStartEndPosition(String fullExpression, String subExpression) {
List<Integer> sAndE = new ArrayList<>();
String[] eParts = subExpression.split("");
List<String> wordParts = new ArrayList<>();
wordParts.addAll(Arrays.asList(eParts));
/*Find multiples of same operand*/
List<Integer> add = getAllOccurencesOfChar(wordParts, "+");
List<Integer> subtract = getAllOccurencesOfChar(wordParts, "-");
List<Integer> divide = getAllOccurencesOfChar(wordParts, "/");
List<Integer> multiply = getAllOccurencesOfChar(wordParts, "*");
/*Find single Operands*/
int plus = subExpression.indexOf("+");
int minus = subExpression.indexOf("-");
int div = subExpression.indexOf("/");
int mult = subExpression.indexOf("*");
int multiOperands = plus + minus + div + mult;//See if multiples exist
int startingPosition = 0;
if (add.size() > 1 || subtract.size() > 1 || divide.size() > 1 || multiply.size() > 1
|| multiOperands > 0) {
//expression has multiple opreands of different types
String findStart = wordParts.get(0) + wordParts.get(1);
String findEnd = wordParts.get(wordParts.size() - 2) + wordParts.get(wordParts.size() - 1);
startingPosition = fullExpression.indexOf(findStart);
sAndE.add(startingPosition);
int endPosition = fullExpression.indexOf(findEnd);
sAndE.add(endPosition);
} else {
startingPosition = fullExpression.indexOf(subExpression);
sAndE.add(startingPosition);
sAndE.add(startingPosition + subExpression.length());
}
return sAndE;
}
}
String expression = "a * (b * c) + (d / e)"
Outputs:
t1 = d/e
t2 = b*c
t3 = a*t2+t1
I'm having some trouble with some code for a program I'm writing. The purpose of this program is to take a word from a separate text file, scramble it ten times, and display the scrambled letters of the word. The problem that I'm having is that I'm unsure as to how I would go about scrambling the letters ten times. I know that the actual scrambling takes place in my mixer method but the how eludes me. I thought about using a for loop but I'm not sure how to go about it.
import java.io.*;
import java.util.*;
public class Scrambler {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("words.txt"));
String text = input.next();
System.out.println("Original Word: " + text);
System.out.println();
System.out.println("Scrambled Word:");
System.out.println("********");
separate(text);
System.out.println("********");
}
public static void separate(String text) {
System.out
.println(" " + text.charAt(0) + " " + text.charAt(1) + " ");
System.out.println(text.charAt(2) + " " + text.charAt(3));
System.out
.println(" " + text.charAt(4) + " " + text.charAt(5) + " ");
}
public static String mixer(String text) {
Random r = new Random();
int r1 = r.nextInt(text.length());
int r2 = r.nextInt(text.length());
String a = text.substring(0, r1);
char b = text.charAt(r1);
String c = text.substring(r1 + 1, r2);
char d = text.charAt(r2);
String e = text.substring(r2 + 1, text.length());
text = a + b + c + d + e;
return text;
}
}
Your mixer() is not working properly. I would first make the string into an char[], and then retrieve 2 random indices and switch the characters in these indices.
char[] stringasarray = text.toCharArray();
int length = text.length;
for(int i=0; i<length; i++){
int letter1 = rnd.nextInt(length);
int letter2 = rnd.nextInt(length);
char temp = stringasarray[letter1];
stringasarray[letter1] = stringasarray[letter2];
stringasarray[letter2] = temp;
}
String newtext = new String(stringasarray);
A simple for loop would do it:
String word = "Hello World";
for(int i = 0; i < 10; i++){
word = mixer(word);
}
Here is one approach for scrambling the string(s) ten times;
// Passing in the Random.
public static String mixer(String in, Random rnd) {
StringBuilder sb = new StringBuilder();
if (in != null) { // <-- check for null.
List<Character> chars = new ArrayList<Character>();
for (char ch : in.toCharArray()) {
chars.add(ch); // <-- add each character to the List.
}
Collections.shuffle(chars, rnd); // <-- "scramble"
for (char ch : chars) {
sb.append(ch);
}
}
return sb.toString();
}
public static void main(String[] args) {
String t = "Hello";
Random rnd = new Random();
// I'm not sure why you want to do it 10 times, but here is one way.
for (int i =0; i < 10; i++) {
t = mixer(t, rnd); // <-- call mixer function.
}
System.out.println(t);
}
public static String mixer(String text) {
Random r = new Random();
int r1 = r.nextInt(text.length()); // generates a random number from 0 to text.length - 1
int r2 = r.nextInt(text.length()); //generates a random number from 0 to text.length - 1
String a = text.substring(0, r1); // creates a substring containing characters from 0 to r1
char b = text.charAt(r1); //grabs the character at r1
String c = text.substring(r1 + 1, r2); // creates a substring from r1+1 to r2
char d = text.charAt(r2); // grabs the character at r2
String e = text.substring(r2 + 1, text.length()); // grabs any remaining characters
text = a + b + c + d + e; // recombines them
return text;
}
without delving into how substring works, this would most likely return the exact same string. If you changed the order of a + b + c + d + e it would scramble it. It takes the word and divides it into five pieces, then reassembles it.
It could probably use a lot of error checking, however, and some validation.
I have written this code to generate the bit stream corresponding to string a and then invert
specific bits in a bit stream.the variable cc gets an integer value in the processing before the code snippet.
However it gives Array Index Out Of Bounds Exception on the following line.
if(sb2.charAt(cc)=='1')
can anyone tell me what is the probable cause?
package abc1;
import java.util.Scanner;
public class abc2 {
public static void main(String s[]) {
String seckey = " ";
String cbs = " ";
String a = "Manikaparasher";
System.out.println("String originally:" + a);
char[] car = a.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : car) {
cbs = Integer.toBinaryString((int) c);
sb.append(cbs);
}
Scanner sc = new Scanner(System.in);
System.out.println(" Enter your passkey ");
int n = sc.nextInt();
int ul, ll;
double nv1, nv2, ns;
ll = n * 3;
ul = n * 7;
nv1 = ll + (Math.random() * (ul - ll));
nv2 = ll + (Math.random() * (ul - ll));
int nv11 = (int) nv1 % 7; //inversion bit
int nv22 = (int) nv2 % 3; //embedding bit
ns = ll + (Math.random() * (ul - ll));
int ns1 = (int) ns % 5;//start bit
if (nv11 == nv22) {
nv11++;
}
if (nv22 == ns) {
ns++;
}
if (nv11 == ns) {
nv11++;
}
seckey = "I" + nv11 + "E" + nv22 + "S" + ns1;
System.out.println(seckey);
System.out.println("old" + sb.toString());
System.out.println("nv11" + nv11);
StringBuilder sb2 = new StringBuilder(sb);
int cc = 0;
while (!cbs.isEmpty()) {
cc = cc + nv11;
if (sb2.charAt(cc) == '1') {
sb2.setCharAt(cc, '0');
sb2.append(sb);
} else {
sb2.setCharAt(cc, '1');
sb2.append(sb);
}
}
System.out.println("new" + sb2.toString());
}
}
You haven't put anything inside sb2 variable before calling
if(sb2.charAt(cc)=='1')
and what ever the cc value, it exceeds the sb2.length() size.
What this program is trying to do is go through numbers starting at "000000" going all the way up to "999999" and trying to find numbers which are palindromes. (eg: 0000000000).
I am having trouble with reversing the string and creating a valid result. The system adds the next 4 numbers creating a length 10 string.
import java.util.Arrays;
public class TestPalindrome{
public static void main(String []args){
int[] intArray = new int[6];
String[] strArray = new String[99];
String nextString;
int count = 0;
int nextnum;
int thisnum;
String thisString = "";
String s = "000000";
nextString = s;
do {
for(int i=0;i<6;i++) {
intArray[i] = Integer.parseInt(String.valueOf(nextString.charAt(i)));
}
int pos1 = intArray[5];
int pos2 = intArray[4]*10;
int pos3 = intArray[3]*100;
int pos4 = intArray[2]*1000;
int pos5 = intArray[1]*10000;
int pos6 = intArray[0]*100000;
nextnum = (pos1 + 1) + pos2 + pos3 + pos4 + pos5 + pos6;
thisnum = pos1 + pos2 + pos3 + pos4 + pos5 + pos6;
// If any of below values = 10, then number is not used
int d7 = ((4*intArray[0])+(10*intArray[1])+(9*intArray[2])+(2*intArray[3])+intArray[4]+(7*intArray[5])) % 11;
int d8 = ((7*intArray[0])+(8*intArray[1])+(7*intArray[2])+(intArray[3])+9*intArray[4]+(6*intArray[5])) % 11;
int d9 = ((9*intArray[0])+(intArray[1])+(7*intArray[2])+(8*intArray[3])+7*intArray[4]+(7*intArray[5])) % 11;
int d10 = ((intArray[0])+(2*intArray[1])+(9*intArray[2])+(10*intArray[3])+4*intArray[4]+(intArray[5])) % 11;
if (d7==10) { }
else if (d8==10) { }
else if (d9==10) { }
else if (d10==10) { }
else {
String s7 = Integer.toString(d7);
String s8 = Integer.toString(d8);
String s9 = Integer.toString(d9);
String s10 = Integer.toString(d10);
thisString = String.format("%06d", thisnum);
String concat = thisString + s7 + s8 + s9 + s10;
StringBuilder input = new StringBuilder(concat);
StringBuilder value = input.reverse();
if( value == input){
System.out.println("" + concat);
strArray[count] = concat;
count = count+1;
}
else {}
}
nextString = String.format("%06d", nextnum);
}
while (nextnum < 1000000 && nextnum > 000000);{
}
}
}
The problem is that it displays all numbers and not just palindromes. Any help is very welcomed.
I would simply put the numbers into strings. Then reverse the string and see if it equals the original.
String originalString = "110011";
String newString = new StringBuilder(originalString ).reverse().toString();
if (originalString.equals(newString )) {
//Is a palindrome
}
Note: Consider how you want to handle leading zeros. "11" is a palindrome, but if you need 4 values then "0011" is not.
One funny way is to use just one for-loop :
public static void main(String [] args){
for(String s = "000000"; !s.equals("1000000"); s = String.format("%06d",Integer.parseInt(s)+1)){
if(new StringBuilder(s).reverse().toString().equals(s))
System.out.println(s);
}
}