Boolean if statement being ignored? - java

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])

Related

purchase management program that shows error on specific inputs in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
The code works on a linkedlist principle, and has worked alright thus far, however the code outputs an error when input is add, 1, a, 10, 5, add, 1, b, 2, 2, add, 2, b, 2, 1, inc, 2, b, print, done
the code:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;
class Prece {
private String nosaukums;
private double cena;
private int daudzums;
public Prece(String n, double c, int d) {
nosaukums = n;
cena = c;
daudzums = d;
}
public String getNosaukums() {
return nosaukums;
}
public double getCena() {
return cena;
}
public int getDaudzums() {
return daudzums;
}
public void setDaudzums(int d) {
daudzums = d;
}
public static Prece inputPrece(Scanner sc) {
String n = sc.next();
double c = sc.nextDouble();
int d = sc.nextInt();
return new Prece(n, c, d);
}
public void outputPrece() {
System.out.printf("%-20s%-10.2f%-10d\n", nosaukums, cena, daudzums);
}
}
public class Main {
public static Scanner sc;
public static void main(String[] args) {
HashMap<String, LinkedList<Prece>> pasutijumi = new HashMap<String, LinkedList<Prece>>();
sc = new Scanner(System.in);
String cmd = "";
while (!cmd.equals("done")) {
cmd = sc.next();
switch (cmd) {
case "add":
add(pasutijumi);
break;
case "print":
print(pasutijumi);
break;
case "sum":
sum(pasutijumi);
break;
case "inc":
inc(pasutijumi);
break;
case "del":
delete(pasutijumi);
break;
case "done":
System.out.println("good bye");
break;
default:
System.out.println("unknown command");
break;
}
}
sc.close();
}
public static void print(HashMap<String, LinkedList<Prece>> pasutijumi) {
LinkedList<Prece> grozs;
for (String id : pasutijumi.keySet()) {
System.out.println("ID: " + id);
grozs = pasutijumi.get(id);
String str = String.format("%-20s%-10s%-10s", "nosaukums", "cena", "daudzums");
System.out.println(str);
for (Prece prece : grozs) {
prece.outputPrece();
}
}
}
public static void inc(HashMap<String, LinkedList<Prece>> pasutijumi) {
String id = sc.next();
String productName = sc.next();
double amount = sc.nextDouble();
LinkedList<Prece> grozs = pasutijumi.get(id);
if (grozs == null) {
System.out.println("unknown client");
} else {
boolean productFound = false;
for (Prece prece : grozs) {
if (prece.getNosaukums().equals(productName)) {
prece.setDaudzums(prece.getDaudzums() + (int) amount);
productFound = true;
break;
}
}
if (!productFound) {
System.out.println("not found");
}
}
}
public static void add(HashMap<String, LinkedList<Prece>> pasutijumi) {
LinkedList<Prece> grozs;
String id = sc.next();
Prece p = Prece.inputPrece(sc);
grozs = pasutijumi.get(id);
if (grozs != null) {
grozs.add(p);
} else {
grozs = new LinkedList<Prece>();
grozs.add(p);
pasutijumi.put(id, grozs);
}
}
public static void sum(HashMap<String, LinkedList<Prece>> pasutijumi) {
for (String id : pasutijumi.keySet()) {
LinkedList<Prece> grozs = pasutijumi.get(id);
if (grozs != null) {
double sum = 0.0;
for (Prece prece : grozs) {
sum += prece.getCena() * prece.getDaudzums();
}
System.out.println("ID: " + id + " sum: " + sum);
} else {
System.out.println("unknown client");
}
}
}
public static void delete(HashMap<String, LinkedList<Prece>> pasutijumi) {
String id = sc.next();
String nosaukums = sc.next();
LinkedList<Prece> grozs = pasutijumi.get(id);
if (grozs != null) {
int index = -1;
for (int i = 0; i < grozs.size(); i++) {
if (grozs.get(i).getNosaukums().equals(nosaukums)) {
index = i;
break;
}
}
if (index >= 0) {
Prece prece = grozs.remove(index);
System.out.println("Prece " + prece.getNosaukums() + " noņemta no klienta ar ID " + id + " pasūtījuma");
} else {
System.out.println("Prece " + nosaukums + " nav atrasta klienta ar ID " + id + " pasūtījumā");
}
} else {
System.out.println("Klienta ID " + id + " nav atrasts");
}
}
}
Sorry that the code is in latvian.
I have tried changing the list types and tried bug fixing however it still shows an error.

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);
}
}

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

Refactoring lots of if statements

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.

Null Pointer Error Again

So I have this compiler class that compiles some .mjava files but others it fails on and wondering if anyone can help me figure out why. I have two methods that break for two different files. The first consts.mjava file I try to compile is:
// demo of true local and global variables
int glob0;
int glob1;
final int two = 2;
final int three = 3;
main() {
int loc1;
int loc2;
int loc3;
final int four = 4;
glob0 = three;
//print("glob0=", glob0, "\n");
loc1 = glob0*two+1;
glob1 = glob0*loc1;
loc2 = glob1+1;
loc3 = glob1*loc2/four;
print("glob0=", glob0, " (should be 3)\n");
print("glob1=", glob1, " (should be 21)\n");
print("loc1=", loc1, " (should be 7)\n");
print("loc2=", loc2, " (should be 22)\n");
print("loc3=", loc3, " (should be 115)\n");
}
When I try to compile this with my compiler class it breaks here:
private void compileFactor() {
if (isIdent(theToken)) {
String ident = theToken;
theToken = t.token();
IdentInfo theInfo = symTable.lookup(ident);
boolean its_a_variable = theInfo.isVar(); ***//Breaks Here for consts.mjava Null Exception***
int theAddr;
boolean isGlobal = theInfo.getIsGlobal();
int constValue;
int theNumber = 0;
if (its_a_variable) { // pld12: CHANGE THIS!!
theAddr = theInfo.getAddr();
isGlobal = theInfo.getIsGlobal();
if (theAddr == -1) t.error("undeclared identifier used in expr: "+ident);
if (isGlobal) cs.emit(Machine.LOAD, theAddr);
else cs.emit(Machine.LOADF, theAddr);
} else {
constValue = theInfo.getValue();
if (constValue == 0)
t.error("undeclared identifier used in expr: "+ident);
else {
cs.emitLOADINT(theNumber);
}
}
} else if (isNumber(theToken)) {
int theNumber = new Integer(theToken).intValue();
cs.emitLOADINT(theNumber);
theToken = t.token();
} else if (equals(theToken, "(")) {
accept("(");
compileExpr();
accept(")");
}
}
The next locs.mjava file I try to run breaks on this method:
private void compileIdentStmt() {
String ident = theToken;
boolean isGlobal = true;
int location = 0;
int entryPoint = 0;
IdentInfo varInfo = null;
if (!isIdent(ident)) t.error("expected identifier, got " + theToken);
theToken = t.token();
if (equals(theToken, "=")) {
accept("=");
varInfo = symTable.lookup(ident);
if (varInfo.isVar() == true) { ***//Breaks Here on locs.mjava: Null Exception***
location = varInfo.getAddr();
isGlobal = varInfo.getIsGlobal();
}
/*
if (varInfo==null) {
location = GHack(ident);
isGlobal = true;
}
if (location == -1) {
location = LHack(ident);
isGlobal = false;
}
/* */
compileExpr();
if (isGlobal) cs.emit(Machine.STOR, location);
else cs.emit(Machine.STORF, location);
accept(";");
} else if (equals(theToken, "(")) {
varInfo = symTable.lookup(ident);
if (varInfo.isProc() == true) {
entryPoint = varInfo.getEntryPoint();
dprint("call to function " + ident + "; generating JSR to location " + entryPoint);
accept("(");
}
/*
if (!equals(theToken, ")")) {
compileExpr();
while (equals(theToken, ",")) {
accept(",");
compileExpr();
}
}
/* */
accept(")");
accept(";");
cs.emit(Machine.JSR, entryPoint);
} else t.error("expected \"=\" or \"(\", got " + theToken);
}
I will even supply my lookup method from my symTable() to help:
public IdentInfo lookup(String ident) {
IdentInfo ii;
if (HMLocal != null) {
ii = HMLocal.get(ident);
if (ii != null) {
return ii;
}
ii = HMGlobal.get(ident);
if (ii != null) {
return ii;
}
}
return null;
}
If you're getting NullPointerExceptions then it's because theInfo and varInfo are null in your examples.
After
IdentInfo theInfo = symTable.lookup(ident);
you should check if theInfo is null before trying to work with it, since your lookup method clearly states it can return null.

Categories