I can't open the jar file of the project - java

I have a project that I need to have its jar file , but it doesn't open , can anyone help me please, I need it as soon as possible for my university . And here is the whole code :
package huffmanproject;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class huffmanproject {
public static class HuffNode implements Comparable<HuffNode> {
public int value;
public int weight;
public HuffNode leftTree;
public HuffNode rightTree;
public HuffNode parent;
public HuffNode() {
parent = null;
}
public HuffNode( int v, int w, HuffNode lTree, HuffNode rTree, HuffNode par ) {
value = v;
weight = w;
leftTree = lTree;
rightTree = rTree;
parent = par;
}
#Override
public int compareTo(HuffNode rhs) {
return weight - rhs.weight;
}
#Override
public String toString() {
String str = "";
str += this.value;
return str;
}
}
public static class HuffTree {
private int size = 0;
private HuffNode root = new HuffNode();
private PriorityQueue<HuffNode> huffQueue = new PriorityQueue();
public ArrayList<String> pathTable = new ArrayList();
public ArrayList<Character> valueTable = new ArrayList();
public HuffTree(int[] freq, char[] code) {
this.size = freq.length;
if (freq.length != code.length) {
throw new UnsupportedOperationException("Error: Character and code length mismatch.");
}
for (int i = 0; i < this.size; i++) {
huffQueue.offer(new HuffNode(code[i], freq[i], null, null, null));
}
createTree();
createTable(this.root, "");
}
private void createTree() {
while (huffQueue.size() > 1) {
HuffNode tempL = huffQueue.poll();
HuffNode tempR = huffQueue.poll();
HuffNode parent = new HuffNode(0, tempL.weight+tempR.weight, tempL, tempR, null);
tempL.parent = parent;
tempR.parent = parent;
huffQueue.offer(parent);
this.size++;
}
this.root = huffQueue.peek();
}
private void createTable(HuffNode curr, String str) {
if (curr == null) return;
if (curr.leftTree == null && curr.rightTree == null) {
char tempChar;
if (curr.value == 32)
tempChar = ' ';
if (curr.value == 10)
tempChar = 'n';
else
tempChar = (char)curr.value;
this.valueTable.add(tempChar);
this.pathTable.add(str);
}
str += "0";
createTable(curr.leftTree, str);
str = str.substring(0, str.length()-1);
str += "1";
createTable(curr.rightTree, str);
}
String tacks = "";
public void getTree(HuffNode curr) {
if (curr == null) return;
if (curr.leftTree == null && curr.rightTree == null) {
switch (curr.value) {
case 32:
System.out.println(tacks + curr.weight + ": sp");
break;
case 10:
System.out.println(tacks + curr.weight + ": nl");
break;
default:
System.out.println(tacks + curr.weight + ": " + (char)curr.value);
break;
}
}
else
System.out.println(tacks + curr.weight);
tacks += "- ";
getTree(curr.leftTree);
getTree(curr.rightTree);
tacks = tacks.substring(0, tacks.length()-2);
}
public int getSize() { return this.size; }
public String encode(String input){
String str = "";
for (int x = 0; x < input.length(); x++) {
for (int i = 0; i < valueTable.size(); i++) {
if (valueTable.get(i) == input.charAt(x))
str += pathTable.get(i);
}
}
return str;
}
public String decode(String bits) {
String decodedStr = "";
for (int i = 0; i < bits.length(); i++) {
if (!getChar(bits.substring(0, i+1)).equals("")) {
decodedStr += getChar(bits.substring(0, i+1));
bits = bits.substring(i+1);
i = 0;
}
}
return decodedStr;
}
private String getChar(String bits) {
String character = "";
for (int i = 0; i < pathTable.size(); i++) {
if (pathTable.get(i).equals(bits))
character = valueTable.get(i).toString();
}
return character;
}
}
public static void main(String[] args) {
// for example assume that we have these letters with these different frequencies like below:
int freq[] = {10, 15, 12, 3, 4, 13, 1};
char code[] = {'a', 'e', 'i', 's', 't', ' ', '\n'};
HuffTree hTree = new HuffTree(freq, code);
System.out.println("Display Tree:");
HuffNode curr = hTree.root;
hTree.getTree(curr);
System.out.println("");
// and we want to build the huffman tree of the word sea :
System.out.println("Encode 'sea': " + hTree.encode("sea") +"\n");
System.out.println("Decode '" + hTree.encode("sea") + "': " + hTree.decode(hTree.encode("tea")));
}
}

If it's simply not compiling into a jar file, try the following command in command prompt or terminal.
jar cf jar-file input-file(s)
From Oracle: Creating jar File
To open command prompt, use WIN+R to open the run box, type cmd, and press enter.
navigate to the directory of your java file:
cd C:\Path\to\my\java\file\HuffNode.java
run the command:
jar cf HuffNode.jar HuffNode.java
If you have multiple .java files:
jar cf HuffNode.jar File1.java File2.java File3.java

Related

Why am I getting an out of bounds exception error?

I am currently working on a project and I have finally finished writing my code but for some reason I am getting a lot of errors and I am not sure where they are. I know it is frowned upon for posting the whole code here, I am working on Java and it is very difficult for me to find errors on Java. My project partner has never been helpful. I am the only one carrying the burden.
Here is my code
public class Main {
public static int Statement_Number = 1;
public static String Current_Statement;
public static int i = 0; //Index for Script
public static int j = 0; //Index for Statements
public static String Missing_Word;
public static ArrayList<String> Letters_of_the_missing_word = new ArrayList<String>();
public static char WhiteSpace = ' ';
public static String Movie_Script;
public static char Missing_Word_Characters[] = new char[20];
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int count = 0;
int length = 0; //Length to compute LPS
char Underscore = '_';
ArrayList<String> Statements_List = new ArrayList<String>();
boolean word_missing = false;
BufferedReader Statements = new BufferedReader(new FileReader("C:\\Users\\hasan\\Desktop\\Programming\\Java Programs\\Analysis of Algorithms Project\\term_project\\statements.txt"));
BufferedReader Script = new BufferedReader(new FileReader("C:\\Users\\hasan\\Desktop\\Programming\\Java Programs\\Analysis of Algorithms Project\\term_project\\the_truman_show_script.txt"));
Movie_Script = Script.readLine();
int Script_Length = Movie_Script.length();
//System.out.println(Script_Length); //81,902
//System.out.println(Movie_Script);
while((Current_Statement = Statements.readLine()) != null)
{
Statements_List.add(Current_Statement);
int Current_Statement_length = Current_Statement.length();
for(Statement_Number = 0; Statement_Number < 6; Statement_Number++)
{
//System.out.println(Statements_List.get(i));
Current_Statement = Statements_List.get(Statement_Number);
System.out.println(Statement_Number + ". " + Current_Statement);
KMPSearch(Current_Statement, Movie_Script);
}
}
}
static void KMPSearch(String Current_Statement, String Movie_Script)
{
int Current_Statement_Length = Current_Statement.length();
int Movie_Script_Length = Movie_Script.length();
int lps[] = new int[Current_Statement_Length];
int j = 0; //Index for Current_Statement
char Underscore = '_';
Calculating_LPS_Array(Current_Statement, Current_Statement_Length, lps);
int i = 0;
while(i < Movie_Script_Length)
{
if(Current_Statement.charAt(j) == Movie_Script.charAt(i))
{
i++;
j++;
}
else if(Current_Statement.charAt(j) != Movie_Script.charAt(i) && Current_Statement.charAt(j) == Underscore)
{
//Replace the underscores with the word
Word_Getter();
String New_Statement = Current_Statement.replaceAll("___", Missing_Word);
System.out.println(New_Statement);
System.out.println("");
}
else if(i < Movie_Script_Length && Current_Statement.charAt(j) != Movie_Script.charAt(i))
{
if(j != 0)
{
j = lps[j - 1];
}
else
{
i = i + 1;
}
}
}
if(i == Movie_Script_Length)
{
System.out.println("STATEMENT NOT FOUND");
}
}
static void Calculating_LPS_Array(String Current_Statement, int Current_Statement_Length, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0;
while(i < Current_Statement_Length)
{
if(Current_Statement.charAt(i) == Current_Statement.charAt(len))
{
len++;
lps[i] = len;
i++;
}
else //Current_Statement.charAt(i) != Current_Statement.charAt(len)
{
if(len != 0)
{
len = lps[len - 1];
}
else
{
lps[i] = len;
i++;
}
}
}
}
static void Word_Getter()
{
if(Movie_Script.charAt(j) != WhiteSpace)
{
Movie_Script.getChars(j, WhiteSpace, Missing_Word_Characters, 0);
j++;
Missing_Word = new String(Missing_Word_Characters);
}
}
}
Here are the errors that I am getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
offset 0, count 32, length 20 at
java.base/java.lang.String.checkBoundsOffCount(String.java:3304) at
java.base/java.lang.String.getChars(String.java:855) at
Main.Word_Getter(Main.java:142) at Main.KMPSearch(Main.java:85) at
Main.main(Main.java:57)
Your help would be much appreciated, thank you in advance.
You just need to change the size of your Array :
public static char Missing_Word_Characters[] = new char[32];

Running 2 java codes

I have 2 java programs (ciphers), one is Playfair and second is Transposition.
Now i want to run Playfair code, then right after that compile Transposition using the result i got from Playfair code. How should i make this?(
Playfair code
import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
and Transposition
import java.util.*;
import java.util.Scanner; // needed for Scanner
public class transpositionCipher
{
public static void main(String args[])
{
String key;
String message;
String encryptedMessage;
// Letters in the x-axis
int x=0;
// Letters in the y-axis
int y=0;
// Prompt the user
System.out.print( "Type your Key : " );
// Read a line of text from the user.
Scanner scan = new Scanner(System.in);
key = scan.nextLine();
// Display the input back to the user.
System.out.println( "Your Key is " + key );
//Prompt the user
System.out.print( "Type your Message : " );
//Read a line of text from the user.
message = scan.nextLine();
//Display the input back to the user.
System.out.println( "Your Message is " + message );
int msgchar = message.length();
int keycahr = key.length();
if (!((msgchar % keycahr) == 0)){
do{
message = message + "x";
msgchar = message.length();
}while(!((msgchar % keycahr) == 0));
}
encryptedMessage = "";
// To set the temp as [x][y]
char temp[][]=new char [key.length()][message.length()];
char msg[] = message.toCharArray();
// To populate the array
x=0;
y=0;
// To convert the message into an array of char
for (int i=0; i< msg.length;i++)
{
temp[x][y]=msg[i];
if (x==(key.length()-1))
{
x=0;
y=y+1;
} // Close if
else
{
x++;
}
} // Close for loop
// To sort the key
char t[]=new char [key.length()];
t=key.toCharArray();
Arrays.sort(t);
for (int j=0;j<y;j++)
{
for (int i=0;i<key.length();i++)
{
System.out.print(temp[i][j]);
}
System.out.println();
}
System.out.println();
// To print out row by row (i.e. y)
for (int j=0;j<y;j++){
// To compare the the sorted Key with the key
// For char in the key
for (int i=0;i<key.length();i++){
int pos=0;
// To get the position of key.charAt(i) from sorted key
for (pos=0;pos<t.length;pos++){
if (key.charAt(i)==t[pos]){
// To break the for loop once the key is found
break;
}
}
System.out.print(temp[pos][j]);
encryptedMessage+=temp[pos][j];
}
System.out.println();
}
System.out.println(encryptedMessage);
System.exit(0);
}enter code here
}
Take the output of one operation (PlayfairCipher.encode), which is the cyphertext and input it to the second operation (your transpositionial code) as it's plaintext.
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
PlayfairCipher.createTable(key, changeJtoI);
String enc = PlayfairCipher.encode(prepareText(txt, changeJtoI));
//Now instead of using 'message' for the second encryption, you use the output of the first operation 'enc'
int x=0;
int y=0;
int msgchar = enc.length();
int keycahr = key.length();
if (!((msgchar % keycahr) == 0)){
do{
enc = enc + "x";
msgchar = enc.length();
}while(!((msgchar % keycahr) == 0));
}
...

Sort String s2 using the order of String s1 using either of comparable or comparator interface

i have two strings s1 and s2 and i would like to sort s2 based on the order of appearance of letters in s1 and if other alphabets are left in s2 sort them alphabetically.
Assume i have the following;
String s1 = "war";
String s2 = "Its awesome being a programmer";
output: waaarrrIbeeeeggimmmnoopsst.
I have written a code to do that already though buut i was wondering if its possible using the comparator/comparable interface to solve it.
Listed below is my code snippet.
public class Sort {
private static String a = "war";
private static String b = "Its awesome being a programmer";
static List<Character> list = new ArrayList<>();
static public void main(String[] args) {
Character s;
Character x;
System.out.println("String to be sorted: '" + b + "'");
System.out.println("Key for sort: '" + a + "'");
/*
* put all the string in a list
*/
for (int i = 0; i < b.length(); i++) {
s = b.charAt(i);
if (s != ' ') {
list.add(s);
}
}
/*
* compare individual chac in key with individaul char in string to sort
*/
StringBuilder sb = new StringBuilder();
for (int j = 0; j < a.length(); j++) {
x = a.charAt(j);
for (int k = 0; k < b.length(); k++) {
s = b.charAt(k);
if (x == s) {
sb.append(s);
list.remove(x);
}
}
}
/*
* check if list is empty if not, sort and append the rest to the stringbuilder
*/
if (!list.isEmpty()) {
Collections.sort(list);
for (char c : list) {
sb.append(c);
}
}
System.out.println("Sorted version of string: '" + sb.toString() + "'");
}
}
private static String a = "war";
private static String b = "Its awesome being a programmer".replace(" ","");
private static String answer = "waaarrrIbeeeeggimmmnoopsst";
public static void main(String[] args) {
List<String> characters = new ArrayList<String>(b.length());
for (int i=0;i<b.length();i++){
characters.add(String.valueOf(b.charAt(i)));
}
Collections.sort(characters,new CompareIt(a));
String sortedString = listToString(characters);
System.out.println(sortedString);
System.out.println(answer);
System.out.println(answer.equals(sortedString));
}
private static String listToString(List<String> listOfStrings){
StringBuilder builder = new StringBuilder();
for (String str : listOfStrings){
builder.append(str);
}
return builder.toString();
}
private static class CompareIt implements Comparator<String>{
private final String source;
public CompareIt(String source) {
super();
this.source = source;
}
public int compare(String o1, String o2) {
int i1 = source.indexOf(o1);
int i2 = source.indexOf(o2);
if (i1==-1 && i2!=-1){
return 1;
} else if (i1!=-1 && i2==-1){
return -1;
} else if (i1!=-1 && i2!=-1){
return i1 > i2 ? 1:-1;
} else {
return o1.compareTo(o2);
}
}
}
This seems to work.
EDITED: To include sysout that result matches expected answer provided in question.
EDIT2: Typo with final indexed comparison I had ? 1:0 instead of 1:-1.
public static void main(String[] args) {
String s1 = "war";
String s2 = "Its awesome being a programmer";
String result = "";
for (int i = 0; i < s1.length(); i++) {
int len = s2.length()
- s2.replace(String.valueOf(s1.charAt(i)), "").length();
s2 = s2.replace(String.valueOf(s1.charAt(i)), "").replace(" ", "");
for (int j = 0; j < len; j++)
result = result + String.valueOf(s1.charAt(i));
}
char[] remaining = s2.toCharArray();
Arrays.sort(remaining);
for (Character c : remaining)
result = result + String.valueOf(c);
System.out.println(result);
}
Try this: I tried without using any interface.
Output:
waaarrrIbeeeeggimmmnoopsst
public static Comparator<Character> compareOn(final String key) {
return new Comparator<Character>() {
public int compare(Character c1, Character c2) {
final int indexInKey1 = key.indexOf(c1);
final int indexInKey2 = key.indexOf(c2);
final int result;
if (indexInKey1 == -1 && indexInKey2 == -1) {
result = c1.compareTo(c2); //fall back to natural ordering
} else {
if (indexInKey1 == -1) {
result = 1;
} else if (indexInKey2 == -1) {
result = -1;
} else {
result = indexInKey1 - indexInKey2;
}
}
return result;
}
};
}
public static void main(String[] args) {
final String a = "war";
final String b = "Its awesome being a programmer";
final List<Character> chars = new ArrayList<Character>();
for (char c: b.toCharArray()) {
if (c != ' ') {
chars.add(c);
}
}
Collections.sort(chars, compareOn(a));
System.out.println(chars);
}

Counting distinct words V2 [duplicate]

This question already has an answer here:
Counting distinct words with Threads
(1 answer)
Closed 9 years ago.
I've asked this question before ( Counting distinct words with Threads ) and made the code more appropriate. As described in first question I need to count the distinct words from a file.
De-Bug shows that all my words are stored and sorted correctly, but the issue now is an infinite "while" loop in the Test class that keeps on going after reading all the words (De-bug really helped to figure out some points...).
I'm testing the code on a small file now with no more than 10 words.
DataSet class has been modified mostly.
I need some advice how to get out of the loop.
Test looks like this:
package test;
import java.io.File;
import java.io.IOException;
import junit.framework.Assert;
import junit.framework.TestCase;
import main.DataSet;
import main.WordReader;
public class Test extends TestCase
{
public void test2() throws IOException
{
File words = new File("resources" + File.separator + "test2.txt");
if (!words.exists())
{
System.out.println("File [" + words.getAbsolutePath()
+ "] does not exist");
Assert.fail();
}
WordReader wr = new WordReader(words);
DataSet ds = new DataSet();
String nextWord = wr.readNext();
// This is the loop
while (nextWord != "" && nextWord != null)
{
if (!ds.member(nextWord))
{
ds.insert(nextWord);
}
nextWord = wr.readNext();
}
wr.close();
System.out.println(ds.toString());
System.out.println(words.toString() + " contains " + ds.getLength()
+ " distinct words");
}
}
Here is my updated DataSet class, especially member() method, I'm still not sure about it because at some point I used to get a NullPointerExeption (don't know why...):
package main;
import sort.Sort;
public class DataSet
{
private String[] data;
private static final int DEFAULT_VALUE = 200;
private int nextIndex;
private Sort bubble;
public DataSet(int initialCapacity)
{
data = new String[initialCapacity];
nextIndex = 0;
bubble = new Sort();
}
public DataSet()
{
this(DEFAULT_VALUE);
nextIndex = 0;
bubble = new Sort();
}
public void insert(String value)
{
if (nextIndex < data.length)
{
data[nextIndex] = value;
nextIndex++;
bubble.bubble_sort(data, nextIndex);
}
else
{
expandCapacity();
insert(value);
}
}
public int getLength()
{
return nextIndex + 1;
}
public boolean member(String value)
{
for (int i = 0; i < data.length; i++)
{
if (data[i] != null && nextIndex != 10)
{
if (data[i].equals(value))
return true;
}
}
return false;
}
private void expandCapacity()
{
String[] larger = new String[data.length * 2];
for (int i = 0; i < data.length; i++)
{
data = larger;
}
}
}
WordReader class didn't change much. ArrayList was replaced with simple array, storing method also has been modified:
package main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class WordReader
{
private File file;
private String[] words;
private int nextFreeIndex;
private BufferedReader in;
private int DEFAULT_SIZE = 200;
private String word;
public WordReader(File file) throws IOException
{
words = new String[DEFAULT_SIZE];
in = new BufferedReader(new FileReader(file));
nextFreeIndex = 0;
}
public void expand()
{
String[] newArray = new String[words.length * 2];
// System.arraycopy(words, 0, newArray, 0, words.length);
for (int i = 0; i < words.length; i++)
newArray[i] = words[i];
words = newArray;
}
public void read() throws IOException
{
}
public String readNext() throws IOException
{
char nextCharacter = (char) in.read();
while (in.ready())
{
while (isWhiteSpace(nextCharacter) || !isCharacter(nextCharacter))
{
// word = "";
nextCharacter = (char) in.read();
if (!in.ready())
{
break;
}
}
word = "";
while (isCharacter(nextCharacter))
{
word += nextCharacter;
nextCharacter = (char) in.read();
}
storeWord(word);
return word;
}
return word;
}
private void storeWord(String word)
{
if (nextFreeIndex < words.length)
{
words[nextFreeIndex] = word;
nextFreeIndex++;
}
else
{
expand();
storeWord(word);
}
}
private boolean isWhiteSpace(char next)
{
if ((next == ' ') || (next == '\t') || (next == '\n'))
{
return true;
}
return false;
}
private boolean isCharacter(char next)
{
if ((next >= 'a') && (next <= 'z'))
{
return true;
}
if ((next >= 'A') && (next <= 'Z'))
{
return true;
}
return false;
}
public boolean fileExists()
{
return file.exists();
}
public boolean fileReadable()
{
return file.canRead();
}
public Object wordsLength()
{
return words.length;
}
public void close() throws IOException
{
in.close();
}
public String[] getWords()
{
return words;
}
}
And Bubble Sort class for has been changed for strings:
package sort;
public class Sort
{
public void bubble_sort(String a[], int length)
{
for (int j = 0; j < length; j++)
{
for (int i = j + 1; i < length; i++)
{
if (a[i].compareTo(a[j]) < 0)
{
String t = a[j];
a[j] = a[i];
a[i] = t;
}
}
}
}
}
I suppose the method that actually blocks is the WordReader.readNext(). My suggestion there is that you use Scanner instead of BufferedReader, it is more suitable for parsing a file into words.
Your readNext() method could be redone as such (where scan is a Scanner):
public String readNext() {
if (scan.hasNext()) {
String word = scan.next();
if (!word.matches("[A-Za-z]+"))
word = "";
storeWord(word);
return word;
}
return null;
}
This will have the same functionality as your code (without using isCharacter() or isWhitespace() - the regex (inside matches())checks that a word contains only characters. The isWhitespace() functionality is built-in in next() method which separates words. The added functionality is that it returns null when there are no more words in the file.
You'll have to change your while-loop in Test class for this to work properly or you will get a NullPointerException - just switch the two conditions in the loop definition (always check for null before, or the first will give a NPE either way and the null-check is useless).
To make a Scanner, you can use a BufferedReader as a parameter or the File directly as well, as such:
Scanner scan = new Scanner(file);

Incrementing the number in a specified sequence

I need a sequence of a Numbers to be generated through incrementing. For Ex if it starts with 001 goes till 999 next no should be A01 again goes till A99 next should be B01. Can anybody help me to write a logic for this. Should be implemented using Java code.
simple and incompleted,
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GenerateProgresId {
private static String[] aChar = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
private static List<String> listA;
public GenerateProgresId() {
List<Number> list3 = new ArrayList<Number>();
List<Integer> list4 = new ArrayList<Integer>();
List<? extends Number> list5 = new ArrayList<Integer>();
List<? extends Number> list6 = list4;
list3.add(Integer.valueOf(333));
list4.add(Integer.valueOf(444));
//list5.add(Integer.valueOf(555)); // compile error
//list6.add(Integer.valueOf(666)); // compile error
Number n3 = list3.get(0);
Integer i4 = list4.get(0);
Number n5 = !list5.isEmpty() ? list5.get(0) : null;
Number n6 = list6.get(0);
System.out.printf("%s, %s, %s, %s%n", n3, i4, n5, n6);
int pomocInt = 1;
String pomocStr = "";
if (pomocInt < 10) {
pomocStr = "0" + pomocInt;
} else if (pomocInt < 100) {
pomocStr = String.valueOf(pomocInt);
} else {
pomocStr = String.valueOf(pomocInt);
}
System.out.println(pomocStr);
pomocInt = 12;
pomocStr = "";
if (pomocInt < 10) {
pomocStr = "0" + pomocInt;
} else if (pomocInt < 100) {
pomocStr = String.valueOf(pomocInt);
} else {
pomocStr = String.valueOf(pomocInt);
}
System.out.println(pomocStr);
pomocInt = 157;
pomocStr = "";
if (pomocInt < 10) {
pomocStr = "0" + pomocInt;
} else if (pomocInt < 100) {
pomocStr = String.valueOf(pomocInt);
} else if (pomocInt > 99) {
pomocStr = String.valueOf(pomocInt);
pomocStr = pomocStr.substring(pomocStr.length() - 2, pomocStr.length());
}
System.out.println(pomocStr);
listA = new ArrayList<String>();
listA.addAll(Arrays.asList(aChar));
System.out.println("From List");
System.out.println(GenerateProgresIdList(null));
System.out.println(GenerateProgresIdList(""));
System.out.println(GenerateProgresIdList("B"));
System.out.println(GenerateProgresIdList("AA"));
System.out.println(GenerateProgresIdList("AZ"));
System.out.println(GenerateProgresIdList("ZY"));
System.out.println(GenerateProgresIdList("ZZ"));
System.out.println("From String[]");
System.out.println(GenerateProgresIdString(null));
System.out.println(GenerateProgresIdString(""));
System.out.println(GenerateProgresIdString("B"));
System.out.println(GenerateProgresIdString("AA"));
System.out.println(GenerateProgresIdString("AZ"));
System.out.println(GenerateProgresIdString("ZY"));
System.out.println(GenerateProgresIdString("ZZ"));
}
public static String GenerateProgresIdList(String str) {
int lastChar = aChar.length - 1;
String retStr = "AA";
if (str != null) {
if (str.length() > 0) {
if (str.length() == 1) {
retStr = str + aChar[0];
} else if (str.length() == 2) {
int stChar = listA.indexOf(str.substring(0, 1));
int ndChar = listA.indexOf(str.substring(1, str.length()));
if ((stChar != lastChar) || (ndChar != lastChar)) {
if (ndChar == lastChar) {
retStr = listA.get(stChar + 1) + listA.get(0);
} else {
retStr = listA.get(stChar) + listA.get(ndChar + 1);
}
}
}
}
}
return retStr;
}
public static String GenerateProgresIdString(String str) {
String lastChar = aChar[aChar.length - 1];
String retStr = "AA";
if (str != null) {
if (str.length() > 0) {
if (str.length() == 1) {
retStr = str + aChar[0];
} else if (str.length() == 2) {
if ((!str.substring(0, 1).equals(lastChar)) || (!str.substring(1, str.length()).equals(lastChar))) {
String pos1 = str.substring(0, 1);
String pos2 = str.substring(1, str.length());
if ((pos2).equals(lastChar)) {
int heplInt = 0;
for (int i = 0; i < aChar.length; i++) {
if (aChar[i].equals(pos1)) {
heplInt = i + 1;
break;
}
}
retStr = aChar[heplInt] + aChar[0];
} else {
int heplInt = 0;
for (int i = 0; i < aChar.length; i++) {
if (aChar[i].equals(pos2)) {
heplInt = i + 1;
break;
}
}
retStr = pos1 + aChar[heplInt];
}
}
}
}
}
return retStr;
}
public static void main(String[] args) {
GenerateProgresId gpi = new GenerateProgresId();
}
}
Try this,
class Foo
{
private static int incr=0;
public static String getNo()
{
incr++;
if(incr%100==0)
incr++;
String no=String.valueOf(incr%100);
String str= String.valueOf((char)('A'+incr/100)) + new String(new byte[]{'0','0'},0,2-no.length()) +
String.valueOf(incr%100);
return str;
}
}
public class Test
{
public static void main(String args[]){
for(int i=1;i<=310;i++){
System.out.println(Foo.getNo());
}
}
}
Here's my (clumsy, yet hopefully correct) attempt:
class Program {
public static void main(String[] args) {
Incrementer inc = new Incrementer();
while (inc.hasNext()) {
System.out.println(inc.getNext());
}
}
}
class Incrementer {
private final static char[] prefixes = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C' };
//all the way to 'Z' if you want, but I'm lazy
private int currentPrefix = 0;
private int currentNumber = 0;
public boolean hasNext() {
if ((currentPrefix == (prefixes.length - 1)) && currentNumber > 99) {
return false;
}
return true;
}
// this may throw ArrayIndexOutOfBoundsException, check hasNext() first
public String getNext() {
String result;
if (currentNumber > 99) {
currentNumber = 1;
currentPrefix++;
}
result = "" + prefixes[currentPrefix];
if (currentNumber <= 9) {
result += "0";
}
result += currentNumber;
currentNumber++;
return result;
}
}
One way to do this would be to make the first character, and the second 2 characters separately.
public SequenceGenerator {
private int lowerTwoDigits;
private char thirdDigit;
public SequenceGenerator () {
lowerTwoDigits = 0;
thirdDigit = '0';
}
public String nextElement() {
lowerTwoDigits++;
if (lowerTwoDigits == 100) {
lowerTwoDigits = 1;
thirdDigit++;
if (thirdDigit == '9' + 1)
thirdDigit = 'A';
}
String result = thirdDigit +
('0' + lowerTwoDigits / 10 ) +
('0' + lowerTwoDigits % 10 );
return result;
}
}
public class Main {
public static void main(String[] args) {
SequenceGenerator s = new SequenceGenerator();
int MAX = 99 * 36;
while (MAX >= 0) {
System.out.println(s.nextElement());
MAX--;
}
}
}
This should do what you are asking for, and I think you can understand what is going on in the nextElement method.
Allocate a batch of 100 numbers in one go and use them and allocate a new batch if the existing batch is exhausted. so something like String getBatchPrefix() which generates 0, "A", "B"... then create an object
class BatchIncrementer {
private final String prefix;
private final AtomicInteger incrementer;
BatchIncrementer(String pPrefix) {
incrementer = new AtomicInteger();
prefix = pPrefix;
}
Integer getNext() {
return incementer.getAndIncrement();
}
Boolean hasNext() {
return incrementer.get() < 100;
}
}
Here is a simple Alphabetic incrementor, im sure you can figure out the rest :-)
public static String incrementAlphabetic(String value, int position) {
value = value.toUpperCase();
char c = value.charAt(position);
c++;
boolean next = false;
if (c > 'Z') {
next = true;
c = 'A';
}
String n = value.substring(0, position)
+ String.valueOf(c)
+ value.substring(position + 1, value.length());
return (next && position > 0) ? incrementAlphabetic(n, position - 1) : n;
}
public static void main(String[] args) {
String start = "A";
for (int i = 0; i < 1000; i++) {
System.out.println(start = incrementAlphabetic(start, 0));
}
}
are you looking for something like this.. (not tested)
char ch='a';
int iterations=999;
int count=0;
for(int i=0;i<iterations;i++){
if(i%100==0){
ch++;
count=0;
}
System.out.println(ch+""+count);
count++;
}

Categories