Java NameLengthNotValidException always gets thrown in domainclass - java

IMPORTANT: Probably a rookie question, but I'm clueless on how to solve it.
I have a UI class which I use to input a name and gender (geslacht) using a scanner (see code below)
private static void geefNaamEnGeslacht(int aantal) {
String naam, geslacht;
for (int i = 0; i < aantal; i++) {
System.out.print("Wat is de naam van speler " + (i + 1) + " (min 6 tekens, max 12 tekens)? ");
naam = sc.next();
naam += sc.nextLine();
System.out.print("Wat is het geslacht van speler " + (i + 1) + "(man=m vrouw=v)? ");
geslacht = sc.next();
System.out.println(naam.length());
try {
dc.maakSpelerAan(naam, geslacht.charAt(0));
} catch (NameLengthNotValidException e) {
System.out.println(e.getMessage());
i--;
}
}
}
In my domain class I check the length of that name in the setter, but it always throws the exception, no matter what I tried. When debugging, the length of any name I picked checks out to be between 6 and 12 characters strangely enough. (see code below)
public final void setNaam(String naam) {
int lengte = naam.length();
if (naam.length() < 6 || naam.length() > 12) {
throw new NameLengthNotValidException("Je naam moet tussen 6 en 12 tekens liggen!");
}
this.naam = naam;
}
Any ideas or tips are apreciated.
EDIT1 code of dc.maakSpelerAan
public void maakSpelerAan(String naam, char geslacht){
s.maakSpeler(naam, geslacht);
}
EDIT2 code of s.maakspeler
public void maakSpeler(String naam, char geslacht){
if (spelCompleet()) {
throw new ListFilledException("De lijst met spelers is vol !");
}
if (!controleerUniekeNaam(naam)) {
throw new NotUniqueNameException();
}
Kaart[] schatkaarten = new Kaart[STARTAANTAL];
Kaart[] kerkerkaarten = new Kaart[STARTAANTAL];
for (int i = 0; i > STARTAANTAL; i++) {
schatkaarten[i] = stapels.get(SCHATKAART).geefBovensteKaart();
kerkerkaarten[i] = stapels.get(KERKERKAART).geefBovensteKaart();
}
try{
Speler s = new Speler(naam, geslacht);
s.getKaarten(kerkerkaarten, schatkaarten);
spelers.add(s);
}catch (IllegalArgumentException | NameLengthNotValidException e){
throw e;
}
if (spelCompleet()) {
//UC2
spelers.get(EERSTESPELERINDEX).setBeurt(true);
}
}
EDIT3 REPOST WITH CORRECT IMAGE Image of variable "naam" right before it goes in the IF loop while debugging. MINLENGTHNAAM and MAXLENGTHNAAM are set to 6 and 12 respectively in an interface class.
EDIT4 Code in my interface class for MINLENGTH AND MAXLENGTH
public interface SpelInfo {
final int STARTAANTAL = 2;
final int MAXAANTALPUNTEN = 10;
final int INDEXNAAMDETAILS = 0;
final int INDEXGESLACHTDETAILS = 1;
final int INDEXPUNTENDETAILS = 2;
final int MINAANTALSPELERS = 3;
final int MAXAANTALSPELERS= 6;
final int EERSTESPELERINDEX = 0;
final int MAXLENGTHNAAM = 6;
final int MINLENGTHNAAM = 12;
final int AANTALSTAPELS = 2;
final char MAN = 'm';
final char VROUW = 'v';
final int SCHATKAART = 0;
final int KERKERKAART = 1;
}

In "Edit4" you need to change the green line into:
if(naam.length() > MAXLENGTHNAAM || naam.length() < MINLENGTHNAAM) {
Just a little logical issue :)

Related

Running my world generation code ends up in 2 or more ArrayIndexOutOfBoundsExceptions

So I'm coding my text-based game with world generation and my friend coded the world generation. He's away right now so I have to ask this.
The code should generate an array with the X and Y positions of chests that spawn in random positions. The packages used are: java.util.Scanner,
java.util.Arrays,
java.util.Random,
Class is declared but I'm not including it in this snippet.
The Code for the method worldgen():
static double[] worldgen() {
//coded by *my friend, name censored*
int random_int_1 = 0;
int random_int_2 = 0;
int x;
int y;
int chest_x;
int chest_y;
double[] chest_x_values;
double[] chest_y_values;
int mineral_x;
int mineral_y;
// chest_x_and_y_values[something (or else)] = chest_x_values[something];
// chest_x_and_y_values[something else] = chest_y_values[something];
Random rand1 = new Random();
int num_of_chests = rand1.nextInt(100);
chest_x_values = new double[num_of_chests];
chest_y_values = new double[num_of_chests];
while (random_int_1 <= num_of_chests)
{
Random rand2 = new Random();
chest_x = rand2.nextInt(301);
System.out.println(chest_x);
chest_x_values[random_int_1] = chest_x;
System.out.println(Arrays.toString(chest_x_values));
if(random_int_1 <= num_of_chests) {
random_int_1++;
System.out.println(random_int_1);
}
}
while (random_int_2 <= num_of_chests)
{
Random rand3 = new Random();
chest_y = rand3.nextInt(301);
chest_y_values[random_int_2] = chest_y;
random_int_2 = random_int_2 + 1;
}
int random_int_3 = num_of_chests;
random_int_1 = 0;
random_int_2 = 0;
double[] chest_x_and_y_values = new double[random_int_3 = random_int_3*2+1];
while (random_int_1 <= random_int_3) {
chest_x_and_y_values[random_int_1] = chest_x_values[random_int_1];
random_int_1 = random_int_1 + 1;
}
chest_x_and_y_values[random_int_1+1] = -1;
while (random_int_2 <= random_int_3) {
chest_x_and_y_values[random_int_1 + 1 + random_int_2] = chest_y_values[random_int_2];
random_int_2 = random_int_2 + 1;
}
return chest_x_and_y_values;
}
public static void main(String[] args) {
//coded by EnZon3
Scanner uIn = new Scanner(System.in);
System.out.println("-------------------------------");
System.out.println(" *game name censored* ");
System.out.println(" 1: Generate new world.. ");
System.out.println(" 2: Generate w/ custom seed.. ");
System.out.println(" 3: See world data ");
System.out.println(" 4: Exit ");
System.out.println("-------------------------------");
int option = uIn.nextInt();
if (option > 4) {
System.err.println("Error 0x1: Not an option");
}
while (option != 4) {
if (option == 1) {
double[] world = worldgen();
System.out.println(Arrays.toString(world));
}
}
}
The error I get is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 77 out of bounds for length 77 at
.worldgen(.java:35) at .main(.java:86)
I've tried tweaking the values but that didn't work
while (random_int_1 <= num_of_chests)
This should be < (strictly less than), remember arrays are 0 indexed.
while (random_int_2 <= num_of_chests)
Same thing here
while (random_int_1 <= random_int_3) {
chest_x_and_y_values[random_int_1] = chest_x_values[random_int_1];
random_int_1 = random_int_1 + 1;
}
random_int_3 is 2 * num_of_chests +1, and chest_x_values is a list of length num_of_chests. In this part, random_int_1 can go all the way up to 2 * num_of_chests +1 which is higher than chest_x_values.

Why is ArraysUtils.addElement not working as it should be?

I have this code that asks for numbers and then introduces them into an array, then, I have to separate positives, negatives and nulls.
I'm having trouble with creating the array of each type.
For example, I start the code, I introduce 5 numbers(1,2,3,4,5), then goes to the method that assings the positives to the positiveArray, negatives to the negativeArray and nulls to the nulledArray.
But when I print, for example, positiveArray, only adds at the final index
I read that everytime I call ArrayUtils.add(), it should be placing the number at the end, but not like what I'm getting, that should be like this:
int[] numbers= new int[4];
numbers = ArrayUtils.add(numbers , 1);
numbers = ArrayUtils.add(numbers , 2);
numbers = ArrayUtils.add(numbers , 3);
numbers = ArrayUtils.add(numbers , 4);
numbers = {1,2,3,4}
Or am I wrong?
I'm using ApacheCommons
Thanks
import java.util.Arrays;
import javax.swing.JOptionPane;
import org.apache.commons.lang3.ArrayUtils;
public class das {
private int cantidadElementos = 0;
private int pos = 0, neg = 0, nulos = 0; //contadores de los números positivos y negativos
private int[] numeros = new int[10]; //array que contendrá los números leídos por teclado
private int[] numerosNegativos;
private int[] numerosPositivos;
private int[] numerosNulos;
public static void main(String[] args) {
das das = new das();
das.agregarElementos();
das.cantidadPositivos();
}
public void agregarElementos(){
int i = 0;
for (i = 0; i < 10; i++) {
try {
numeros[i] = (Integer.parseInt(JOptionPane.showInputDialog(null, "Introduce un valor", "Agregando elemento ["+cantidadElementos+"]", JOptionPane.QUESTION_MESSAGE)));
if(numeros[i] > 0)
{
pos++;
}
else if (numeros[i] < 0)
{
neg++;
}
else
{
nulos++;
}
cantidadElementos++;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Has agregado "+cantidadElementos+" elementos.", "Información que cura", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
}
public void cantidadPositivos(){
int i = 0;
for(i = 0; i < cantidadElementos; i++)
{
if(numeros[i] >= 1)
{
numerosPositivos = new int[pos];
numerosPositivos = ArrayUtils.add(numerosPositivos, numeros[i]);
System.out.println(Arrays.toString(numerosPositivos));
}
else if (numeros[i] <=-1)
{
numerosNegativos = new int[neg];
numerosNegativos = ArrayUtils.add(numerosNegativos, numeros[i]);
}
else
{
numerosNulos = new int[nulos];
numerosNulos = ArrayUtils.add(numerosNulos, numeros[i]);
}
}
JOptionPane.showMessageDialog(null, "De los [ "+cantidadElementos +" ] elementos en el vector:\n\nPositivos: "+ pos +"\n\nNegativos: "+ neg +"\n\nNulos: " + nulos + "\n", "Información que cura", JOptionPane.INFORMATION_MESSAGE, null);
}
}
The problem is that you recreate a new array at each iteration, like this line (in cantidadPositivos()):
numerosPositivos = new int[pos];
You should define those arrays before entering the for cycle.
public void cantidadPositivos(){
int i = 0;
numerosPositivos = new int[pos];
numerosNegativos = new int[neg];
numerosNulos = new int[nulos];
for(i = 0; i < cantidadElementos; i++)
{
if(numeros[i] >= 1)
{
numerosPositivos = ArrayUtils.add(numerosPositivos, numeros[i]);
System.out.println(Arrays.toString(numerosPositivos));
}
else if (numeros[i] <=-1)
{
numerosNegativos = ArrayUtils.add(numerosNegativos, numeros[i]);
}
else
{
numerosNulos = ArrayUtils.add(numerosNulos, numeros[i]);
}
}
JOptionPane.showMessageDialog(null, "De los [ "+cantidadElementos +" ] elementos en el vector:\n\nPositivos: "+ pos +"\n\nNegativos: "+ neg +"\n\nNulos: " + nulos + "\n", "Información que cura", JOptionPane.INFORMATION_MESSAGE, null);
}
When you use new int[4] you get an array like [0, 0, 0, 0] since int is primitive so it cannot be null.
ArrayUtil.add does not replace those 0 values, since they are valid entries, so it just appends your new number to the array.
So i would suggest to start with an empty array.

Why am I getting an input mismatch exception in thread "main"?

I marked where I got the exception and I don't know why it's happening. This code finds the popularity and meaning of a name that the user types in . It also makes a graph(but it doesn't work)
The files are too long to put on here but on line examples are: names.txt:
Brenda f 0 0 0 0 917 42 14 13 40 115 123 172 426 (popularity), meanings.txt:
BRITTANY f English From the name of the region in the northwest of France, called in French Bretagne.(meaning)
1. Why am I getting this exception?
2. How do I fix the exception?
3. Why isn't my graph drawing the bars (in method changingGraph)
Example Console Output:
Name: aaron
Aaron f 0 0 0 0 0 0 0 0 0 883 0 0 0
AARON m English, Biblical From the Hebrew name ??????? ('Aharon) which is most likely of unknown Egyptian origin.
Exception:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at BabyNames.changingGraph(BabyNames.java:131)
at BabyNames.main(BabyNames.java:32)
my code:
import java.util.*;
import java.io.*;
import java.awt.*;
public class BabyNames{
public static final int STARTINGYEAR = 1890;
public static final int WIDTH = 60;
public static final int HEIGHT = 30;
private static String nameFinal;
private static String originalName;
public static int HEIGHTOFPANEL = 500 + (HEIGHT * 2);
public static void main(String[] args) throws FileNotFoundException{
Scanner console = new Scanner(System.in);
DrawingPanel panel = new DrawingPanel(780,HEIGHTOFPANEL);//DOES PANEL SIZE CHANGE????!?!?!?!??!?!?!?
Graphics g = panel.getGraphics(); //does there always need to be 500 free in the middle???
Scanner nameFile = new Scanner(new File("names.txt"));
Scanner meaningsFile = new Scanner(new File("meanings.txt"));
Scanner nameFile2 = new Scanner(new File("names2.txt"));
intro();
fixedGraph(g);
String nameFinal;
nameFinal = nameToLowerCase(console, originalName);//changes to correct capitalization
String meanings = "";
String popularity = "";
if(STARTINGYEAR == 1890){
popularity = findingStatistics(console,nameFile, nameFinal);
}
else{
popularity = findingStatistics(console, nameFile2, nameFinal);
}
meanings = findingStatistics(console, meaningsFile, nameFinal);
changingGraph(meanings,g,popularity); //EXCEPTION HERE
}
//prints introduction to what the program does
public static void intro(){
System.out.println("This program allows you to search through the");
System.out.println("data from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since" + STARTINGYEAR );
System.out.println();
System.out.print("Name: ");
}
//Converts what the user types in so the first letter is
//capitalized and the rest is lower case
public static String nameToLowerCase(Scanner console, String originalName){
originalName = console.next();
String name = "" ;
int lengthOfName = originalName.length();
String beginingOfName = originalName.substring(0,1).toUpperCase();
String endOfName = originalName.substring(1,lengthOfName).toLowerCase();
name = beginingOfName + endOfName;
return name;
}
public static String findingStatistics(Scanner console, Scanner data, String nameFinal){
boolean goesThroughOnce = false; //
String statistics = "";
String currWord = "";
String currLine = "";
while (data.hasNext() && goesThroughOnce == false){
currLine = data.nextLine();
Scanner lineBeingRead = new Scanner(currLine); //make other scanners?? for each file
currWord = lineBeingRead.next(); //
if (currWord.equals(nameFinal) || currWord.equals(nameFinal.toUpperCase())){ //
statistics = currLine;
goesThroughOnce = true;
System.out.println(statistics);
}
else{
}
}
if(goesThroughOnce == false){
System.out.print(originalName + " not found"); //ASK ABOUT THE EXCEPTION
}
return statistics;
}
public static void fixedGraph(Graphics g){ //Draws fixed things such as gray blocks and black lines
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0,780,HEIGHT);
g.fillRect(0,HEIGHTOFPANEL-HEIGHT,780,HEIGHT);
g.setColor(Color.BLACK);
g.drawLine(0,HEIGHT,780,HEIGHT);
g.drawLine(0,HEIGHTOFPANEL-HEIGHT,780,HEIGHTOFPANEL-HEIGHT);
}
public static void changingGraph(String meanings, Graphics g, String popularity){
g.drawString("" + meanings,0,16); //draws meaning text
int startingYear = STARTINGYEAR;
int amountOfDecades = 0;
if(startingYear == 1890){
amountOfDecades = 13;
}
else{
amountOfDecades = 8;
}
// g.drawString("" + startingYear,0,552); //fencepost
for(int i=0; i<=amountOfDecades;i++){
int year = startingYear + (10 * i);
g.drawString("" + year,(WIDTH*i),HEIGHTOFPANEL-8); //draws decade numbers
}
Scanner popularityData = new Scanner(popularity);
Scanner meaningsData = new Scanner(meanings);
String currChar = popularityData.next();
boolean gender = false; //if it is a boys name
boolean stop = false;
while(meaningsData.hasNext() && stop == false){//determines which color the bars will be
if(currChar.equals("f")){
gender = true;
}
if(gender == true){
g.setColor(Color.PINK);
stop = true;
}
else{
currChar = meaningsData.next();
}
}
if(stop ==false){
g.setColor(Color.BLUE);
}
int ranking;
while(popularityData.hasNext() && stop == false){ //EXCEPTION HERE
ranking = popularityData.nextInt();
for(int i=0; i<=amountOfDecades;i++){
g.fillRect(WIDTH*i,(ranking/2)+30,WIDTH/2,(560-HEIGHT*2)-((ranking/2)+30) );
g.drawString("" + ranking, WIDTH*i, (ranking/2)+30);
}
}
}
}

Credit Card validator for java

I need to do a Credit card number validation.
When I googled this I found the org.apache.commons.validator.CreditCardValidator. But seems like it is not working correctly.
When I pass a non-digit character also it porvides true.
Code for Apache CreditCardValidator:
String ccNumber = "378282246310005";
CreditCardValidator creditCardValidator = new CreditCardValidator();
if(!creditCardValidator.isValid(ccNumber)) throw new Exception("Credit Card Number is not a valid one!");
Then, I wrote following methods to validate credit card numbers based on the card type and the card number (using the luhn's algorithm).
CardType validator (null if an invalid card type)
public String getCCType(String ccNumber){
String visaRegex = "^4[0-9]{12}(?:[0-9]{3})?$";
String masterRegex = "^5[1-5][0-9]{14}$";
String amexRegex = "^3[47][0-9]{13}$";
String dinersClubrRegex = "^3(?:0[0-5]|[68][0-9])[0-9]{11}$";
String discoverRegex = "^6(?:011|5[0-9]{2})[0-9]{12}$";
String jcbRegex = "^(?:2131|1800|35\\d{3})\\d{11}$";
String commonRegex = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$";
try {
ccNumber = ccNumber.replaceAll("\\D", "");
return (ccNumber.matches(visaRegex) ? "VISA" : ccNumber.matches(masterRegex) ? "MASTER" :ccNumber.matches(amexRegex) ? "AMEX" :ccNumber.matches(dinersClubrRegex) ? "DINER" :ccNumber.matches(discoverRegex) ? "DISCOVER" :ccNumber.matches(jcbRegex) ? "JCB":null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
CardNumber validator using Luhn's algorithem.
public boolean isValidCardNumber(String ccNumber){
try {
ccNumber = ccNumber.replaceAll("\\D", "");
char[] ccNumberArry = ccNumber.toCharArray();
int checkSum = 0;
for(int i = ccNumberArry.length - 1; i >= 0; i--){
char ccDigit = ccNumberArry[i];
if((ccNumberArry.length - i) % 2 == 0){
int doubleddDigit = Character.getNumericValue(ccDigit) * 2;
checkSum += (doubleddDigit % 9 == 0 && doubleddDigit != 0) ? 9 : doubleddDigit % 9;
}else{
checkSum += Character.getNumericValue(ccDigit);
}
}
return (checkSum != 0 && checkSum % 10 == 0);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
I want to know,
Is there any other thrid party class to validate the credit cards
other than the org.apache one?
Is there any issue with the my code?
(I tested it for several times. So far so good. I just want to know
if you could spot something that I didn't.)
References :
How do you detect Credit card type based on number?
I did this a long time ago, Sorry Code is in C. Easily Convertible. Hope this will help you.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int CardNoChecker(unsigned long long int Number)
{
int dijts=0;
int Ans=0;
{
unsigned long long int k=1;
while(Number%k!=Number)
{
dijts=dijts+1;
k=k*10;
}
}
{
int i=1;
int Product=0;
int Sum=0;
for(i=dijts;i>=1;i--)
{
if(i%2==0)
{
if((Number%10)*2<10)
Product = Product + ( Number % 10 ) * 2 ;
else
{
int No=(Number%10)*2;
Product = Product + No/10;
Product = Product + No%10;
}
}
else
{
Sum = Sum + ( Number % 10 ) ;
}
Number=Number /10;
}
Ans = Sum + Product ;
}
if(Ans%10==0)
return (1);
else
return (0);
}
int main()
{
unsigned long long int CardNO;
int valid=0;
while(!valid)
{
int CnV=0;
int VC=0;
int AE=0;
int MC=0;
printf("Enter Card NO : ");
scanf("%llu",&CardNO);
if(CardNO/1000000000000==4 || CardNO/1000000000000000==4)
{
VC=1;
}
else if(CardNO/10000000000000==34 ||CardNO/10000000000000==37)
{
AE=1;
}
else if(CardNO/100000000000000==51 || CardNO/100000000000000==52 || CardNO/100000000000000==53 || CardNO/100000000000000==54 || CardNO/100000000000000==55)
{
MC=1;
}
CnV=CardNoChecker(CardNO);
if(CnV && MC )
printf("This is a Valid Master Card\n\n");
else if(CnV && VC )
printf("This is a Valid Visa Card\n\n");
else if(CnV && AE )
printf("This is a Valid American Express Card\n\n");
else
printf("Card is Not Valid'\n\n");
}
return (0);
}
Have a look to Luhn algorithm
https://en.wikipedia.org/wiki/Luhn_algorithm
public static void main(String[] args) {
boolean isValid = checkCC("4561 2612 1234 5467");
System.out.println(isValid);
}
private static boolean checkCC(String input) {
String purportedCC = input.replaceAll(" ", "");
int sum = 0;
for (int i = 0; i < purportedCC.length(); i++) {
int cardNum = Integer.parseInt(
Character.toString(purportedCC.charAt(i)));
if ((purportedCC.length() - i) % 2 == 0) {
cardNum = cardNum * 2;
if (cardNum > 9) {
cardNum = cardNum - 9;
}
}
sum += cardNum;
}
return sum % 10 == 0;
}
You can find custom implantation of credit card validator here which is doing both credit card number validation plus credit card type detection,
http://www.esupu.com/credit-card-validator-java/

JTable table.getSelectedRows() issue

I create a JTable with a customized model and characteristics. I have a long written class that carries out the set up and rendering properly. I see that the .getSelectedRows() method is not working and never evaluates to a value. I was trying to get the index of the first row selected and the last. Here is my code.
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
rows = table.getSelectedRows();
firstRow = rows[0];
int rowCount = rows.length;
lastRow = rows[(rowCount - 1)];
if (command.equals("Run Threw")) {
}else if (command.equals("Shield Bash")) {
this.attack(firstRow, lastRow, command);
}
public boolean block (int defendersRow) {
}
public boolean fumble (int attackersRow) {
}
public boolean dodge (int defendersRow) {
}
public boolean critical (int attackersRow, int attackRoll) {
}
public void attack(int firstRow, int lastRow, String command) {
command = this.command;
firstRow = this.firstRow;
lastRow = this.lastRow;
if (command == "Bludgeon" || command == "React" || command == "ShieldBash") {
attackersRow = this.lastRow;
defendersRow = this.firstRow;
}else if(command == "Attack" || command == "Skill") {
attackersRow = this.firstRow;
defendersRow = this.lastRow;
}else {
}
table.setValueAt(true, attackersRow, 16);
fumbled = this.fumble(attackersRow);
if (fumbled == true) {
outputString = "fumbled";
}
Object maxDamageObject = table.getValueAt(attackersRow, 10);
int maxDamage = (Integer) maxDamageObject;
attackRoll = generator.nextInt(100) + 1;
this.critical(attackersRow, attackRoll);
if (criticaled == true) {
outputString = "criticaled";
}
dodged = this.dodge(defendersRow);
if (dodged == true) {
outputString = "dodged";
}
blocked = this.block(defendersRow);
if (blocked == true) {
outputString = "blocked";
}
int defenseRoll = generator.nextInt(100) + 1;
Object attackBaseObject = table.getValueAt(attackersRow, 6);
Object defenseBaseObject = table.getValueAt(defendersRow, 11);
int attackBase = (Integer) attackBaseObject;
int defenseBase = (Integer) defenseBaseObject;
int attack = attackRoll + attackBase;
int defense = defenseRoll + defenseBase;
Object minDamageObject = table.getValueAt(attackersRow, 9);
int minDamage = (Integer) minDamageObject;
damage = generator.nextInt((maxDamage - minDamage))+minDamage;
if (criticaled == true) {
damage = maxDamage * 2;
}else if (attack >= (defense + 50)) {
damage = damage * 2;
}else if (attack >= defense) {
damage = damage;
}else {
damage = 0;
}
this.outputSelection(outputString, attackersRow, defendersRow, command, damage);
this.damage(defendersRow, damage);
}
private void damage(int defendersRow, int damage) {
}
private void outputSelection(String outputString, int attackersRow, int defendersRow, String command, int damage) {
}
I doesn't see problem with code. May be you can cross check following points:
Are you able to select single / multiple row(s)? Or check what jTableObject.getRowSelectionAllowed() returns
Does your code gets called only after selecting rows. Your code should be executed after some rows are selected so that it can return you expected values.
Listener which calls above mentioned code, is it added to table.
Small points but better to cross check :).
As shown in this working example, you can add a ListSelectionListener to your table's ListSelectionModel and see if anything comes through. It may help pin down where things have gone awry: for example, a local table reference that shadows the intended one.

Categories

Resources