RadioButton value Increment decrement using Java - 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);
}
}

Related

how to select players join the game and start a game

I am a beginner in Java, and I've been creating a practicing project for a game. For this purpose, I've already put some features in this project, and I separate the entire project into three files: Nimsys, NimPlayer, NimGame.
I've created these features.
addplayer into playerList in the NimPlayer.
removeplayer
editplayer
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
What I did was trying to store the user data (addplayer) from the prompt input, and brought the game to be played (last part of the incomplete code).
import java.util.Scanner;
public class Nimsys {
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
System.out.println(userName+","+familyName+""+givenName);
}
}
if (commandin.equals("startgame")) {
String dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data.length==4 && data !=null) {
for (int i = 0; i < NimPlayer.getId(); i++) {
for (int j = i + 1; j < NimPlayer.getId(); j++) {
String player1 = NimPlayer.getPlayer()[i].getUserName();
String player2 = NimPlayer.getPlayer()[j].getUserName();
if (player1==null || player2==null) {
System.out.println("One of the players does not exist. Please enter again");
} else {
System.out.println("Data built successfully.Game starts!");
break;
}
}
}
dataIn = in.nextLine();
}
int dataStone = Integer.parseInt(data[0]);
int dataRemoval = Integer.parseInt(data[1]);
}
}}
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
static int id;
//define NimPlayer data type
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
}
Above are my Nimsys and NimPlayers class. So far, I have a question:
Is it wrong to manipulate the players in the Nimplayer?
Or it is better to create an object in Nimsys if I want to store the record and the times game played?
public class NimGame {
int stoneBalance;
int stars;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
Scanner in = new Scanner(System.in);
String playOrNot;
do {
System.out.println("Initial stone count: "+datastone);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1.getUserName());
System.out.println("Player 2: "+player2.getUserName());
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
System.out.print(initialStone + " stones left:");
printStar(initialStone);
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
break;
}
}
// ask players to play again
in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
} while (playOrNot.equals("Y"));
}
And this above is my NimGame class. It's the process of the classical Nim game. What should I do to introduce the player? What I did in Nimsys is only to check if players are inside the playerList.
Thanks for taking the time to review my code. Any help is highly appreciated!
On a side note (because it won't affect the execution of the program), the name of an identifier should be self-explanatory e.g. your getPlayer method should be named as getPlayerList as it is returning the playerList, not a single player.
Your logic for startgame should be as follows:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[2])) {// Checking player1
player1 = players[i].getUserName();
break;
}
}
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[3])) {// Checking player2
player2 = players[i].getUserName();
break;
}
}
}
} while(player1 == null || player2 == null)
//...
}
You can put the repeated code in a function to make your program modular e.g.
String findPlayerByName(String name){
String player = null;
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(name)) {
player = players[i].getUserName();
break;
}
}
return player;
}
Then, the logic for startgame will reduce to:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
player1 = findPlayerByName(data[2]);
player2 = findPlayerByName(data[3]);
}
} while(player1 == null || player2 == null)
//...
}
Another thing I would like you to understand is the problem with the following line:
if (data.length==4 && data !=null)
It should be
if (data !=null && data.length==4)
This way, if data is null, the condition, data.length==4 will not be checked because && operator allows to proceed further only if the condition on its left side evaluates to true.
The problem with your line is that if data is null, you will get the NullPointerException because you will be checking .length on a null reference.
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
Currently, you have userName, familyName, and givenName attributes in NimPlayer class. You need to create two more attributes, private int score and private int numbersOfGamesPlayed with their public getters and setters. You need to use these attributes to store the value of score and the numbers of time a player has played the game.

Method that doesn't allow more participants than the maximum and same number of registration

I have a issue here. I need to create this method:
Method: registraParticipante (Aluno alu) that will receive by parameter one
student(Aluno) and add to the participant(participante) array. The method should also implement the following rules:
control not to allow more participants to register which was defined in the attribute: Maximum number of participants(qtMaxParticipantes);
not allow registration of a participant who has the same number of registration(int matricula) of an already registered participant.
I have the superclass Usuario (means User) with the int matricula in it
and the subclass Aluno (means student)
PROBLEM SOLVED - Thanks Andre.
public void registraParticipante(Aluno alu) {
if (!matriculaJaExistente(alu))
{
for (int i = 0; i < listaDeParticipantes.length; i++)
{
if (listaDeParticipantes[i] == null)
{
listaDeParticipantes[i] = alu;
break;
} else {
System.out.println("Número maximo de participante atingido.");
}
}
} else {
System.out.println("Aluno já matriculado.");
}
}
public boolean matriculaJaExistente(Aluno a)
{
boolean resultado = false;
for (int i = 0; i < listaDeParticipantes.length; i++)
{if (listaDeParticipantes[i].getMatricula() == a.getMatricula())
{
resultado = true;
}
else
{
resultado = false;
}
}
return resultado ;
}
I don't know if you necessarily have to use an array, so I guess that using a List would be the best solution, than, your code would look like this:
List<Aluno> alunosList = new ArrayList();
private int maxParticipantes = 5; // arbitrary number
public void registraParticipante(Aluno a) {
if (alunosList.size() > maxParticipantes || alunoJaRegistrado(a)) {
System.out.println("Can't add this aluno");
} else {
alunosList.add(a);
}
}
public boolean alunoJaRegistrado(Aluno aluno) {
boolean result;
for (Aluno a : alunosList) { // this goes through each aluno on the list
if (a.getMatricula() == aluno.getMatricula) {
result = true;
break;
} else result = false;
}
return result;
}

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.

trying to use search engine using jcombobox

The problem is that when I enter some character in JComboBox then it just autoselected, again I enter other text then it replace the first character, so I am not able to type multiple character in JComboBox(my JComboBox is editable)...
pleasw help.
private void combo1KeyReleased(java.awt.event.KeyEvent evt)
{
if((evt.getKeyChar() >= '0' && evt.getKeyChar() <= '9')||(evt.getKeyChar() >= 'a' && evt.getKeyChar() <= 'z')||(evt.getKeyChar() >= 'A' && evt.getKeyChar() <= 'Z')||evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)
{
try
{
Connection con=null;
ResultSet rs;
con=LoginConnection.getConnection();
String srch="";
if(con!=null)
{
srch=(String)combo1.getEditor().getItem();
System.out.println("value to search:"+srch);
String s="select name from supplier where name like '%"+srch+"%' order by name";
PreparedStatement pst=con.prepareStatement(s,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=pst.executeQuery();
int itemCount = combo1.getItemCount();
System.out.println("no of value="+itemCount);
for(int i=0;i<itemCount;i++){ //removing items
combo1.removeItemAt(0);
}
if(!rs.next())
{
System.out.println("----------------------No Data Found");
}
else
{
rs.beforeFirst();
while(rs.next())
{
combo1.addItem(rs.getString(1)); // addind item
System.out.println("while value is:"+rs.getString(1));
}
}
combo1.getEditor().setItem(srch);// adding item in field which i have fetched using getItem method
combo1.showPopup();
}
}
catch(Exception e)
{
System.out.println("ex:"+e);
}
}
}

Infinite while loop in java, not reading in sentinel

I've had this problem throughout multiple programs, but I can't remember how I fixed it last time. In the second while loop in my body, the second sentinel value is never read in for some reason. I've been trying to fix it for a while now, thought I might see if anyone had any clue.
import java.text.DecimalFormat; // imports the decimal format
public class Car {
// Makes three instance variables.
private String make;
private int year;
private double price;
// Makes the an object that formats doubles.
public static DecimalFormat twoDecPl = new DecimalFormat("$0.00");
// Constructor that assigns the instance variables
// to the values that the user made.
public Car(String carMake,int carYear, double carPrice)
{
make = carMake;
year = carYear;
price = carPrice;
}
// Retrieves variable make.
public String getMake()
{
return make;
}
// Retrieves variable year.
public int getYear()
{
return year;
}
// Retrieves variable price.
public double getPrice()
{
return price;
}
// Checks if two objects are equal.
public boolean equals(Car c1, Car c2)
{
boolean b = false;
if(c1.getMake().equals(c2.getMake()) && c1.getPrice() == c2.getPrice() &&
c1.getYear() == c2.getYear())
{
b = true;
return b;
}
else
{
return b;
}
}
// Turns the object into a readable string.
public String toString()
{
return "Description of car:" +
"\n Make : " + make +
"\n Year : " + year +
"\n Price: " + twoDecPl.format(price);
}
}
import java.util.Scanner; // imports a scanner
public class CarSearch {
public static void main(String[] args)
{
// initializes all variables
Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car[] carArr = new Car[SIZE_ARR];
final String SENT = "EndDatabase";
String carMake = "";
int carYear = 0;
double carPrice = 0;
int count = 0;
int pos = 0;
final String SECSENT = "EndSearchKeys";
final boolean DEBUG_SW = true;
// Loop that goes through the first list of values.
// It then stores the values in an array, then uses the
// values to make an object.
while(scan.hasNext())
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car car1 = new Car(carMake, carYear, carPrice);
carArr[count] = car1;
count++;
}
// Calls the method debugSwitch to show the debug information.
debugSwitch(carArr, DEBUG_SW, count);
// Calls the method printData to print the database.
printData(carArr, count);
// Loops through the second group of values and stores them in key.
// Then, it searches for a match in the database.
**while(scan.hasNext())**
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SECSENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car key = new Car(carMake, carYear, carPrice);
// Stores the output of seqSearch in pos.
// If the debug switch is on, then it prints these statements.
if(DEBUG_SW == true)
{
System.out.println("Search, make = " + key.getMake());
System.out.println("Search, year = " + key.getYear());
System.out.println("Search, price = " + key.getPrice());
}
System.out.println("key =");
System.out.println(key);
pos = seqSearch(carArr, count, key);
if(pos != -1)
{
System.out.println("This vehicle was found at index = " + pos);
}
else
{
System.out.println("This vehicle was not found in the database.");
}
}
}
// This method prints the database of cars.
private static void printData(Car[] carArr, int count)
{
for(int i = 0; i < count; i++)
{
System.out.println("Description of car:");
System.out.println(carArr[i]);
}
}
// Searches for a match in the database.
private static int seqSearch(Car[] carArr, int count, Car key)
{
for(int i = 0; i < count; i++)
{
boolean b = key.equals(key, carArr[i]);
if(b == true)
{
return i;
}
}
return -1;
}
// Prints debug statements if DEBUG_SW is set to true.
public static void debugSwitch(Car[] carArr, boolean DEBUG_SW, int count)
{
if(DEBUG_SW == true)
{
for(int i = 0; i < count; i++)
{
System.out.println("DB make = " + carArr[i].getMake());
System.out.println("DB year = " + carArr[i].getYear());
System.out.println("DB price = " + carArr[i].getPrice());
}
}
}
}
I think this is your problem, but I might be wrong:
Inside your while loop, you have these calls:
next()
nextInt()
nextDouble()
The problem is that the last call (nextDouble), will not eat the newline. So to fix this issue, you should add an extra nextLine() call at the end of the two loops.
What happens is that the next time you call next(), it will return the newline, instead of the CarMake-thing.

Categories