package javaisnotbannana;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class Javaisnotbannana{
public static void main(String[] args) {
window();
}
////////////////////////////////////////////////////
public static void window()
{
JFrame window= new JFrame();
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField(30);
JButton jb = new JButton("Enter");
window.setTitle("ThisisTitleofWindow");
window.setVisible(true);
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//textfield
jp.add(jt);
jt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String inoutt = jt.getText();
jl.setText(inoutt);
}
});
Why dose this lower section have the problem "Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range:(how ever many characters i entered)".str is receiving what is typed in the Jtextfield and im trying to filter the input to give a different output. With out a filter it works fine like above just press enter,but when i try to press the button i and filter i get an error.
//button
jp.add(jb);
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String str = jt.getText();
String text="";
int A=0;
int B=1;
int C=2;
for(int num=0;num<=str.length()/3;num++)
{
if (str.charAt(A) == 'T'&&str.charAt(B) == 'A'&&str.charAt(C)=='S')
{
text+="smell tasty";
}
else if(str.charAt(A) == 'B'&&str.charAt(B) == 'A'&&str.charAt(C)=='N')
{
text+="bannanas";
}
A+=3;
B+=3;
C+=3;
}
jl.setText(text);
}
});
jp.add(jl);
window.add(jp);
}
}
your index is overshooting use this instead
for(int num=0;num<str.length()/3;num++)
just < not <=