ArrayOutOfBoundException while inserting elements - java

Getting ArrayIndexOutOfBoundException while inserting elements to a two Dimensional array..I dont know where the problem is..
I tried a lot but couldn't understand why this is giving the exception.Here is my code..Thanks in advance..
public class TruthTableAutoMateClass extends JPanel implements ActionListener
{
static int size;
private int i = 0;
static JButton btnOk = new JButton();
String[][] array= new String[size][];
private double[][] dim = { {0.50, 0.50}, {0.25, 0.20, 0.20, 0.20, TableLayout.FILL}};
public static void main(String args[])
{
TruthTableAutoMateClass auto = new TruthTableAutoMateClass();
checkAdding(auto);
btnOk.addActionListener(auto);
}
private static String[] prepareArray()
{
String[] arr = new String[2];
if (size == 16)
{
String text1 = field1.getText();
String text2 = field2.getText();
String text3 = field3.getText();
String text4 = field4.getText();
String firstArray = new StringBuilder().append(text1).append("|").append(text3).append("|").append(text3).append("|").append(text4).toString();
arr[0] = firstArray;
arr[1] = ledValue1.getText();
}
else if (size == 9)
{
}
else if (size == 4)
{
}
return arr;
}
private static void checkAdding(TruthTableAutoMateClass auto1)
{
TruthTableAutoMateClass auto = auto1;
String answer = JOptionPane.showInputDialog("How many values are there 4 or 3 " + "if 4 yes else press no");
if (answer.equalsIgnoreCase("yes"))
{
size = 4 * 4;
auto.add(lbl1, "0,0");
auto.add(lbl2, "0,1");
auto.add(lbl3, "0,2");
auto.add(lbl4, "0,3");
auto.add(field1, "1,0");
auto.add(field2, "1,1");
auto.add(field3, "1,2");
auto.add(field4, "1,3");
auto.add(ledValue1, "1,4");
/*auto.add(ledValue2);
auto.add(ledValue3);
auto.add(ledValue4);*/
auto.add(btnOk, "0,4");
}
else
{
size = 3 * 3;
String answer2 = JOptionPane.showInputDialog("Again enter yes or no" + "3 for yes , 2 for no");
if (answer2.equalsIgnoreCase("yes"))
{
auto.add(lbl1, "0,0");
auto.add(lbl2, "0,1");
auto.add(lbl3, "0,2");
auto.add(field1, "1,0");
auto.add(field2, "1,1");
auto.add(field3, "1,2");
auto.add(ledValue1, "1,4");
/* auto.add(ledValue2);
auto.add(ledValue3);*/
auto.add(btnOk, "0,4");
}
else
{
size = 2 * 2;
auto.add(lbl1, "0,0");
auto.add(lbl2, "0,1");
auto.add(field1, "1,0");
auto.add(field2, "1,1");
auto.add(ledValue1, "1,4");
/* auto.add(ledValue2);*/
auto.add(btnOk, "0,4");
}
}
}
#Override
public void actionPerformed(ActionEvent e)
{
array[i] = prepareArray();
i++;
System.out.println(Arrays.toString(array));
}}

At the main() method you are creating an instance of TruthTableAutoMateClass. When this one is creating, size = 0 (by default) and String[][] array= new String[size][]; creates an array with size 0.
So, your array had size 0 and you got an exception when you had tried to assign some value like this array[i] = prepareArray();.

Related

How to display if those two arrays have the same number on the same place in both arrays?

So here's my problem :
I have two arrays, I want to count how many values are on the exact same position [i] on both arrays, and how many values are the same on both arrays but for different [i]
I tried the usual loop with for and the size of an array but it displays strange values that are far from what expected
package stackOverflow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class mainStack extends JFrame implements ActionListener {
JButton jbr,jbv,jbb,jbo,jbn,jbj;
JTextField l11b;
String a;
int tabRef[]= {0,1,2,3};
int correctAndSameCase=0;
int correctButDiffCase=0;
mainStack(){
this.setLayout(null);
jbr = new JButton("Rouge");
jbr.setBounds(0,80,85,30);
add(jbr);
jbv = new JButton("Vert");
jbv.setBounds(125, 80, 85, 30);
add(jbv);
jbb = new JButton("Bleu");
jbb.setBounds(0, 120, 85, 30);
add(jbb);
jbj = new JButton("Jaune");
jbj.setBounds(125, 120, 85, 30);
add(jbj);
jbo = new JButton("Orange");
jbo.setBounds(0, 160, 85,30);
add(jbo);
jbn = new JButton("Noir");
jbn.setBounds(125,160, 85,30);
add(jbn);
jbr.addActionListener(this);
jbv.addActionListener(this);
jbb.addActionListener(this);
jbj.addActionListener(this);
jbo.addActionListener(this);
jbn.addActionListener(this);
setLayout(null);
setSize(800,800);
setVisible(true);
}
private int index = 0;
private int p=0;
private int tabAnswer[][] = new int[3][4];
private int i;
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(jbr)) {
tabAnswer[p][index] = 0;
} else if (e.getSource().equals(jbv)) {
tabAnswer[p][index] = 1;
} else if (e.getSource().equals(jbj)) {
tabAnswer[p][index] = 2;
} else if (e.getSource().equals(jbb)) {
tabAnswer[p][index] = 3;
} else if (e.getSource().equals(jbo)) {
tabAnswer[p][index] = 4;
} else if (e.getSource().equals(jbn)) {
tabAnswer[p][index] = 5;
}
index++;
if (index >= tabAnswer[p].length) {
System.out.println(Arrays.toString(tabAnswer[p]));
for(i=0 ; i<tabRef.length;i++) {
if(tabAnswer[p][i]==tabRef[i]) {
correctAndSameCase++;
}else if(tabAnswer[p][i]==tabRef[0] & tabAnswer[p][i]!=tabRef[i] || tabAnswer[p][i]==tabRef[1] & tabAnswer[p][i]!=tabRef[i] || tabAnswer[p][i]==tabRef[2]& tabAnswer[p][i]!=tabRef[i] ||tabAnswer[p][i]==tabRef[3] & tabAnswer[p][i]!=tabRef[i]) {
correctButDiffCase++;
}
}
index = 0;
p++;
System.out.println(correctAndSameCase+" number are on the same case on both arrays");
System.out.println(correctButDiffCase+" number are on different case on both arrays");
if(p>=3) {
p=0;
}
correctAndSameCase=0;
correctButDiffCase=0;
}
}
public static void main(String[] args) {
mainStack t= new mainStack();
}
Here for tabAnswer {5,4,3,2} correctAndSameCase should be 0 and correctButDiffCase should be 2 but in stead it gives me 0 and 1 as answer.
EDIT: I can see that the problem is in the condition to set the value to correctButDiffCasebut i don't know how to fix it
here a short code snippet that counts these two values.
But I didn't know, if you want to count some special cases (see TODOs).
public static void main(String[] args) throws Exception {
List<Integer> tabRef = Arrays.asList(10, 5, 3, 5, 2, 6);
List<Integer> tabRef2 = Arrays.asList(12, 8, 3, 5, 6, 2);
int matchesOnSameIndex = 0;
int matchesButDifferentIndex = 0;
for (int i = 0; i < tabRef.size(); i++) {
//compare on same index, if other list has element on this index
if (tabRef2.size() > i) {
if (tabRef.get(i) == tabRef2.get(i)) {
//same element on same index
matchesOnSameIndex++;
}
}
//check if value exists in other list
if (tabRef2.contains(tabRef.get(i))) {
//if yes, check if it is not at same position
if (tabRef2.size() > i) {
if (tabRef2.get(i) != tabRef.get(i)) {
//not same index
//TODO must count multiple times, if element exists multiple times?
matchesButDifferentIndex++;
}else {
//TODO must count, if also exists on other index?
}
}else {
//same position not existing, so must be on other position
matchesButDifferentIndex++;
}
}
}
System.out.println("matchesOnSameIndex: "+matchesOnSameIndex);
System.out.println("matchesButDifferentIndex: "+matchesButDifferentIndex);
}
your code to count the occurences seem fine (although a bit messy).
I wrote a junit test using your code and there is no issue:
#Test
public void testArrayCheck() {
int[] tabRef = {0,1,2,3};
int tabAnswer[][] = new int[3][4];
int[] tabAnswerPos0 = {0,0,0,0};
tabAnswer[0] = tabAnswerPos0;
int p = 0;
int correctAndSameCase = 0;
int correctButDiffCase = 0;
Set<Integer> setArrayValues = new HashSet<Integer>();
for(int i=0 ; i<tabRef.length;i++) {
if(tabAnswer[p][i]==tabRef[i]) {
correctAndSameCase++;
}else if(tabAnswer[p][i]==tabRef[0] && tabAnswer[p][i]!=tabRef[i]
|| tabAnswer[p][i]==tabRef[1] && tabAnswer[p][i]!=tabRef[i]
|| tabAnswer[p][i]==tabRef[2] && tabAnswer[p][i]!=tabRef[i]
||tabAnswer[p][i]==tabRef[3] && tabAnswer[p][i]!=tabRef[i]) {
if (!setArrayValues.contains(tabAnswer[p][i])) {
correctButDiffCase++;
setArrayValues.add(tabAnswer[p][i]);
}
}
}
System.out.println(correctAndSameCase+" number are on the same case on both arrays");
System.out.println(correctButDiffCase+" number are on different case on both arrays");
}
1 number are on the same case on both arrays
1 number are on different case on both arrays
Are you sure that tabAnswers has the values {5,4,3,2}?

Error in Java Method Cant get it to print to the console

I'm not sure where I went wrong but I could use some help. I'm new to JAVA and I'm not sure where I'm going wrong. Just trying to get the items in the public void method to print to my console.
public class HomersDonutShop {
public static void main (String[] args) {
//Creates flavor array
String[] donutFlavors = new String[4];
donutFlavors[0]= "Chocolate";
donutFlavors[1]= "Vanilla";
donutFlavors[2]= "Chocolate With Sprinkles";
donutFlavors[3]= "Blueberry";
//default is chocolate. prints string with array selected
System.out.println("You picked " +donutFlavors[0]+"."+" Great choice!!");
//creates donut rating
final int donutRating[] = new int[5];
donutRating[0] = 1;
donutRating[1] = 2;
donutRating[2] = 3;
donutRating[3] = 4;
donutRating[4] = 5;
//default is 5 prints string with array selected
System.out.println("You gave " +donutFlavors[0]+" donuts"+" a rating of"+ " "+donutRating[4]);
}
public void makeDonuts(){
donutCount = donuCount + 1;
System.out.println("Time to mke more donuts."+" MMMMMMMM DOOOONNNUUUUTSSS.");
}
public void buyMoreIngredients() {
int ingredients = 10;
while (ingredients >= 10)
System.out.println(ingredients);
ingredients--;
if (ingredients <=1) {
System.out.println("Time to go shopping");
}
}
}

Java Array Sorting based on multiple parameters

I have an array that I want to sort in ascending order. However, I want to sort them with reference to a boolean array.I would like to sort the values that are true in ascending order, followed by the values that are false in ascending order.
Little stuck on how to get there.
This is what I have currently:
Object[] arr = new Object[6];
arr[0] = new Object(2);
arr[1] = new Object(5);
arr[2] = new Object(3);
arr[3] = new Object(1);
arr[4] = new Object(6);
arr[5] = new Object(4);
Available[] avalarr = new Available[6];
availarr[0] = new Available (true);
availarr[1] = new Available (false);
availarr[2] = new Available (false);
availarr[3] = new Available (true);
availarr[4] = new Available (true);
availarr[5] = new Available (false);
I need the output to be:
1 2 6 3 4 5
Code:
import java.util.Arrays;
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
Arrays.sort(items);
System.out.println("\n\nAfter Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
}
class Item implements Comparable<Item> {
private int _intValue;
private boolean _boolValue;
public Item(int intValue, boolean boolValue) {
_intValue = intValue;
_boolValue = boolValue;
}
public int getIntValue() { return _intValue; }
public boolean getBoolValue() { return _boolValue; }
#Override
public int compareTo(Item otherItem) {
// Using explicit comparison
int boolComparison = (_boolValue == otherItem._boolValue) ? 0 :
(_boolValue) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (_intValue == otherItem.getIntValue()) ? 0 :
(_intValue > otherItem.getIntValue()) ? 1 : -1);
}
}
Output:
Before Sorting:
2 5 3 1 6 4
After Sorting:
1 2 6 3 4 5
Explanation:
The idea is to let your "Item" implement Comparable, and override the compareTo(Item otherItem) function based on the desired order.
Once that is done, all you need to do is to call Arrays.sort() on your array of Item.
Version 2 (w/o Comparable/Comparator):
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
bubbleSort(items);
System.out.println("\n\nAfter Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
public static void bubbleSort(Item [] items) {
int n = items.length;
do {
int newN = 0;
for(int i = 1; i < n; i++) {
if(compareTo(items[i-1], items[i]) == 1) {
Item temp = items[i-1];
items[i-1] = items[i];
items[i] = temp;
newN = i;
}
}
n = newN;
} while (n != 0);
}
public static int compareTo(Item item1, Item item2) {
int boolComparison = (item1.getBoolValue() == item2.getBoolValue())
? 0 : (item1.getBoolValue()) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (item1.getIntValue() == item2.getIntValue()) ? 0 :
(item1.getIntValue() > item2.getIntValue()) ? 1 : -1);
}
}
(To expand on my comment:
You need a basic "thing":
class Thing {
boolean newAvailable;
int order;
public Thing(boolean newAvailable, int order) {
...
}
}
...and a Comparable...
class CompareThings implements Comparator<Thing> {
...
int compare(Thing t1, Thing t2) {
if (t1.newAvailable!=t2.newAvailable)
return t1.newAvailable==true ? 1 : -1;
return t1.order-t2.order;
}
}
(Note that t1.newAvailable==true is redundant, but I think it clarifies what's going on here.)
Now build an array of Thing and call Arrays.sort(Thing[] things, CompareThings);

JOptionPane.showMessageDialog keeps reappearing

My code is supposed to ensure that users only enter a binary string. Everything goes right and in order if I enter a correct binary number (1, 0). But when I enter a wrong number (alphabet or number other than 0 and 1) JOptionPane.ShowMessageDialog appears showing the error message, and when I click "OK" or "Cross" Button it reappears again. So to close the app I have to use the process manager to kill "java.exe".
Here is the complete code for my app:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Bn extends JFrame {
private JLabel l1;
private JLabel l2;
private JLabel l3;
private JTextField tf;
private JButton oc;
private JButton hd;
private JButton dc;
public Bn() {
setTitle("Binary Conversion");
setSize(350 , 190);
setResizable(false);
setLocation(720 , 200);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.CENTER, 25, 10));
l1 = new JLabel(">>>>>>>>BINARY CONVERSION<<<<<<<<");
l2 = new JLabel("Enter The Number:");
l3 = new JLabel(" Convert to: ");
tf = new JTextField(25);
oc = new JButton("Octal");
hd = new JButton("Hexa Decimal");
dc = new JButton("Decimal");
add(l1); // Binary conversion
add(l2); // Enter The Number
add(tf); // Text Field
add(l3); // Conver to
add(oc); // Octal
add(hd); // Hexa Decimal
add(dc); // Decimal
oc.addActionListener(new cvr());
hd.addActionListener(new cvr());
dc.addActionListener(new cvr());
setVisible(true);
}
void res()
{
int b = 0;
String num = tf.getText();
int i , l;
l = num.length();
char ch;
do
{
for (i=0 ; i<l ; i++)
{
b = 0;
ch = num.charAt(i);
if (Character.isDigit(ch) && (ch == 48 || ch == 49))
b=1;
else
{
JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)");
}
}
}
while(b != 1);
}
void occ()
{
res();
String num = tf.getText();
long dec = Long.parseLong(num,2);
String oct = Long.toOctalString(dec);
JOptionPane.showMessageDialog(null, "Octal equivalent is: "+ oct);
}
void hdc()
{
res();
String num = tf.getText();
long dec = Integer.parseInt(num,2);
String hex = Long.toHexString(dec);
JOptionPane.showMessageDialog(null, "Hexa Decimal equivalent is: "+ hex);
}
void dcc()
{
res();
String num = tf.getText();
long decimal = 0, temp, i = 0;
temp = Long.parseLong(num);
while (temp != 0) {
long r = temp % 10;
long value = r * (int)Math.pow(2, i);
i++;
decimal = decimal + value;
temp /= 10;
}
JOptionPane.showMessageDialog(null, "Decimal equivalent is: "+ decimal);
}
private class cvr implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == oc)
{
occ();
}
if (e.getSource() == hd)
{
hdc();
}
if (e.getSource() == dc)
{
dcc();
}
}
}
public static void main(String args[])
{
Bn obj = new Bn();
}
}
The code for JOptionPane is located in void res() method. How can I close this Dialog pane so I may reenter the value for input?
Remove the do { } while loop
do
{
for (i=0 ; i < l ; i++)
{
b = 0;
ch = num.charAt(i);
if (Character.isDigit(ch) && (ch == 48 || ch == 49))
b=1;
else
{
JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)");
}
}
}
while(b != 1);

*new title: JButton array scope (it was:change color of button with button name)

How can is alter the color of the correct button?
It is for a small application, this app has 5 buttons from a array.(the name's are a,b,c,d,e)
The appearence of the buttons have to alter (change color) when i type in a number in a Jtextfield.
I added a name to each button:
knop = new JButton(Titel[i]);
knop.setName(tel[i]);
Here i get the text:
public void actionPerformed(ActionEvent e) {
String invoer = antwoord.getText();
try
{
int welke = Integer.parseInt(invoer);
if (welke-1 >0 && welke-1<5)
{
vraag.setText("Goeie keus!");
if (welke == 1){
knop.setBackground(Color.BLUE);
}
knop.setBackground(Color.red);
}
But now it only changes the last button to red which is created bij the array.
So the question can I select a button by its name?
So if (input = 1) alter button 1 to green. in stead of only button 5.
I have tried de solution of gile, but i can't get it to work:
I get every time a: "AWT-EventQueue-0" java.lang.NullPointerException"
package kiesknop;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
//public class Paneel extends JApplet
public class Paneel extends JFrame
{
private JPanel paneel;
private JButton knop;
public JTextField antwoord;
private JLabel vraag;
public JButton[] knops;
public Paneel() {
int [][] numButtons = new int [5][4];
numButtons[0][0] = 50;
numButtons[0][1] = 10;
numButtons[0][2] = 10;
numButtons[0][3] = 10;
numButtons[1][0] = 100;
numButtons[1][1] = 10;
numButtons[1][2] = 30;
numButtons[1][3] = 30;
numButtons[2][0] = 200;
numButtons[2][1] = 10;
numButtons[2][2] = 50;
numButtons[2][3] = 50;
numButtons[3][0] = 300;
numButtons[3][1] = 10;
numButtons[3][2] = 100;
numButtons[3][3] = 100;
numButtons[4][0] = 500;
numButtons[4][1] = 10;
numButtons[4][2] = 200;
numButtons[4][3] = 200;
String [] Titel = new String [5];
Titel [0] = "*";
Titel [1] = "**";
Titel [2] = "***";
Titel [3] = "****";
Titel [4] = "*****";
String [] tel = new String [5];
tel [0] = "a";
tel [1] = "b";
tel [2] = "c";
tel [3] = "d";
tel [4] = "e";
paneel = new JPanel();
JButton[] knops = new JButton[5];
for (int i = 0; i < 5; i++)
{
knops[i] = new JButton(Titel[i]);
knops[i].setName (tel[i]);
knops[i].setBounds(numButtons[i][0],numButtons[i][1], numButtons[i][2], numButtons[i][3]);
knops[i].addActionListener(new KnopHandler());
}
for (int i = 0; i < 5; i++)
{
paneel.add(knops[i]);
}
vraag = new JLabel("Welke knop grootte vind je het mooist?");
vraag.setBounds(100, 400, 250, 20);
antwoord = new JTextField(20);
antwoord.setBounds(500, 400, 100, 20);
antwoord.setEditable(true);
antwoord.addActionListener(new AntwoordHandler());
paneel.add (vraag);
paneel.add (antwoord);
setContentPane (paneel);
}
public class KnopHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton o = (JButton)e.getSource();
String Text = o.getText();
String name = o.getName();
String Label =o.getLabel();
System.out.println("knop gedrukt");
System.out.println(Text);
System.out.println(name);
System.out.println(Label);
}
}
class AntwoordHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String invoer = antwoord.getText();
try
{
int welke = Integer.parseInt(invoer);
if (welke >0 && welke<5)
{
vraag.setText("Goeie keus!");
if(welke == 1)// knops[welke].setBackground(Color.BLUE);
System.out.println(knops[1]);
if(welke == 2) knops[welke].setBackground(Color.BLUE);
if(welke == 3) knops[welke].setBackground(Color.BLUE);
if(welke == 4) knops[welke].setBackground(Color.BLUE);
if(welke == 5) knops[welke].setBackground(Color.BLUE);
}
else vraag.setText("Geen geldige invoer!");
}
catch( NumberFormatException nfe)
{
if( invoer.equals("")) vraag.setText("Niets ingevuld!");
else
vraag.setText("Alleen nummers invoeren!");
}
}
}
public static void main (String arg[])
{
JFrame frame = new Paneel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);
frame.setSize(900, 500);
}
}
What am i doing wrong ?
You can put buttons in an array
JButton[] knops = new JButton[5];
...
knops[i] = new JButton(Titel[i]);
...
And then set the background after user entered a number:
if (welke == 1){
knops[welke].setBackground(Color.GREEN);
}
Your title doesn't match with the given example: you are asking to get a button reference with string name but you are trying to parse the name to an integer.
However, if i understood your requirement correctly: I can think of two option:
Traverse each button of the button's array you have and compare with their name with your target name: you can get the name of the component(JButton) invoking button.getName().
Instead of using array which require traverse each time to get the target button with matching name, Create a HashMap<key, value>: HashMap<String, JButton>, map the button to their name and use it to get the component on Action Event.
HashMap<String, JButton>buttomMap = new HashMap<>();
buttonMap.put("kicker", kickerButton); // kickButton is a button
//// Then in actionPerformed() function
JButton button = buttonMap.get("kicker");
button.setBackground(Color.BLUE);

Categories