Refactoring lots of if statements - java

So I have a project to make a random-name generator, and currently I have prefixes and suffixes being selected by:
A) The amount of letters in the person's first name, and
B) The first and last letter of their name.
The code currently functions as expected, I'd just like to refine the code and hopefully remove the hundreds of lines that have thousands of if statements.
import java.util.*;
public class ranName
{
public static void main(String[] args)
{
String input, firstName, lastName;
String firstPre, firstSuff, lastPre, lastSuff, lSuffMean, lPreMean, fLastLet, fFirstLet, lLastLet, lFirstLet;
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Lord Of The Rings Elf name Generator!");
System.out.println("------------------------------------------------");
System.out.println("");
System.out.print("First Name: ");
firstName = sc.nextLine();
while (true)
{
System.out.println("------------------------------------------------");
System.out.println("You inserted " + firstName);
System.out.println("Are you sure?");
System.out.print("Y/N: ");
input = sc.nextLine();
System.out.println("------------------------------------------------");
if (input.equalsIgnoreCase("Y"))
{
break;
}
else if (input.equalsIgnoreCase("N"))
{
System.out.print("First Name: ");
firstName = sc.nextLine();
}
else
{
System.out.println("Oh well, you tried. Here's another go at it.");
}
}
System.out.print("Last Name: ");
lastName = sc.nextLine();
while (true)
{
System.out.println("------------------------------------------------");
System.out.println("You inserted " + lastName);
System.out.println("Are you sure?");
System.out.print("Y/N: ");
input = sc.nextLine();
System.out.println("------------------------------------------------");
if (input.equalsIgnoreCase("Y"))
{
break;
}
else if (input.equalsIgnoreCase("N"))
{
System.out.print("Last Name: ");
lastName = sc.nextLine();
}
else
{
System.out.println("Oh well, you tried. Here's another go at it.");
}
}
System.out.print("Your Elf Name: ");
firstPre = preGet(firstName);
firstSuff = suffGet(firstName);
lastPre = housePreGet(lastName);
lastSuff = houseSuffGet(lastName);
lPreMean = preMean(lastPre);
lSuffMean = suffMean(lastSuff);
fLastLet = String.valueOf(firstPre.charAt(firstPre.length()-1));
fFirstLet = String.valueOf(firstSuff.charAt(0));
lLastLet = String.valueOf(lastPre.charAt(lastPre.length()-1));
lFirstLet = String.valueOf(lastSuff.charAt(0));
if (fFirstLet.equals(fLastLet))
{
firstSuff = (firstSuff.substring(1));
}
if (lFirstLet.equals(lLastLet))
{
lastSuff = (lastSuff.substring(1));
}
System.out.println(firstPre + firstSuff + " " + lastPre + lastSuff);
System.out.println("");
System.out.println("------------------------------------------------");
System.out.println("The House Name (lastname) Translates to: " + lPreMean + " " + lSuffMean);
System.out.println("------------------------------------------------");
}
public static String preGet(String fN)
{
String[] namePre;
String fNN, fL;
fNN = fN.trim();
int fnCount = fNN.length();
fL = String.valueOf(fNN.charAt(0));
namePre = new String[53];
namePre[0] = "PlaceHolder";
namePre[1] = "Ael";
namePre[2] = "Aer";
namePre[3] = "Bael";
namePre[4] = "Bes";
namePre[5] = "Cael";
namePre[6] = "Cor";
namePre[7] = "Dae";
namePre[8] = "Dre";
namePre[9] = "Eil";
namePre[10] = "Ev";
namePre[11] = "Fir";
namePre[12] = "Fis";
namePre[13] = "Gael";
namePre[14] = "Gil";
namePre[15] = "Ha";
namePre[16] = "Hu";
namePre[17] = "Ia";
namePre[18] = "Il";
namePre[19] = "Ja";
namePre[20] = "Jar";
namePre[21] = "Kan";
namePre[22] = "Kor";
namePre[23] = "La";
namePre[24] = "Lue";
namePre[25] = "Mai";
namePre[26] = "Mara";
namePre[27] = "Na";
namePre[28] = "Nim";
namePre[29] = "Ol";
namePre[30] = "Onn";
namePre[31] = "Py";
namePre[32] = "Pael";
namePre[33] = "Qu";
namePre[34] = "Qi";
namePre[35] = "Rum";
namePre[36] = "Rua";
namePre[37] = "Sae";
namePre[38] = "Sha";
namePre[39] = "Tahl";
namePre[40] = "Thro";
namePre[41] = "Ul";
namePre[42] = "Uon";
namePre[43] = "Ver";
namePre[44] = "Vil";
namePre[45] = "Wuo";
namePre[46] = "Waal";
namePre[47] = "Xae";
namePre[48] = "Xen";
namePre[49] = "Ya";
namePre[50] = "Yae";
namePre[51] = "Za";
namePre[52] = "Zy";
if (fnCount % 2 == 0)
{
if (fL.equalsIgnoreCase("A"))
{
return namePre[1];
}
else if (fL.equalsIgnoreCase("B"))
{
return namePre[3];
}
else if (fL.equalsIgnoreCase("C"))
{
return namePre[5];
}
else if (fL.equalsIgnoreCase("D"))
{
return namePre[7];
}
else if (fL.equalsIgnoreCase("E"))
{
return namePre[9];
}
else if (fL.equalsIgnoreCase("F"))
{
return namePre[11];
}
else if (fL.equalsIgnoreCase("G"))
{
return namePre[13];
}
else if (fL.equalsIgnoreCase("H"))
{
return namePre[15];
}
else if (fL.equalsIgnoreCase("I"))
{
return namePre[17];
}
else if (fL.equalsIgnoreCase("J"))
{
return namePre[19];
}
else if (fL.equalsIgnoreCase("K"))
{
return namePre[21];
}
else if (fL.equalsIgnoreCase("L"))
{
return namePre[23];
}
else if (fL.equalsIgnoreCase("M"))
{
return namePre[25];
}
else if (fL.equalsIgnoreCase("N"))
{
return namePre[27];
}
else if (fL.equalsIgnoreCase("O"))
{
return namePre[29];
}
else if (fL.equalsIgnoreCase("P"))
{
return namePre[31];
}
else if (fL.equalsIgnoreCase("Q"))
{
return namePre[33];
}
else if (fL.equalsIgnoreCase("R"))
{
return namePre[35];
}
else if (fL.equalsIgnoreCase("S"))
{
return namePre[37];
}
else if (fL.equalsIgnoreCase("T"))
{
return namePre[39];
}
else if (fL.equalsIgnoreCase("U"))
{
return namePre[41];
}
else if (fL.equalsIgnoreCase("V"))
{
return namePre[43];
}
else if (fL.equalsIgnoreCase("W"))
{
return namePre[45];
}
else if (fL.equalsIgnoreCase("X"))
{
return namePre[47];
}
else if (fL.equalsIgnoreCase("Y"))
{
return namePre[49];
}
else if (fL.equalsIgnoreCase("Z"))
{
return namePre[51];
}
}
else
{
if (fL.equalsIgnoreCase("A"))
{
return namePre[2];
}
else if (fL.equalsIgnoreCase("B"))
{
return namePre[4];
}
else if (fL.equalsIgnoreCase("C"))
{
return namePre[6];
}
else if (fL.equalsIgnoreCase("D"))
{
return namePre[8];
}
else if (fL.equalsIgnoreCase("E"))
{
return namePre[10];
}
else if (fL.equalsIgnoreCase("F"))
{
return namePre[12];
}
else if (fL.equalsIgnoreCase("G"))
{
return namePre[14];
}
else if (fL.equalsIgnoreCase("H"))
{
return namePre[16];
}
else if (fL.equalsIgnoreCase("I"))
{
return namePre[18];
}
else if (fL.equalsIgnoreCase("J"))
{
return namePre[20];
}
else if (fL.equalsIgnoreCase("K"))
{
return namePre[22];
}
else if (fL.equalsIgnoreCase("L"))
{
return namePre[24];
}
else if (fL.equalsIgnoreCase("M"))
{
return namePre[26];
}
else if (fL.equalsIgnoreCase("N"))
{
return namePre[28];
}
else if (fL.equalsIgnoreCase("O"))
{
return namePre[30];
}
else if (fL.equalsIgnoreCase("P"))
{
return namePre[32];
}
else if (fL.equalsIgnoreCase("Q"))
{
return namePre[34];
}
else if (fL.equalsIgnoreCase("R"))
{
return namePre[36];
}
else if (fL.equalsIgnoreCase("S"))
{
return namePre[38];
}
else if (fL.equalsIgnoreCase("T"))
{
return namePre[40];
}
else if (fL.equalsIgnoreCase("U"))
{
return namePre[42];
}
else if (fL.equalsIgnoreCase("V"))
{
return namePre[44];
}
else if (fL.equalsIgnoreCase("W"))
{
return namePre[46];
}
else if (fL.equalsIgnoreCase("X"))
{
return namePre[48];
}
else if (fL.equalsIgnoreCase("Y"))
{
return namePre[50];
}
else if (fL.equalsIgnoreCase("Z"))
{
return namePre[52];
}
}
return "";
}
public static String suffGet(String fN)
{
String[] nameSuff;
String fNN, fL;
fNN = fN.trim();
int fnCount = fNN.length();
fL = String.valueOf(fNN.charAt(fNN.length()-1));
nameSuff = new String[53];
nameSuff[0] = "placeholder";
nameSuff[1] = "ae";
nameSuff[2] = "aith";
nameSuff[3] = "brar";
nameSuff[4] = "bael";
nameSuff[5] = "cael";
nameSuff[6] = "con";
nameSuff[7] = "drimme";
nameSuff[8] = "dul";
nameSuff[9] = "emar";
nameSuff[10] = "evar";
nameSuff[11] = "fel";
nameSuff[12] = "faen";
nameSuff[13] = "gael";
nameSuff[14] = "gin";
nameSuff[15] = "hal";
nameSuff[16] = "har";
nameSuff[17] = "ii";
nameSuff[18] = "im";
nameSuff[19] = "jin";
nameSuff[20] = "jaal";
nameSuff[21] = "ki";
nameSuff[22] = "kas";
nameSuff[23] = "lian";
nameSuff[24] = "lihn";
nameSuff[25] = "mah";
nameSuff[26] = "'mek";
nameSuff[27] = "nes";
nameSuff[28] = "'nil";
nameSuff[29] = "onna";
nameSuff[30] = "oth";
nameSuff[31] = "pae";
nameSuff[32] = "pek";
nameSuff[33] = "'que";
nameSuff[34] = "quis";
nameSuff[35] = "ruil";
nameSuff[36] = "reth";
nameSuff[37] = "san";
nameSuff[38] = "sel";
nameSuff[39] = "thal";
nameSuff[40] = "thus";
nameSuff[41] = "ual";
nameSuff[42] = "uath";
nameSuff[43] = "vain";
nameSuff[44] = "vin";
nameSuff[45] = "wyn";
nameSuff[46] = "waal";
nameSuff[47] = "'xe";
nameSuff[48] = "'xol";
nameSuff[49] = "yth";
nameSuff[50] = "yl";
nameSuff[51] = "zair";
nameSuff[52] = "zara";
if (fnCount % 2 != 0)
{
if (fL.equalsIgnoreCase("A"))
{
return nameSuff[1];
}
else if (fL.equalsIgnoreCase("B"))
{
return nameSuff[3];
}
else if (fL.equalsIgnoreCase("C"))
{
return nameSuff[5];
}
else if (fL.equalsIgnoreCase("D"))
{
return nameSuff[7];
}
else if (fL.equalsIgnoreCase("E"))
{
return nameSuff[9];
}
else if (fL.equalsIgnoreCase("F"))
{
return nameSuff[11];
}
else if (fL.equalsIgnoreCase("G"))
{
return nameSuff[13];
}
else if (fL.equalsIgnoreCase("H"))
{
return nameSuff[15];
}
else if (fL.equalsIgnoreCase("I"))
{
return nameSuff[17];
}
else if (fL.equalsIgnoreCase("J"))
{
return nameSuff[19];
}
else if (fL.equalsIgnoreCase("K"))
{
return nameSuff[21];
}
else if (fL.equalsIgnoreCase("L"))
{
return nameSuff[23];
}
else if (fL.equalsIgnoreCase("M"))
{
return nameSuff[25];
}
else if (fL.equalsIgnoreCase("N"))
{
return nameSuff[27];
}
else if (fL.equalsIgnoreCase("O"))
{
return nameSuff[29];
}
else if (fL.equalsIgnoreCase("P"))
{
return nameSuff[31];
}
else if (fL.equalsIgnoreCase("Q"))
{
return nameSuff[33];
}
else if (fL.equalsIgnoreCase("R"))
{
return nameSuff[35];
}
else if (fL.equalsIgnoreCase("S"))
{
return nameSuff[37];
}
else if (fL.equalsIgnoreCase("T"))
{
return nameSuff[39];
}
else if (fL.equalsIgnoreCase("U"))
{
return nameSuff[41];
}
else if (fL.equalsIgnoreCase("V"))
{
return nameSuff[43];
}
else if (fL.equalsIgnoreCase("W"))
{
return nameSuff[45];
}
else if (fL.equalsIgnoreCase("X"))
{
return nameSuff[47];
}
else if (fL.equalsIgnoreCase("Y"))
{
return nameSuff[49];
}
else if (fL.equalsIgnoreCase("Z"))
{
return nameSuff[51];
}
}
else
{
if (fL.equalsIgnoreCase("A"))
{
return nameSuff[2];
}
else if (fL.equalsIgnoreCase("B"))
{
return nameSuff[4];
}
else if (fL.equalsIgnoreCase("C"))
{
return nameSuff[6];
}
else if (fL.equalsIgnoreCase("D"))
{
return nameSuff[8];
}
else if (fL.equalsIgnoreCase("E"))
{
return nameSuff[10];
}
else if (fL.equalsIgnoreCase("F"))
{
return nameSuff[12];
}
else if (fL.equalsIgnoreCase("G"))
{
return nameSuff[14];
}
else if (fL.equalsIgnoreCase("H"))
{
return nameSuff[16];
}
else if (fL.equalsIgnoreCase("I"))
{
return nameSuff[18];
}
else if (fL.equalsIgnoreCase("J"))
{
return nameSuff[20];
}
else if (fL.equalsIgnoreCase("K"))
{
return nameSuff[22];
}
else if (fL.equalsIgnoreCase("L"))
{
return nameSuff[24];
}
else if (fL.equalsIgnoreCase("M"))
{
return nameSuff[26];
}
else if (fL.equalsIgnoreCase("N"))
{
return nameSuff[28];
}
else if (fL.equalsIgnoreCase("O"))
{
return nameSuff[30];
}
else if (fL.equalsIgnoreCase("P"))
{
return nameSuff[32];
}
else if (fL.equalsIgnoreCase("Q"))
{
return nameSuff[34];
}
else if (fL.equalsIgnoreCase("R"))
{
return nameSuff[36];
}
else if (fL.equalsIgnoreCase("S"))
{
return nameSuff[38];
}
else if (fL.equalsIgnoreCase("T"))
{
return nameSuff[40];
}
else if (fL.equalsIgnoreCase("U"))
{
return nameSuff[42];
}
else if (fL.equalsIgnoreCase("V"))
{
return nameSuff[44];
}
else if (fL.equalsIgnoreCase("W"))
{
return nameSuff[46];
}
else if (fL.equalsIgnoreCase("X"))
{
return nameSuff[48];
}
else if (fL.equalsIgnoreCase("Y"))
{
return nameSuff[50];
}
else if (fL.equalsIgnoreCase("Z"))
{
return nameSuff[52];
}
return "";
}
return "";
}

Use an implementation of Map. Let the key be the letter of the alphabet and the value be what you're currently storing in your namePre array. This approach will also let you dispense with the array because your Map is acting as a means of both storage and retrieval.
Take your preGet method as an example. Rather than writing all those conditionals, you can achieve the same goal in a more compact fashion, something like so:
firstEvenPre = new HashMap<String, String>();
// some code to load up your prefixes
public static String preGet(String fN)
{
String[] namePre;
String fNN, fL;
fNN = fN.trim();
int fnCount = fNN.length();
fL = String.valueOf(fNN.charAt(0));
return (String)firstEvenPre.get(fL);
}
Use some discretion in trying the code, I didn't test it and I've been writing Ruby lately, so I might have some brain fog.

String fNN, fL;
fNN = fN.trim();
int fnCount = fNN.length();
fL = String.valueOf(fNN.charAt(fNN.length()-1));
can be replaced with
fN = fN.trim();
char fL = fN.charAt(fN.length()-1);
then you can use the ASCII code of the letter to determine what the array index should be
fN = fN.trim();
char fL = fN.charAt(fN.length()-1);
String[] suffixOdd = {"aith", "bael", "con", "dul", "evar", "faen", "gin", "har", "im", "jaal", "kas", "lihn", "'mek", "'nil", "oth", "pek", "quis", "reth", "sel", "thus", "uath", "vin", "waal", "'xol", "yl", "zara"};
String[] suffixEven = {"ae", "brar", "cael", "drimme", "emar", "fel", "gael", "hal", "ii", "jin", "ki", "lian", "mah", "nes", "onna", "pae", "'que", "ruil", "san", "thal", "ual", "vain", "wyn", "'xe", "yth", "zair"};
int suffixIndex = Character.toUpperCase(fL) - 'A';
if (fN.length() % 2 != 0)
{
if(suffixIndex >= suffixOdd.length)
return "";
return suffixOdd[Character.toUpperCase(fL) - 'A'];
}
else
{
if(suffixIndex >= suffixEven.length)
return "";
return suffixEven[Character.toUpperCase(fL) - 'A'];
}
In this case your suffix even and odd are both 26 long as they should be so I put the length checks in each of the respective code blocks.
PS: I highly encourage you to type out more descriptive variable names fN, fL, lastPre ect... are bad names, I have no idea what they are. Future you will thank you.

After looking back at the answer, everyone seems to be right, a switch statement would probably not be the best solution, because it would help that much.
However you could use a map, which is basically a data structure that takes key value pairs. You could reduce your two sets of if-statements and initial declaration to something like this:
public static String preGet(String fN)
{
HashMap<String, String> namePre = new HashMap<String, String>();
String fNN, fL;
fNN = fN.trim();
fL = String.valueOf(fNN.charAt(0));
String[] names = {"Ael", "Aer", "Bael", "Bes", "Cael", "Cor", "Dae", "Dre", "Eil", "Ev", "Fir", "Fis", "Gael", "Gil", "Ha", "Hu", "Ia", "Il", "Ja", "Jar", "Kan", "Kor", "La", "Lue", "Mai", "Mara", "Na", "Nim", "Ol", "Onn", "Py", "Pael", "Qu", "Qi", "Rum", "Rua", "Sae", "Sha", "Tahl", "Thro", "Ul", "Uon", "Ver", "Vil", "Wuo", "Waal", "Xae", "Xen", "Ya", "Yae", "Za", "Zy"};
for (int i=0; i <26; i++){
namePre.put(String.valueof((char)((i+64))), names[i]);
}
if (namePre.count(fN)){
return namePre.get(fN);
}
return "";
}

The huge if - else can be expressed as
int translation = 2 * (fNN.toUpper().charAt(0) - 'A');
if (fnCount % 2 == 0) {
return nameStuff[ 1 + translation ];
} else {
return nameStuff[ 2 + translation ];
}
The math-side of my brain is a little oozy right now, so let me know if there's some mistake here. This should work, though.
Though this is a hacky and incomprehensible code (remember to comment the shit out of this one), I think it is fine when it reduces 50 lines of code into 5.

Related

RadioButton value Increment decrement using Java

this is a online exam system. if the answer is correct marks increment by 1 it is work correctly at the same question second time select wrong answer i i need decrement the value
int marks;
String cor;
public void answerCheck()
{
String answerAnswer="";
if(r1.isSelected())
{
answerAnswer = r1.getText();
}
else if(r2.isSelected())
{
answerAnswer = r2.getText();
}
else if(r3.isSelected())
{
answerAnswer = r3.getText();
}
else if(r4.isSelected())
{
answerAnswer = r4.getText();
}
if(answerAnswer.equals(cor))
{
marks = marks + 1;
String Marks = String.valueOf(marks);
txtc.setText(Marks);
}
else if(!answerAnswer.equals(cor))
{
marks = marks - 1;
String Marks = String.valueOf(marks);
txtc.setText(Marks);
}
else
{
marks =0;
}
}
i am loading all data from the database correct answer also i am loading
Database Load
public void Connection()
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/onlineex","root","");
String query = "select * from questions";
pst = con.prepareStatement(query);
rs = pst.executeQuery();
while(rs.next())
{
txtqu.setText(rs.getString("id"));
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
cor = rs.getString(7);
}
}
i have a button call next
try
{
if(rs.previous())
{
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
cor=rs.getString(7);
}
else
{
JOptionPane.showMessageDialog(this, "This is first record of student");
}
answerCheck();
}
i have button call previous
if(rs.next())
{
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
cor=rs.getString(7);
}
else
{
JOptionPane.showMessageDialog(this, "This is first record of student");
}
answerCheck();
Firstly there is a Logical error in last else which will never execute because either answer is correct or wrong there is no third condition.
String cor;
public void answerCheck()
{
String answerAnswer="";
if(r1.isSelected())
{
answerAnswer = r1.getText();
}
else if(r2.isSelected())
{
answerAnswer = r2.getText();
}
else if(r3.isSelected())
{
answerAnswer = r3.getText();
}
else if(r4.isSelected())
{
answerAnswer = r4.getText();
}
if(answerAnswer.equals(cor))
{
marks = marks + 1;
String Marks = String.valueOf(marks);
txtc.setText(Marks);
}
else if(!answerAnswer.equals(cor) || ((r1.isSelected() ||
r2.isSelected() || r3.isSelected() || r4.isSelected()))
{
marks = marks - 1;
String Marks = String.valueOf(marks);
txtc.setText(Marks);
}
}

Converting multiple strings into one

I'm trying to convert multiple strings into one simple dialogue from a NPC. Basically what I'm trying to do is make a list of all the skills a player has 200M experience in and output it into a NPC dialogue.
OLD
if (componentId == OPTION_4) {
sendNPCDialogue(npcId, 9827, "You can prestige: "+maxedSkills()+"");
}
private String maxedSkills() {
return ""+attackMax()+""+strengthMax()+""+defenceMax()+"";
}
public String attackMax() {
if (player.getSkills().getXp(Skills.ATTACK) == 200000000)
return "Attack, ";
else
return "";
}
public String strengthMax() {
if (player.getSkills().getXp(Skills.STRENGTH) == 200000000)
return "Strength, ";
else
return "";
}
public String defenceMax() {
if (player.getSkills().getXp(Skills.DEFENCE) == 200000000)
return "Defence, ";
else
return "";
}
With that code I have it working, but that is a lot of code to add due to there being 25 different skills. How would I create a way to make all of the skills be referenced into one? Here are all of the skill names:
public static final String[] SKILL_NAME = { "Attack", "Defence", "Strength", "Constitution", "Ranged", "Prayer",
"Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining",
"Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "Construction",
"Summoning", "Dungeoneering" };
New and working (for attack/strength/defence):
public static final int[] SKILL_TYPE = {Skills.ATTACK, Skills.STRENGTH, Skills.DEFENCE};
public String maxedSkills() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < SKILL_TYPE.length; i++) {
if (player.getSkills().getXp(i) == 200000000) {
if(sb.length()>0) sb.append(", ");
sb.append(Skills.SKILL_NAME[i]);
}
}
if(sb.length()>0) sb.append(".");
return sb.toString();
}
Simplest way would be to have a parameteried method that takes the Skill type as input. Here is how it would look like:
public String skillMax(Skills skill) {
if (player.getSkills().getXp(skill) == 200000000)
return skill.getName() + ", ";
else
return "";
}
The next thing to do is to provide a name to the skill in Skills enum. Something like this should work:
public enum Skills {
DEFENSE("Defense"), ...;
private String name;
Skills(String name) { this.name = name; }
String getName() { return this.name; }
}
Use a StringBuffer (thread safe) or a StringBuilder and do something like this.
....
public static final Skills[] SKILL_TYPE = {Skills.Attack, Skills.Defence, ...};
public String getBigString() {
StringBuffer sb = new StringBuffer();
int nSkills = 0, lSkill = 0;
for( int i = 0; i < SKILL_TYPE.length; i++ )
{
if( player.getSkills().getXp(SKILL_TYPE[i]) == K_SOMELEVEL ) {
if(nSkills > 0) sb.append(", ");
lSkill = sb.length(); // track position of last skill in string
nSkills += 1;
sb.append(SKILL_NAME[i]);
}
}
if( nSkills > 0 )
{
if( nSkills > 1 ) sb.insert( lSkill, "and ");
sb.append(".");
}
return sb.toString();
}

Tic tac toe in java, overwrite issues

This is a simple tic tac toe game,every thing is right but with a problem that anyone can overwrite the previous marker and put his
I want to disable overwrite, How can I do it ?
Do we have to use final syntax ?
import java.util.*;
class TicTacToe {
static String Side;
static int NumberOfMoves=0;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Functions fc = new Functions();
int move;
System.out.println("Enter your Side :\n1) X\n2) O");
Side = sc.next();
if(Side.equals("1") ||Side.equals("x") ||Side.equals("X")) {
Side = "X";
} else if(Side.equals("2") ||Side.equals("o") ||Side.equals("O")) {
Side = "O";
}
fc.initialize();
fc.DisplayBoard();
while(fc.CheckIfWin() == 0) {
System.out.println("Its "+Side+"'s turn");
move = sc.nextInt();
fc.Move(move);
NumberOfMoves++;
fc.CheckIfWin();
fc.DisplayBoard();
fc.SideChange();
}
}
static class Functions {
String Row[] = new String[9];
public void initialize() {
for(int i = 1;i<=9;i++) {
Row[i-1] = Integer.toString(i);
}
}
public void DisplayBoard() {
System.out.print('\u000C');
System.out.println(" "+Row[0]+" | "+Row[1]+" | "+Row[2]);
System.out.println("---|---|---");
System.out.println(" "+Row[3]+" | "+Row[4]+" | "+Row[5]);
System.out.println("---|---|---");
System.out.println(" "+Row[6]+" | "+Row[7]+" | "+Row[8]);
}
public int CheckIfWin() {
/* Possible wins :-
* Horzontal : ( 0=1=2 ), (3, 4, 5), (6, 7, 8)
* Vertical : ( 0=3=6 ), (1=4=7), (2=5=8)
* Croswards : (0=4=8 ), (2=4=6)
*/
if(Row[0].equals(Row[1]) && Row[1].equals(Row[2])) {
System.out.println(Side+" wins.");
Row[0] = "--";Row[1] = "--";Row[2] = "--";
return 1;
} else if(Row[3].equals(Row[4]) && Row[4].equals(Row[5])) {
System.out.println(Side+" wins.");
Row[3] = "--";Row[4] = "--";Row[5] = "--";
return 1;
} else if(Row[6].equals(Row[7]) && Row[7].equals(Row[8])) {
System.out.println(Side+" wins.");
Row[6] = "--";Row[7] = "--";Row[8] = "--";
return 1;
} else if(Row[0].equals(Row[3]) && Row[3].equals(Row[6])) {
System.out.println(Side+" wins.");
Row[0] = "|";Row[3] = "|";Row[6] = "|";
return 1;
} else if(Row[1].equals(Row[4]) && Row[4].equals(Row[7])) {
System.out.println(Side+" wins.");
Row[1] = "|";Row[4] = "|";Row[7] = "|";
return 1;
} else if(Row[2].equals(Row[5]) && Row[5].equals(Row[8])) {
System.out.println(Side+" wins.");
Row[2] = "|";Row[5] = "|";Row[8] = "|";
return 1;
} else if(Row[0].equals(Row[4]) && Row[4].equals(Row[8])) {
System.out.println(Side+" wins.");
Row[0] = "\\";Row[4] = "\\";Row[8] = "\\";
return 1;
} else if(Row[2].equals(Row[4]) && Row[4].equals(Row[6])) {
System.out.println(Side+" wins.");
Row[2] = "/";Row[4] = "/";Row[6] = "/";
return 1;
}
return 0;
}
public void SideChange() {
if(Side.equals("O")) {
Side = "X";
} else {
Side = "O";
}
}
public void Move(int move) {
try {
Row[move-1] = Side;
} catch(Exception e) {
System.out.println("Tried to cheat\n Move will not be accepted");
}
}
}
}
This is pretty scholastic so I can just give you some advice and not the solution.
When you enter the new move, put a method that returns a Boolean (like isValid(int move)) and if that area is occupied it return false. Than put the moves request in a while waiting for a valid move

Java Array Bound Exception

I'm trying to make a program for a password security, but many times I get Java Array Index Out of Bounds Exception...I tried to fix, but nothing, this is my code:
import java.util.Arrays;
public class BruteForce {
public static void main(String[] args) {
String password = "aaaa";
char[] charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true) {
if (attempt.equals(password)) {
System.out.println("Password Found: " + attempt); // low security
break;
}
attempt = bf.toString();
System.out.println(attempt);
bf.increment();
}
}
private char[] cs;
private char[] cg;
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while (index >= 0) {
if (cg[index] == cs[cs.length - 1]) {
if (index == 0) {
cg = new char[cg.length + 1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString() {
return String.valueOf(cg);
}
}
When I try to add special char(s):
import java.util.Arrays;
public class BruteForce
{
public static void main(String[] args)
{
String password = "aaaa";
char[] charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.##".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true)
{
if (attempt.equals(password))
{
System.out.println("Password Found: " + attempt); // low security
break;
}
attempt = bf.toString();
System.out.println(attempt);
bf.increment();
}
}
private char[] cs;
private char[] cg;
public BruteForce(char[] characterSet, int guessLength)
{
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment()
{
int index = cg.length - 1;
while(index >= 0)
{
if (cg[index] == cs[cs.length-1])
{
if (index == 0)
{
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
}
else
{
cg[index] = cs[0];
index--;
}
}
else
{
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString()
{
return String.valueOf(cg);
}
}
And I get something like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -65
The difference between
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
and
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.##"
is that in the first case, the characters are in ascending order (characters in java have a value).
Arrays.binarySearch requires the array to be in ascending order.
If you use
"#.0123456789#ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
instead (or use Arrays.sort in the BruteForce constructor) it should work.
Always remember to post the exact code that you are using!

Boolean if statement being ignored?

I don't understand why the if statements in the final method are being ignored. Is it because I used too many if statements?
I've commented out all the if statements and tried using this code in printShowChosen(....) to see if the boolean values are actually carried over
System.out.println(showchosen[0]);
System.out.println(showchosen[1]);
System.out.println(showchosen[2]);
System.out.println(showchosen[3]);
And it printed out
true
false
false
true
Can someone explain where I went wrong?
Here is the complete code:
import javax.swing.*;
public class short8 {
public static void main(String[] args) {
String[] ShowName = {"Les Miserables","Mamma Mia","Cats", "Chicago", "Phantom of the Opera"};
String[] TheatreName = {"Queens Theatre", "Garrick Theatre", "Palmer Theatre", "Spoa Theatre", "Dend Theatre"};
boolean[] showchosen = new boolean [5];
askTouristChoices(TheatreName, showchosen);
printShowsChosen(ShowName, TheatreName, showchosen);
}//ends main
public static String askTouristChoices(String[] ShowName, boolean[] showchosen)
{
System.out.println("Please type yes if you are interested in any of the following shows:");
String interestedMiserables = JOptionPane.showInputDialog("Les Miserables");
String interestedMammaMia = JOptionPane.showInputDialog("Mamma Mia");
String interestedCats = JOptionPane.showInputDialog("Cats");
String interestedChicago = JOptionPane.showInputDialog("Chicago");
String interestedPhantom = JOptionPane.showInputDialog("Phantom of the Opera");
if ((interestedMiserables.equals("Yes")) || (interestedMiserables.equals("yes")))
{
showchosen[0] = true;
}
else if ((interestedMiserables.equals("No")) || (interestedMiserables.equals("no")))
{
showchosen[0] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
if ((interestedMammaMia.equals("Yes")) || (interestedMammaMia.equals("yes")))
{
showchosen[1] = true;
}
else if ((interestedMammaMia.equals("No")) || (interestedMammaMia.equals("no")))
{
showchosen[1] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
if ((interestedCats.equals("Yes")) || (interestedCats.equals("yes")))
{
showchosen[2] = true;
}
else if ((interestedCats.equals("No")) || (interestedCats.equals("no")))
{
showchosen[2] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
if ((interestedChicago.equals("Yes")) || (interestedChicago.equals("yes")))
{
showchosen[3] = true;
}
else if ((interestedChicago.equals("No")) || (interestedChicago.equals("no")))
{
showchosen[3] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
if ((interestedPhantom.equals("Yes")) || (interestedPhantom.equals("yes")))
{
showchosen[4] = true;
}
else if ((interestedPhantom.equals("No")) || (interestedPhantom.equals("no")))
{
showchosen[4] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
return null;
} //ends askTouristChoices
public static void printShowsChosen(String[] ShowName,String[] TheatreName, boolean[] showchosen)
{
if(showchosen[0] = true)
{
System.out.println(ShowName[0] + ": " + TheatreName[0]);
}
if(showchosen[1] = true)
{
System.out.println(ShowName[1] + ": " + TheatreName[1]);
}
if(showchosen[2] = true)
{
System.out.println(ShowName[2] + ": " + TheatreName[2]);
}
if(showchosen[3] = true)
{
System.out.println(ShowName[3] + ": " + TheatreName[3]);
}
if(showchosen[4] = true)
{
System.out.println(ShowName[4] + ": " + TheatreName[4]);
}
}//ends printShowsChosen
}//ends short8
The
if(showchosen[0] = true)
should read
if(showchosen[0] == true)
or
if(showchosen[0])
A single = is assignment, not comparison.
The statement
if(showchosen[0] = true)
should be:
if(showchosen[0] == true)
or even better:
if(showchosen[0])

Categories