Getting back into programming after many years, and build a simple "blackjack" program in Java.
I'm wondering if the way I structured the methods/objects is bad, using global static variables. The program seems to work fine, but there's no way to implement a "split" method without re-writing everything, since you can't pass the new "split" hands into the "hit" or "stand" functions.
I'm curious how others would structure this and what the flaws in my methodology were. Thanks!
import java.io.*;
import java.util.*;
public class BlackJack {
static int bankroll = 0;
static int bet = 1;
static int index = 0;
static CardDeck d = new CardDeck();
static ArrayList<Card> playerCards = new ArrayList<Card>();
static ArrayList<Card> playerCards2 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards3 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards4 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards5 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards6 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> dealerCards = new ArrayList<Card>(); //unused - was thinking of using for splitting
static int playerScore = 0;
static int dealerScore = 0;
static String action = "";
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
initializeBankroll();
while (bet != 0) {
startRound();
display();
if(checkBlackJacks()) continue;
while (playerScore <= 21) {
System.out.println("H - hit, S - stand, X - surrender, D - double down");
action = s.nextLine();
if (action.equals("H")) hit();
else if (action.equals("S")) {
stand();
break;
}
else if (action.equals("X")) surrender();
else if (action.equals("D")) {
doubleDown();
break;
}
}
eval();
}
}
public static int score (ArrayList<Card> list) {
int ret = 0;
int acecounter = 0;
for (int i=0; i<list.size(); i++) {
if (list.get(i).getVal()>1) {
ret += Math.min(10, list.get(i).getVal());
}
else { //An ace
ret += 11;
acecounter++;
}
}
while(ret >21 && acecounter >0) {
ret -= 10;
acecounter -= 1;
}
return ret;
}
public static void dealToPlayer() {
playerCards.add(d.getCard(index));
index++;
}
public static void dealToDealer() {
dealerCards.add(d.getCard(index));
index++;
}
public static void display() {
System.out.println("PLAYER CARDS:");
String playerCardString = "";
for (int i=0; i<playerCards.size(); i++) {
playerCardString += playerCards.get(i).toString();
playerCardString += " ";
}
System.out.println(playerCardString);
System.out.println("DEALER CARD:");
System.out.println(dealerCards.get(0).toString());
}
public static void hit() {
dealToPlayer();
reScore();
display();
}
public static void surrender() {
if(playerCards.size()>2) {
System.out.println("You can't do that");
return;
}
bankroll -= (bet / 2);
playerScore = 100; //surrender
}
public static void reScore() {
playerScore = score(playerCards);
dealerScore = score(dealerCards);
}
public static void stand() {
try {
System.out.println("DEALER DOWNCARD: " + dealerCards.get(1).toString());
Thread.sleep(1000);
while (dealerScore <17) {
dealToDealer();
System.out.println(dealerCards.get(dealerCards.size()-1).toString());
reScore();
System.out.println("DEALER SCORE " + Integer.toString(dealerScore));
Thread.sleep(1000);
}
}catch(Exception E) {
System.out.println("Exception");
}
}
public static void doubleDown() {
if(playerCards.size()>2) {
System.out.println("You can't do that, hitting instead");
hit();
if(playerScore<=21) stand();
return;
}
if( bet * 2 > bankroll) {
System.out.println("Doubling for less...");
bet = bankroll;
hit();
if(playerScore<=21) stand();
return;
}
bet *= 2;
hit();
if(playerScore<=21) stand();
}
public static void split(ArrayList<Card> splitarray, int splitcount) { //INCOMPLETE. How to get this to work?
if(splitarray.size()>2 || bet * (splitcount+1) > bankroll || splitarray.get(1).getVal() != splitarray.get(0).getVal()) {
System.out.println("Can't split. Hitting instead");
hit();
}
ArrayList<Card> s1 = new ArrayList<Card>();
ArrayList<Card> s2 = new ArrayList<Card>();
s1.add(splitarray.get(0));
s2.add(splitarray.get(1));
}
public static void eval() {
if (playerScore==100) { //indicates a surrender, and bankroll has already been adjusted
return;
}
if (playerScore>21) {
System.out.println("BUST");
bankroll -= bet;
return;
}
if (dealerScore>21) {
System.out.println("DEALER BUST");
bankroll += bet;
return;
}
if (playerScore > dealerScore) {
System.out.println("WIN");
bankroll += bet;
return;
}
if (playerScore < dealerScore) {
System.out.println("LOSE");
bankroll -= bet;
return;
}
System.out.println("PUSH");
return;
}
public static void newhand() {
d.shuffle();
playerCards.clear();
dealerCards.clear();
index = 0;
reScore();
}
public static boolean checkBlackJacks() {
if(playerScore == 21) {
if(dealerCards.get(0).getVal()==1) {
System.out.println("Even money? Y / N");
String even = s.nextLine();
if (even=="Y"){
bankroll += bet;
newhand();
return true;
}
}
if(dealerScore != 21) {
System.out.println("BlackJack");
bankroll += (1.5 * bet);
newhand();
return true;
}
else {
System.out.println("Push - Mutual Blackjack");
newhand();
return true;
}
}
if(dealerCards.get(0).getVal()==1) { //insurance
System.out.println("Insurance? Type wager or 0, up to half your bet");
int insuranceBet = s.nextInt();
if (insuranceBet > bankroll) insuranceBet = bankroll;
if (insuranceBet > (bet / 2)) insuranceBet = bet / 2;
if (dealerScore == 21) bankroll += (insuranceBet * 2);
else bankroll -= insuranceBet;
}
if(dealerScore==21) {
System.out.println("Dealer Blackjack");
bankroll -= bet;
newhand();
return true;
}
return false;
}
public static void initializeBankroll() {
System.out.println("Enter your buy-in");
bankroll = s.nextInt();
}
public static void startRound() {
newhand();
System.out.println("Money remaining:" + Integer.toString(bankroll));
System.out.println("Enter your bet");
bet = s.nextInt();
if (bet>bankroll) bet=0;
dealToPlayer();
dealToDealer();
dealToPlayer();
dealToDealer();
reScore();
}
}
___________________
public class Card {
int val; //1 = Ace, 11 = Jack, 12 = Queen, 13 = King
int suit; //1 = Club, 2 = Diamond, 3 = Heart, 4 = Spade
public Card() {
this(1,1);
}
public Card(int val, int suit) {
this.val = val;
this.suit = suit;
}
public int getSuit(){
return suit;
}
public int getVal() {
return val;
}
public void setVal(int a) {
if(a>=1 && a<= 13) val = a;
}
public void setSuit(int a) {
if (a>=1 && a<=4) suit = a;
}
public String toString() {
String valString = "";
String suitString = "";
String ret = "";
switch(val) {
case 1: valString = "A"; break;
case 10: valString = "T"; break;
case 11: valString = "J"; break;
case 12: valString = "Q"; break;
case 13: valString = "K"; break;
default: valString = Integer.toString(val);
}
switch(suit) {
case 1: suitString = "c"; break;
case 2: suitString = "d"; break;
case 3: suitString = "h"; break;
case 4: suitString = "s"; break;
default: suitString = "ERROR"; break;
}
ret = valString + suitString;
return ret;
}
}
______________________
public class CardDeck{
Card[] deck;
public CardDeck(){
int k=0;
deck = new Card[52];
for (int i=0; i<13; i++){
for (int j=0; j<4; j++){
Card c = new Card(i+1,j+1);
deck[k]=c;
k++;
}
}
shuffle();
}
public void shuffle(){
Card[] deckCopy = new Card[52];
boolean[] flags = new boolean[52];
for (int i=0; i<flags.length; i++) flags[i]=false;
int numConverted=0;
while(numConverted<52){
int num = (int)(Math.random() * 52);
if (flags[num]==false){
deckCopy[numConverted]=deck[num];
numConverted++;
flags[num]=true;
}
}
deck = deckCopy;
} //end shuffle
public String toString() {
String ret = "";
for (int i = 0; i<deck.length; i++) {
ret += deck[i].toString();
ret += " ";
}
return ret;
}
public Card getCard(int a) {
if (a<0 || a > 51) return null;
else return deck[a];
}
public int getSuit(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getSuit();
}
public int getVal(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getVal();
}
}
So i have this function EDIT:Whole program as requested
//This is a java program to construct Expression Tree using Infix Expression
import java.io.*;
public class Infix_Expression_Tree
{
public static void main(String args[]) throws IOException
{
String result="";
File vhod = new File(args[0]);
try{
BufferedReader reader = new BufferedReader(new FileReader(vhod));
Tree t1 = new Tree();
String a = reader.readLine();
t1.insert(a);
t1.traverse(1,result);
System.out.println("rez "+ result);
ch = reader.readLine();
}catch(IOException e){
e.printStackTrace();
}
}
}
class Node
{
public char data;
public Node leftChild;
public Node rightChild;
public Node(char x)
{
data = x;
}
public void displayNode()
{
System.out.print(data);
}
}
class Stack1
{
private Node[] a;
private int top, m;
public Stack1(int max)
{
m = max;
a = new Node[m];
top = -1;
}
public void push(Node key)
{
a[++top] = key;
}
public Node pop()
{
return (a[top--]);
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Stack2
{
private char[] a;
private int top, m;
public Stack2(int max)
{
m = max;
a = new char[m];
top = -1;
}
public void push(char key)
{
a[++top] = key;
}
public char pop()
{
return (a[top--]);
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Conversion
{
private Stack2 s;
private String input;
private String output = "";
public Conversion(String str)
{
input = str;
s = new Stack2(str.length());
}
public String inToPost()
{
for (int i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
switch (ch)
{
case '+':
gotOperator(ch, 2);
break;
case '*':
gotOperator(ch,1);
break;
case '/':
gotOperator(ch, 3);
break;
case '(':
s.push(ch);
break;
case ')':
gotParenthesis();
//s.pop();
break;
default:
//gotOperator(ch, 0);
//break;
output = output + ch;
}
}
while (!s.isEmpty())
output = output + s.pop();
//System.out.println("to je output iz inToPost " +output);
return output;
}
private void gotOperator(char opThis, int prec1)
{
while (!s.isEmpty())
{
char opTop = s.pop();
if (opTop == '(')
{
s.push(opTop);
break;
} else
{
int prec2;
if (opTop == '+')
prec2 = 2;
else if(opTop=='*')
prec2=1;
else
prec2 = 3;
if (prec2 <= prec1)
{
s.push(opTop);
break;
} else
output = output + opTop;
}
}
s.push(opThis);
}
private void gotParenthesis()
{
while (!s.isEmpty())
{
char ch = s.pop();
if (ch == '(')
break;
else
output = output + ch;
}
}
}
class Tree
{
private Node root;
public Tree()
{
root = null;
}
public void insert(String s)
{
Conversion c = new Conversion(s);
s = c.inToPost();
Stack1 stk = new Stack1(s.length());
s = s + "#";
int i = 0;
char symbol = s.charAt(i);
Node newNode;
while (symbol != '#')
{
if (symbol >= '0' && symbol <= '9' || symbol >= 'A'
&& symbol <= 'Z' || symbol >= 'a' && symbol <= 'z')
{
newNode = new Node(symbol);
stk.push(newNode);
} else if (symbol == '+' || symbol == '/'
|| symbol == '*')
{
Node ptr1=null;
Node ptr2=null;
//if(!stk.isEmpty()){
ptr1 = stk.pop();
if(!stk.isEmpty()){
ptr2 = stk.pop();
}
//}
newNode = new Node(symbol);
newNode.leftChild = ptr2;
newNode.rightChild = ptr1;
stk.push(newNode);
}
/*else if(symbol=='/'){
Node ptr = stk.pop();
newNode = new Node(symbol);
newNode.leftChild = ptr;
newNode.rightChild=null;
stk.push(newNode);
}*/
symbol = s.charAt(++i);
}
root = stk.pop();
}
public void traverse(int type,String result)
{
System.out.println("Preorder Traversal:- ");
preOrder(root,result);
}
private void preOrder(Node localRoot, String result)
{
if(root==null){
return;
}
if (localRoot != null)
{
if(localRoot.data == '/'){
preOrder(localRoot.leftChild,result);
result=result + localRoot.data;
//StringBuilder stringBuilder1 = new StringBuilder();
//stringBuilder1.append(result).append(localRoot.data);
System.out.println(result);
//localRoot.displayNode();
preOrder(localRoot.rightChild,result);
return;
}else{
//System.out.println("trenutni root je" );
//localRoot.displayNode();
result=result + localRoot.data;
// StringBuilder stringBuilder1 = new StringBuilder();
//stringBuilder1.append(result).append(localRoot.data);
System.out.println(result);
preOrder(localRoot.leftChild,result);
//result=result + localRoot.data;
//System.out.print(root.data);
preOrder(localRoot.rightChild,result);
//System.out.print(root.data);
//preOrder(localRoot.rightChild);
return;
}
}
}
}
my problem with it is that with localRoot.DisplayNode() i get the result i want. But when i add the same thing to the String result it adds data, until i get to leaf of the tree(leaf doesnt have left/right child) so it returns to previous recursive call, and goes to right child, here somewhere the leaf(from which we came back) isnt in String anymore. How do i fix this?
String is defined in main method
I'm programming a java game. It's almost done but it's giving me a error (and I don't understand why it happens, the code seems okay).
Error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: projetofinal.ProjetoFinalv2.movimento
at projetofinal.ProjetoFinalv2.main(ProjetoFinalv2.java:26)
C:\Users\Francisco\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)
Here's the code:
package projetofinal;
import java.util.Scanner;
import java.util.Random;
public class ProjetoFinalv2 {
static char[][] tabuleiro;
static int x, y, jogadorX, jogadorY, pontos;
static char direction;
static boolean inGame = true;
public static void main(String[] args) {
x = 5;
y = 5;
tabuleiro = new char[x][y];
jogadorX = 0;
jogadorY = 4;
pontos = 7;
quadro();
while(inGame == true)
{
customcreator();
Scanner scan = new Scanner(System.in);
String resposta = scan.nextLine();
movimento(resposta.charAt(0));
}
}
public static void placePot()
{
boolean notDone = true;
while(notDone)
{
int tabX = random(0, 4);
int tabY = random(0, 4);
if(tabuleiro[tabX][tabY] == '.')
{
tabuleiro[tabX][tabY] = 'P';
notDone = false;
}
}
}
public static boolean bomba(int x, int y)
{
if(tabuleiro[x][y] == 'B')
{
return true;
}
else
{
return false;
}
}
public static boolean win()
{
if(tabuleiro[jogadorX][jogadorY] == 'F')
{
return true;
}
else
{
return false;
}
}
public static boolean gameover()
{
if(pontos > 0)
{
return false;
}
else
{
return true;
}
}
public static int potepoints(int x, int y)
{
if(tabuleiro[x][y] == 'P')
{
return random(3,5);
}
else
{
return -1;
}
}
public static void quadro()
{
for(int linha = 0; linha < x; linha++)
{
for(int vertical = 0; vertical < y; vertical++)
{
tabuleiro[linha][vertical] = '.';
}
}
//Por as bombas na posição correta
for(int i = quantos(); i>0; i--)
{
boolean tab = true;
while(tab)
{
int tabX = random(1, 3);
int tabY = random(1, 2);
if(tabuleiro[tabX][tabY] != 'B')
{
tabuleiro[tabX][tabY] = 'B';
tab = false;
}
}
}
//Mete o pote que da pontos
placePot();
}
public static void tabuleirocreator()
{
playercreator();
for(int linha = 0; linha < y; linha++)
{
for(int vertical = 0; vertical < x; vertical++)
{
System.out.print(tabuleiro[vertical][linha]);
}
System.out.print("\n");
}
}
public static void playercreator()
{
tabuleiro[jogadorX][jogadorY] = 'J';
}
public static void customcreator()
{
tabuleiro[0][4] = 'I';
tabuleiro[4][0] = 'F';
tabuleirocreator();
}
public static int random(int min, int max)
{
Random generator = new Random();
int Num = generator.nextInt((max - min) + 1) + min;
return Num;
}
public static int quantos()
{
return random(2, 3);
}
}
//Ciclo do jogo
public static void movimento(char newDirection)
{
if(newDirection == 'w' || newDirection == 'W')
{
if(jogadorY > 0)
{
tabuleiro[jogadorX][jogadorY] = '.';
jogadorY -= 1;
pontos--;
}
}
else
{
if(newDirection == 'a' || newDirection == 'A')
{
if(jogadorX > 0)
{
tabuleiro[jogadorX][jogadorY] = '.';
jogadorX -= 1;
pontos--;
}
}
else
{
if(newDirection == 's' || newDirection == 'S')
{
if(jogadorY < 4)
{
tabuleiro[jogadorX][jogadorY] = '.';
jogadorY += 1;
pontos--;
}
}
else
{
if(newDirection == 'd' || newDirection == 'D')
{
if(jogadorX < 4)
{
tabuleiro[jogadorX][jogadorY] = '.';
jogadorX += 1;
pontos--;
}
}
else
{
System.out.println("Wrong direction!");
}
}
}
}
if(bomba(jogadorX, jogadorY))
{
pontos = 0;
}
int tab = potepoints(jogadorX, jogadorY);
if(tab != -1)
{
pontos += tab;
}
if(win())
{
System.out.println("You won");
inGame = false;
}
if(gameover())
{
System.out.println("Game Over");
inGame = false;
}
}
//////////////////////////////////////////////////////////////
I'm a quite noob in java (i started to learn recently) so, i'm sorry if the question is bad.
The message tells you that the compiler cannot find a definition for projetofinal.ProjetoFinalv2.movimento, a symbol on line 26: movimento(resposta.charAt(0));. But movimento is not defined inside the class. The class definition ends with the closing brace (}) just before the orphaned method definition for movimento. Not only does that make the method definition inaccessible to the caller, it is utterly illegal to define methods or variables outside of a class.
I'm a bit new to java, I'm having one error with my Java program that I can't seem to fix, very easy solution I just can't see it haha. How can I fix this? I tried a few things but it adds more errors on top of each other. Thank you all!
import java.io.*;
import java.util.*;
class Node {
public char ch;
public Node leftChild;
public Node rightChild;
Node(char c) {
ch = c;
}
public void displayNode() {
System.out.print(ch);
}
}
class Tree {
public Node root;
public Tree(Node nd) {
root = nd;
}
public void traverse(int traverseType) {
switch (traverseType) {
case 1:
System.out.print(" \n Preorder traversal : ");
preOrder(root);
break;
case 2:
System.out.print(" \n Inorder traversal : ");
inOrder(root);
break;
case 3:
System.out.print(" \n Postorder traversal : ");
postOrder(root);
break;
}
System.out.println();
}
private void preOrder(Node localRoot) {
if (localRoot != null) {
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
}
}
private void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
}
}
public void displayTree() {
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(" ...................................................... ");
while (isRowEmpty == false) {
Stack localStack = new Stack();
isRowEmpty = true;
for (int j = 0; j < nBlanks; j++)
System.out.print(' ');
while (globalStack.isEmpty() == false) {
Node temp = (Node) globalStack.pop();
if (temp != null) {
temp.displayNode();
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if (temp.leftChild != null || temp.rightChild != null)
isRowEmpty = false;
} else {
System.out.print("-");
localStack.push(null);
localStack.push(null);
}
for (int j = 0; j < nBlanks * 2 - 1; j++)
System.out.print(' ');
}
System.out.println();
nBlanks / = 2;
while (localStack.isEmpty() == false)
globalStack.push(localStack.pop());
}
System.out.println(" ...................................................... ");
}
}
class BottomUp {
private String inString;
private int strlen;
private Tree[] treeArray;
private Tree aTree;
private int numNodes;
BottomUp(String s) {
inString = s;
strlen = inString.length();
treeArray = new Tree[100];
for (int j = 0; j < strlen; j++) {
char ch = inString.charAt(j);
Node aNode = new Node(ch);
treeArray[j] = new Tree(aNode);
}
}
public Tree getTree() {
return aTree;
}
public void balanced() {
numNodes = strlen;
while (numNodes > 1) {
int i = 0;
int j = 0;
Tree[] tempArray = new Tree[100];
for (j = 0; j < strlen - 1; j++) {
Tree tree1 = treeArray[j];
Tree tree2 = treeArray[j + 1];
Node aNode = new Node('+');
aTree = new Tree(aNode);
aTree.root.leftChild = tree1.root;
aTree.root.rightChild = tree2.root;
tempArray[i++] = aTree;
numNodes--;
j++;
}
if (strlen % 2 == 1) {
Tree tree1 = treeArray[j];
Node aNode = new Node('+');
aTree = new Tree(aNode);
aTree.root.leftChild = tree1.root;
tempArray[i++] = aTree;
}
treeArray = tempArray;
strlen = numNodes;
}
aTree = treeArray[0];
}
}
class BottomUpApp {
public static void main(String[] args) throws IOException {
BottomUp bup;
Tree theTree = null;
int value;
String str;
while (true) {
System.out.print(" Enter first letter of ");
System.out.print(" balanced , show , or traverse : ");
int choice = getChar();
switch (choice) {
case 'b':
System.out.print(" Enter string : ");
str = getString();
bup = new BottomUp(str);
bup.balanced();
theTree = bup.getTree();
break;
case 's':
theTree.displayTree();
break;
case 't':
System.out.print(" Enter type 1, 2 or 3 : ");
value = getInt();
theTree.traverse(value);
break;
default:
System.out.print(" Invalid entry \n ");
}
}
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
}
ERROR CODE
Node.java:112: error: illegal start of expression
nBlanks / = 2 ;
^
1 error
The Java operator /= must be typed without spaces in between, or else it will be parsed as 2 separate operators, / and =, which is a syntax error. Try
nBlanks /= 2 ;
Currently I have a program that asks for a string, for example "Hello stackoverflow!" and I'm trying to make it increment every individual character by a large, random number. The problem is, once the program gets to '~' it has to start going backwards, then once it gets '!' it has to switch again. (! is the first Ascii symbol, and ~ is the last, with numbers and letters in the middle.) So far this is what I have for the incrementing part, it isn't quite working though:
for(int i = 0; i < inputStringB.length(); i++){
currentChar = inputString.charAt(i);
for(int e = 0; e < 1000; e++){
if(currentChar == '!'){
switchIncrement = 1;
} else if(currentChar == '~') {
switchIncrement = 0;
}
switch(switchInc){
case 0: currentChar--;
inputStringB.setCharAt(i, currentChar);
break;
case 1: currentChar++;
inputStringB.setCharAt(i, currentChar);
break;
default: currentChar++;
inputStringB.setCharAt(i, currentChar);
break;
}
}
System.out.println(inputStringB);
}
When I input 'Hello' I receive: 'n#J&)' Which doesn't make sense considering 'Hello' contains two l's, so I would expect 'n#JJ)'
Any help would be awesome, thanks!
Full code:
import java.util.Scanner;
public class EncryptionMain {
public static void main(String args[]){
char currentChar;
String EorD;
int switchInc = 1; // 0 = BACK 1 = FORWARD
Scanner scanner = new Scanner(System.in);
System.out.println("Encrypt or decrypt: ");
EorD = scanner.next();
if(EorD.equalsIgnoreCase("e")){
System.out.println("Please enter text to encrypt: ");
String inputString = scanner.next();
System.out.println("Encrypting: '" + inputString + "' ");
System.out.println("...");
System.out.println("...");
System.out.println("...");
StringBuilder inputStringB = new StringBuilder(inputString);
for(int i = 0; i < inputStringB.length(); i++){
currentChar = inputStringB.charAt(i);
System.out.println(currentChar);
for(int e = 0; e < 1000; e++){
if(currentChar == '!'){
switchInc = 1;
}else if(currentChar == '~'){
switchInc = 0;
}
switch(switchInc){
case 0: currentChar--;
inputStringB.setCharAt(i, currentChar);
break;
default: currentChar++;
inputStringB.setCharAt(i, currentChar);
break;
}
}
System.out.println(inputStringB);
}
}else if(EorD.equalsIgnoreCase("d")){
System.out.println("Please enter text to decrypt: ");
String inputString = scanner.next();
System.out.println("Decrypting: '" + inputString + "' ");
System.out.println("...");
System.out.println("...");
System.out.println("...");
StringBuilder inputStringB = new StringBuilder(inputString);
for(int i = 0; i < inputStringB.length(); i++){
currentChar = inputStringB.charAt(i);
for(int e = 0; e < 1000; e++){
if(currentChar == '!'){
switchInc = 0;
}else if(currentChar == '~'){
switchInc = 1;
}
switch(switchInc){
case 0: currentChar++;
inputStringB.setCharAt(i, currentChar);
break;
case 1: currentChar--;
inputStringB.setCharAt(i, currentChar);
break;
default: currentChar--;
inputStringB.setCharAt(i, currentChar);
break;
}
}
inputStringB.setCharAt(i, currentChar);
System.out.println(inputStringB);
}
}
}
}
First I'm going to remove all of the I/O (except for outputting the result), get rid of the decryption piece for brevity, and write encrypt(String) and encrypt(char) as pure functions.
public class EncryptionMain {
public static void main(String args[]){
System.out.println(encrypt("Hello"));
}
static String encrypt(String plaintext) {
StringBuilder ciphertext = new StringBuilder(plaintext);
for (int i = 0; i < ciphertext.length(); i++) {
ciphertext.setCharAt(i, encrypt(ciphertext.charAt(i)));
}
return ciphertext.toString();
}
static char encrypt(char c) {
int switchInc = 1; // 0 = BACK 1 = FORWARD
for(int e = 0; e < 1000; e++){
if (c == '!') {
switchInc = 1;
} else if (c == '~') {
switchInc = 0;
}
switch (switchInc) {
case 0: c--; break;
default: c++; break;
}
}
return c;
}
}
And, whoops! - just by doing that, I accidentally fixed the bug. Here, I'll add it back:
public class EncryptionMain {
public static void main(String args[]){
System.out.println(encrypt("Hello"));
}
static String encrypt(String plaintext) {
StringBuilder ciphertext = new StringBuilder(plaintext);
for (int i = 0; i < ciphertext.length(); i++) {
ciphertext.setCharAt(i, encrypt(ciphertext.charAt(i)));
}
return ciphertext.toString();
}
static int switchInc = 1; // 0 = BACK 1 = FORWARD
static char encrypt(char c) {
for(int e = 0; e < 1000; e++){
if (c == '!') {
switchInc = 1;
} else if (c == '~') {
switchInc = 0;
}
switch (switchInc) {
case 0: c--; break;
default: c++; break;
}
}
return c;
}
}
Edit - Here's a working Caesar cipher I referred to in the comments below.
main/cipher/Cipher.java
package cipher;
public final class Cipher {
public Cipher(Range range, int key) {
this.range = range;
this.key = key;
}
public final Range range;
public final int key;
public String encrypt(String plaintext) {
return cipher(plaintext, key);
}
public String decrypt(String ciphertext) {
return cipher(ciphertext, -key);
}
String cipher(String in, int n) {
StringBuilder out = new StringBuilder(in.length());
for (int i = 0; i < in.length(); i++) {
out.append(range.shift(in.charAt(i), n));
}
return out.toString();
}
}
main/cipher/Range.java
package cipher;
public final class Range {
public final char min;
public final char max;
public final int size;
public static Range inclusive(char min, char max) {
return new Range(min, max);
}
Range(char min, char max) {
this.min = min;
this.max = max;
size = max - min + 1;
}
/** Shift c up by i places, wrapping around to the
* beginning of the range when it reaches the end. */
public char shift(char c, int i) {
return (char) (min + mod(c - min + i, size));
}
/** x mod a */
static int mod(int x, int a) {
return ((x % a) + a) % a;
}
}
test/cipher/CipherTest.java
package cipher;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class CipherTest {
#Test
public void testZeroKey() throws Exception {
Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 0);
assertEquals(cipher.encrypt("abcxyz"), "abcxyz");
assertEquals(cipher.decrypt("abcxyz"), "abcxyz");
}
#Test
public void testOneKey() throws Exception {
Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 1);
assertEquals(cipher.encrypt("abcxyz"), "bcdyza");
assertEquals(cipher.decrypt("bcdyza"), "abcxyz");
}
#Test
public void testSizePlusOneKey() throws Exception {
Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 27);
assertEquals(cipher.encrypt("abcxyz"), "bcdyza");
assertEquals(cipher.decrypt("bcdyza"), "abcxyz");
}
}
test/cipher/RangeTest.java
package cipher;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static cipher.Range.mod;
public class RangeTest {
#Test
public void testSize() {
Assert.assertEquals(Range.inclusive('a', 'c').size, 3);
}
#Test
public void testMod() throws Exception {
assertEquals(mod(-2, 5), 3);
assertEquals(mod(-1, 5), 4);
assertEquals(mod(0, 5), 0);
assertEquals(mod(1, 5), 1);
assertEquals(mod(2, 5), 2);
assertEquals(mod(3, 5), 3);
assertEquals(mod(4, 5), 4);
assertEquals(mod(5, 5), 0);
assertEquals(mod(6, 5), 1);
}
#Test
public void testShift() throws Exception {
Range r = Range.inclusive('a', 'd');
Assert.assertEquals(r.shift('a', -2), 'c');
Assert.assertEquals(r.shift('a', -1), 'd');
Assert.assertEquals(r.shift('a', 0), 'a');
Assert.assertEquals(r.shift('a', 1), 'b');
Assert.assertEquals(r.shift('a', 2), 'c');
Assert.assertEquals(r.shift('a', 3), 'd');
Assert.assertEquals(r.shift('a', 4), 'a');
Assert.assertEquals(r.shift('a', 5), 'b');
}
}