I am looking for some help scanning the array for the used letters in the user input and tell them, so I am lost at this point.
/**
*
*/
package Hangman;
import java.io.IOException;
/**
* #author
*
*/
public class Hangman {
static int choice;
static String solve;
static String promt;
static String guess;
static char chaGuess;
static char[] guesses = new char[25];
static char[] check;
static int counter = 1;
static boolean contine;
public static void main(String[] args) throws IOException, InterruptedException {
playerOne();
for (int i = 0; i < 300; i++) {
System.out.println(" ");
}
while (contine = true) {
playerTwo();
choiceMade(choice);
}
}
public static String playerOne() throws IOException {
System.out.println("Welcome player one");
promt = ConsoleUI.promptForInput("Enter a Phrase or word for Player Two to guess", true);
return promt;
}
public static int playerTwo() throws IOException {
String[] ask = new String[3];
ask[0] = "Give up";
ask[1] = "Guess a letter";
ask[2] = "Solve the puzle";
choice = ConsoleUI.promptForMenuSelection(ask, true);
return choice;
}
public static void choiceMade(int c) throws IOException {
if (c == 0) {
contine = false;
System.out.println("Thank you for playing");
System.exit(0);
}
if (c == 1) {
guess = ConsoleUI.promptForInput("Enter your guess", true);
guessChar(guess);
contine = true;
} else if (c == 2) {
solve = ConsoleUI.promptForInput("Enter your answer", true);
if (solve.equals(promt)) {
System.out.println("You solved it you're amazing");
contine= false;
} else {
System.out.println("Sorry you guessed it wrong.");
System.exit(0);
contine= false;
}
}
}
public static char guessChar(String g) {
chaGuess = g.charAt(0);
promt = promt.replace(" ", "");
check = promt.toCharArray();
if(guesses[counter -1] != chaGuess)
if (chaGuess >= 'a' && chaGuess <= 'z' || chaGuess >= 'A' && chaGuess <= 'Z') {
guesses[counter] = chaGuess;
System.out.println(guesses);
}
if(guesses[counter - 1] == chaGuess)
{
System.out.println("You all ready guessed that");
}
}
counter++;
return chaGuess;
}
}
Use a string, append each used guess to the end of it, and then just use indexOf()
I can only do the 4 operations,
I'm having a problem on how to input expressions like this, sin(60)*50/4
without GUI and using Scanner only.
Sorry but I'm just a newbie in programming and still learning the basics.
(1st time in programming subject XD)
This is my current code. I'm having a hard time on how to add sin, cos, tan, square, mod and exponent in my calculator.
import java.util.*;
public class Calculator {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int check=0;
while (check==0)
{
String sInput, sReal, sToken, sMToken, sMULTd;
int t, M, Md, term, a, b, sb, sbb;
System.out.print("Enter Expression: ");
sInput=sc.nextLine();
if (sInput.charAt(0)== '-')
{
sReal = sInput.substring(0,1) + minusTracker(sInput.substring(1));
System.out.print(sReal);
}
else
{
sReal = minusTracker(sInput);
System.out.print(sReal);
}
StringTokenizer sADD = new StringTokenizer(sReal, "+");
t = sADD.countTokens();
double iTerm[] = new double [t];
while(sADD.hasMoreTokens())
{
sToken = sADD.nextToken();
for(a=0; a<=(sToken.length()-1); a++)
{
b=a+1;
if( ((sToken.substring(a,b)).equals("*")) || ((sToken.substring(a,b)).equals("/")) )
{
StringTokenizer sMULT = new StringTokenizer(sToken, "*");
M = sMULT.countTokens();
double iMTerm[] = new double [M];
while(sMULT.hasMoreTokens())
{
sMToken = sMULT.nextToken();
for(sb=0; sb<=(sMToken.length()-1); sb++)
{
sbb= sb+1;
if((sMToken.substring(sb,sbb)).equals("/"))
{
StringTokenizer sMULTdiv = new StringTokenizer(sMToken, "/");
Md = sMULTdiv.countTokens();
double iMdTerm[] = new double [Md];
while(sMULTdiv.hasMoreTokens())
{
sMULTd = sMULTdiv.nextToken();
iMdTerm[--Md] = Double.parseDouble(sMULTd);
}
double MdTotal = getMdQuotient(iMdTerm);
sMToken = Double.toString(MdTotal);
}
}
iMTerm[--M] = Double.parseDouble(sMToken);
double mProduct = getMProduct(iMTerm);
sToken = Double.toString(mProduct);
}
}
}
iTerm[--t]= Double.parseDouble(sToken);
double finalAnswer = getSum(iTerm);
if(sADD.hasMoreTokens()==false)
System.out.println(" = " + finalAnswer );
}
}
}
public static String minusTracker(String sInput)
{
if(sInput.isEmpty())
{
return "";
}
else if(sInput.charAt(0)== '*' || sInput.charAt(0)=='/' || sInput.charAt(0)=='+' )
{
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else if( sInput.charAt(0)== '-')
{
if(sInput.charAt(1)== '-')
{
sInput = sInput.replaceFirst("--", "+");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else
{
sInput = sInput.replaceFirst("-", "+-");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
}
else
{
return sInput.substring(0,1) + minusTracker(sInput.substring(1));
}
}
public static double getMdQuotient(double iMdTerm[])
{
double quotient= iMdTerm[(iMdTerm.length)-1];
for(int y=(iMdTerm.length)-2; y>=0; y--)
{
quotient = quotient / iMdTerm[y];
}
return quotient;
}
public static double getMProduct(double iMTerm[])
{
double product= 1;
for(int z=(iMTerm.length)-1; z>=0; z--)
{
product = product * iMTerm[z];
}
return product;
}
public static double getSum(double iTerm[])
{
double sum= 0;
for(int z=(iTerm.length)-1; z>=0; z--)
{
sum = sum + iTerm[z];
}
return sum;
}
}
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.
I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.
OK, I don't know how to word this question, but maybe my code will spell out the problem:
public class ControllerTest
{
public static void main(String [] args)
{
GamePadController rockbandDrum = new GamePadController();
DrumMachine drum = new DrumMachine();
while(true)
{
try{
rockbandDrum.poll();
if(rockbandDrum.isButtonPressed(1)) //BLUE PAD HhiHat)
{
drum.playSound("hiHat.wav");
Thread.sleep(50);
}
if(rockbandDrum.isButtonPressed(2)) //GREEN PAD (Crash)
{
//Todo: Change to Crash
drum.playSound("hiHat.wav");
Thread.sleep(50);
}
//Etc....
}
}
}
public class DrumMachine
{
InputStream soundPlayer = null;
AudioStream audio = null;
static boolean running = true;
public void playSound(String soundFile)
{
//Tak a sound file as a paramater and then
//play that sound file
try{
soundPlayer = new FileInputStream(soundFile);
audio = new AudioStream(soundPlayer);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
AudioPlayer.player.start(audio);
}
//Etc... Methods for multiple audio clip playing
}
Now the problem is, if I lower the delay in the
Thread.sleep(50)
then the sound plays multiple times a second, but if I keep at this level or any higher, I could miss sounds being played...
It's an odd problem, where if the delay is too low, the sound loops. But if it's too high it misses playing sounds. Is this just a problem where I would need to tweak the settings, or is there any other way to poll the controller without looping sound?
Edit: If I need to post the code for polling the controller I will...
import java.io.*;
import net.java.games.input.*;
import net.java.games.input.Component.POV;
public class GamePadController
{
public static final int NUM_BUTTONS = 13;
// public stick and hat compass positions
public static final int NUM_COMPASS_DIRS = 9;
public static final int NW = 0;
public static final int NORTH = 1;
public static final int NE = 2;
public static final int WEST = 3;
public static final int NONE = 4; // default value
public static final int EAST = 5;
public static final int SW = 6;
public static final int SOUTH = 7;
public static final int SE = 8;
private Controller controller;
private Component[] comps; // holds the components
// comps[] indices for specific components
private int xAxisIdx, yAxisIdx, zAxisIdx, rzAxisIdx;
// indices for the analog sticks axes
private int povIdx; // index for the POV hat
private int buttonsIdx[]; // indices for the buttons
private Rumbler[] rumblers;
private int rumblerIdx; // index for the rumbler being used
private boolean rumblerOn = false; // whether rumbler is on or off
public GamePadController()
{
// get the controllers
ControllerEnvironment ce =
ControllerEnvironment.getDefaultEnvironment();
Controller[] cs = ce.getControllers();
if (cs.length == 0) {
System.out.println("No controllers found");
System.exit(0);
}
else
System.out.println("Num. controllers: " + cs.length);
// get the game pad controller
controller = findGamePad(cs);
System.out.println("Game controller: " +
controller.getName() + ", " +
controller.getType());
// collect indices for the required game pad components
findCompIndices(controller);
findRumblers(controller);
} // end of GamePadController()
private Controller findGamePad(Controller[] cs)
/* Search the array of controllers until a suitable game pad
controller is found (eith of type GAMEPAD or STICK).
*/
{
Controller.Type type;
int i = 0;
while(i < cs.length) {
type = cs[i].getType();
if ((type == Controller.Type.GAMEPAD) ||
(type == Controller.Type.STICK))
break;
i++;
}
if (i == cs.length) {
System.out.println("No game pad found");
System.exit(0);
}
else
System.out.println("Game pad index: " + i);
return cs[i];
} // end of findGamePad()
private void findCompIndices(Controller controller)
/* Store the indices for the analog sticks axes
(x,y) and (z,rz), POV hat, and
button components of the controller.
*/
{
comps = controller.getComponents();
if (comps.length == 0) {
System.out.println("No Components found");
System.exit(0);
}
else
System.out.println("Num. Components: " + comps.length);
// get the indices for the axes of the analog sticks: (x,y) and (z,rz)
xAxisIdx = findCompIndex(comps, Component.Identifier.Axis.X, "x-axis");
yAxisIdx = findCompIndex(comps, Component.Identifier.Axis.Y, "y-axis");
zAxisIdx = findCompIndex(comps, Component.Identifier.Axis.Z, "z-axis");
rzAxisIdx = findCompIndex(comps, Component.Identifier.Axis.RZ, "rz-axis");
// get POV hat index
povIdx = findCompIndex(comps, Component.Identifier.Axis.POV, "POV hat");
findButtons(comps);
} // end of findCompIndices()
private int findCompIndex(Component[] comps,
Component.Identifier id, String nm)
/* Search through comps[] for id, returning the corresponding
array index, or -1 */
{
Component c;
for(int i=0; i < comps.length; i++) {
c = comps[i];
if ((c.getIdentifier() == id) && !c.isRelative()) {
System.out.println("Found " + c.getName() + "; index: " + i);
return i;
}
}
System.out.println("No " + nm + " component found");
return -1;
} // end of findCompIndex()
private void findButtons(Component[] comps)
/* Search through comps[] for NUM_BUTTONS buttons, storing
their indices in buttonsIdx[]. Ignore excessive buttons.
If there aren't enough buttons, then fill the empty spots in
buttonsIdx[] with -1's. */
{
buttonsIdx = new int[NUM_BUTTONS];
int numButtons = 0;
Component c;
for(int i=0; i < comps.length; i++) {
c = comps[i];
if (isButton(c)) { // deal with a button
if (numButtons == NUM_BUTTONS) // already enough buttons
System.out.println("Found an extra button; index: " + i + ". Ignoring it");
else {
buttonsIdx[numButtons] = i; // store button index
System.out.println("Found " + c.getName() + "; index: " + i);
numButtons++;
}
}
}
// fill empty spots in buttonsIdx[] with -1's
if (numButtons < NUM_BUTTONS) {
System.out.println("Too few buttons (" + numButtons +
"); expecting " + NUM_BUTTONS);
while (numButtons < NUM_BUTTONS) {
buttonsIdx[numButtons] = -1;
numButtons++;
}
}
} // end of findButtons()
private boolean isButton(Component c)
/* Return true if the component is a digital/absolute button, and
its identifier name ends with "Button" (i.e. the
identifier class is Component.Identifier.Button).
*/
{
if (!c.isAnalog() && !c.isRelative()) { // digital and absolute
String className = c.getIdentifier().getClass().getName();
// System.out.println(c.getName() + " identifier: " + className);
if (className.endsWith("Button"))
return true;
}
return false;
} // end of isButton()
private void findRumblers(Controller controller)
/* Find the rumblers. Use the last rumbler for making vibrations,
an arbitrary decision. */
{
// get the game pad's rumblers
rumblers = controller.getRumblers();
if (rumblers.length == 0) {
System.out.println("No Rumblers found");
rumblerIdx = -1;
}
else {
System.out.println("Rumblers found: " + rumblers.length);
rumblerIdx = rumblers.length-1; // use last rumbler
}
} // end of findRumblers()
// ----------------- polling and getting data ------------------
public void poll()
// update the component values in the controller
{
controller.poll();
}
public int getXYStickDir()
// return the (x,y) analog stick compass direction
{
if ((xAxisIdx == -1) || (yAxisIdx == -1)) {
System.out.println("(x,y) axis data unavailable");
return NONE;
}
else
return getCompassDir(xAxisIdx, yAxisIdx);
} // end of getXYStickDir()
public int getZRZStickDir()
// return the (z,rz) analog stick compass direction
{
if ((zAxisIdx == -1) || (rzAxisIdx == -1)) {
System.out.println("(z,rz) axis data unavailable");
return NONE;
}
else
return getCompassDir(zAxisIdx, rzAxisIdx);
} // end of getXYStickDir()
private int getCompassDir(int xA, int yA)
// Return the axes as a single compass value
{
float xCoord = comps[ xA ].getPollData();
float yCoord = comps[ yA ].getPollData();
// System.out.println("(x,y): (" + xCoord + "," + yCoord + ")");
int xc = Math.round(xCoord);
int yc = Math.round(yCoord);
// System.out.println("Rounded (x,y): (" + xc + "," + yc + ")");
if ((yc == -1) && (xc == -1)) // (y,x)
return NW;
else if ((yc == -1) && (xc == 0))
return NORTH;
else if ((yc == -1) && (xc == 1))
return NE;
else if ((yc == 0) && (xc == -1))
return WEST;
else if ((yc == 0) && (xc == 0))
return NONE;
else if ((yc == 0) && (xc == 1))
return EAST;
else if ((yc == 1) && (xc == -1))
return SW;
else if ((yc == 1) && (xc == 0))
return SOUTH;
else if ((yc == 1) && (xc == 1))
return SE;
else {
System.out.println("Unknown (x,y): (" + xc + "," + yc + ")");
return NONE;
}
} // end of getCompassDir()
public int getHatDir()
// Return the POV hat's direction as a compass direction
{
if (povIdx == -1) {
System.out.println("POV hat data unavailable");
return NONE;
}
else {
float povDir = comps[povIdx].getPollData();
if (povDir == POV.CENTER) // 0.0f
return NONE;
else if (povDir == POV.DOWN) // 0.75f
return SOUTH;
else if (povDir == POV.DOWN_LEFT) // 0.875f
return SW;
else if (povDir == POV.DOWN_RIGHT) // 0.625f
return SE;
else if (povDir == POV.LEFT) // 1.0f
return WEST;
else if (povDir == POV.RIGHT) // 0.5f
return EAST;
else if (povDir == POV.UP) // 0.25f
return NORTH;
else if (povDir == POV.UP_LEFT) // 0.125f
return NW;
else if (povDir == POV.UP_RIGHT) // 0.375f
return NE;
else { // assume center
System.out.println("POV hat value out of range: " + povDir);
return NONE;
}
}
} // end of getHatDir()
public boolean[] getButtons()
/* Return all the buttons in a single array. Each button value is
a boolean. */
{
boolean[] buttons = new boolean[NUM_BUTTONS];
float value;
for(int i=0; i < NUM_BUTTONS; i++) {
value = comps[ buttonsIdx[i] ].getPollData();
buttons[i] = ((value == 0.0f) ? false : true);
}
return buttons;
} // end of getButtons()
public boolean isButtonPressed(int pos)
/* Return the button value (a boolean) for button number 'pos'.
pos is in the range 1-NUM_BUTTONS to match the game pad
button labels.
*/
{
if ((pos < 1) || (pos > NUM_BUTTONS)) {
System.out.println("Button position out of range (1-" +
NUM_BUTTONS + "): " + pos);
return false;
}
if (buttonsIdx[pos-1] == -1) // no button found at that pos
return false;
float value = comps[ buttonsIdx[pos-1] ].getPollData();
// array range is 0-NUM_BUTTONS-1
return ((value == 0.0f) ? false : true);
} // end of isButtonPressed()
// ------------------- Trigger a rumbler -------------------
public void setRumbler(boolean switchOn)
// turn the rumbler on or off
{
if (rumblerIdx != -1) {
if (switchOn)
rumblers[rumblerIdx].rumble(0.8f); // almost full on for last rumbler
else // switch off
rumblers[rumblerIdx].rumble(0.0f);
rumblerOn = switchOn; // record rumbler's new status
}
} // end of setRumbler()
public boolean isRumblerOn()
{ return rumblerOn; }
} // end of GamePadController class
I think you are using the wrong design pattern here. You should use the observer pattern for this type of thing.
A polling loop not very efficient, and as you've noticed doesn't really yield the desired results.
I'm not sure what you are using inside your objects to detect if a key is pressed, but if it's a GUI architecture such as Swing or AWT it will be based on the observer pattern via the use of EventListeners, etc.
Here is a (slightly simplified) Observer-pattern
applied to your situation.
The advantage of this design is that when a button
is pressed and hold, method 'buttonChanged' will
still only be called once, instead of start
'repeating' every 50 ms.
public static final int BUTTON_01 = 0x00000001;
public static final int BUTTON_02 = 0x00000002;
public static final int BUTTON_03 = 0x00000004;
public static final int BUTTON_04 = 0x00000008; // hex 8 == dec 8
public static final int BUTTON_05 = 0x00000010; // hex 10 == dec 16
public static final int BUTTON_06 = 0x00000020; // hex 20 == dec 32
public static final int BUTTON_07 = 0x00000040; // hex 40 == dec 64
public static final int BUTTON_08 = 0x00000080; // etc.
public static final int BUTTON_09 = 0x00000100;
public static final int BUTTON_10 = 0x00000200;
public static final int BUTTON_11 = 0x00000400;
public static final int BUTTON_12 = 0x00000800;
private int previousButtons = 0;
void poll()
{
rockbandDrum.poll();
handleButtons();
}
private void handleButtons()
{
boolean[] buttons = getButtons();
int pressedButtons = getPressedButtons(buttons);
if (pressedButtons != previousButtons)
{
buttonChanged(pressedButtons); // Notify 'listener'.
previousButtons = pressedButtons;
}
}
public boolean[] getButtons()
{
// Return all the buttons in a single array. Each button-value is a boolean.
boolean[] buttons = new boolean[MAX_NUMBER_OF_BUTTONS];
float value;
for (int i = 0; i < MAX_NUMBER_OF_BUTTONS-1; i++)
{
int index = buttonsIndex[i];
if (index < 0) { continue; }
value = comps[index].getPollData();
buttons[i] = ((value == 0.0f) ? false : true);
}
return buttons;
}
private int getPressedButtons(boolean[] array)
{
// Mold all pressed buttons into a single number by OR-ing their values.
int pressedButtons = 0;
int i = 1;
for (boolean isBbuttonPressed : array)
{
if (isBbuttonPressed) { pressedButtons |= getOrValue(i); }
i++;
}
return pressedButtons;
}
private int getOrValue(int btnNumber) // Get a value to 'OR' with.
{
int btnValue = 0;
switch (btnNumber)
{
case 1 : btnValue = BUTTON_01; break;
case 2 : btnValue = BUTTON_02; break;
case 3 : btnValue = BUTTON_03; break;
case 4 : btnValue = BUTTON_04; break;
case 5 : btnValue = BUTTON_05; break;
case 6 : btnValue = BUTTON_06; break;
case 7 : btnValue = BUTTON_07; break;
case 8 : btnValue = BUTTON_08; break;
case 9 : btnValue = BUTTON_09; break;
case 10 : btnValue = BUTTON_10; break;
case 11 : btnValue = BUTTON_11; break;
case 12 : btnValue = BUTTON_12; break;
default : assert false : "Invalid button-number";
}
return btnValue;
}
public static boolean checkButton(int pressedButtons, int buttonToCheckFor)
{
return (pressedButtons & buttonToCheckFor) == buttonToCheckFor;
}
public void buttonChanged(int buttons)
{
if (checkButton(buttons, BUTTON_01)
{
drum.playSound("hiHat.wav");
}
if (checkButton(buttons, BUTTON_02)
{
drum.playSound("crash.wav");
}
}
Please post more information about the GamePadController class that you are using.
More than likely, that same library will offer an "event" API, where a "callback" that you register with a game pad object will be called as soon as the user presses a button. With this kind of setup, the "polling" loop is in the framework, not your application, and it can be much more efficient, because it uses signals from the hardware rather than a busy-wait polling loop.
Okay, I looked at the JInput API, and it is not really event-driven; you have to poll it as you are doing. Does the sound stop looping when you release the button? If so, is your goal to have the sound play just once, and not again until the button is release and pressed again? In that case, you'll need to track the previous button state each time through the loop.
Human response time is about 250 ms (for an old guy like me, anyway). If you are polling every 50 ms, I'd expect the controller to report the button depressed for several iterations of the loop. Can you try something like this:
boolean played = false;
while (true) {
String sound = null;
if (controller.isButtonPressed(1))
sound = "hiHat.wav";
if (controller.isButtonPressed(2))
sound = "crash.wav";
if (sound != null) {
if (!played) {
drum.playSound(sound);
played = true;
}
} else {
played = false;
}
Thread.sleep(50);
}