I am making a calculator in Net-beans JFrame and using a Stack to help calculated the variables that are inputted. I seem to have run in to this error StringIndexOutOfBounds: 0 and i can't seem to figure out how to solve it when it happens. Whenever I press the equal button that initiates the Stack the error pops up. I think its something wrong with my Stack but again I can't figure it out. And I really need some fresh eyes on this.
I used/imported swings and .awts but I don't think they are giving me the error here are my swings.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.Math.round;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.swing.JFileChooser;
Here is my Stack:
public class StackCalc
{
private LinkedList stackList = new LinkedList();
private int top, maxTop;
public Object removedEle;
public Object topEle;
public StackCalc(int mt)
{
maxTop=mt;
top=-1;
}
public boolean isFull()
{
return top == maxTop-1;
}
public boolean push (Object O)
{
if(!isFull())
{
stackList.addFirst(O);
top++;
return true;
}
else
{
return false;
}
}
public boolean pop()
{
if(!stackList.isEmpty())
{
removedEle= stackList.removeFirst();
top--;
return true;
}
else
{
return false;
}
}
public void getTop()
{
topEle=stackList.getFirst();
}
public boolean isEmpty()
{
return stackList.isEmpty();
}
}
Here is the code that I think is giving me this error
static void processExpR(String exp)
{
boolean advance = true;
String token = " ";
int loc = exp.indexOf(token);
while (loc != -1)
{
if (token.isEmpty()){
return;
}
else if (advance){
token = exp.substring(0,loc);
exp = exp.substring(loc+1);
}
char ch = token.charAt(0);//there is a specific problem with this line
if(Character.isDigit(ch)){
advance = true;
s1R.push(token);
}
else
{
if(s2R.isEmpty())
{
advance = true;
s2R.push(token);
}
else
{
advance = false;
calcR();
}
}
if(advance){
loc = exp.indexOf(" ");
}
}//end of while
if (Character.isDigit(exp.charAt(0)))
{
s1R.push(exp);
}
else
{
s2R.push(exp);
}
while (!s2R.isEmpty())
{
calcR();
}
}
Any help would be much appreciated. I'm like really lost here. Thank you.
The problem comes here:
token = exp.substring(0,loc);
The above line takes a substring from exp. A bit later you do:
char ch = token.charAt(0);//there is a specific problem with this line
And what happens is: the string that you cut from exp and store into token ... is empty. And therefore, when you try to access index 0 of that string you are told: that string doesn't even have an index 0 (and that can only happen if token is empty!).
Thus the answer here is two-fold:
Before doing calls like charAt(someIndex) you better check upfront if your string actually has that index
But in your case, checking alone wouldn't help.
You see, your problem is basically that your logic how you compute your "substring" index is probably wrong.
My suggestion: sit down, and process your input data manually. Meaning: use example input, and manually execute your program. To understand how your counters/index variables look like, to understand what your code is really doing with its input. If you find that too cumbersome, than at least learn using a debugger to do that (but doing it one, two times manually will still tell you more than 50 or 100 answers here on SO!)
Related
My bot is stuck printing the output. I check and there was no problem with the logical part as I used the sane logic to make a normal java program. Please help as it is stuck printing the output in discord and I do not know how to solve it.
I also added some unnecessary print functions to find out where the error was. To my surprise, it was just in printing the message which is unusual as I have made bots before and none of them had any errors to just "print" messages.
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
public class rpsidnfp {
public static JDA jda;
public static void main(String args[]) throws LoginException {
jda = JDABuilder.createDefault("(my token here)").build();
core2 core2obj = new core2();
jda.addEventListener(core2obj);
}
}
The former was my main class.
And below is the core class as it contains all the functions.
package pack.rpsidnfp;
import java.util.Random;
//import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class core2 extends ListenerAdapter {
public static String prefix = "!";
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String input = event.getMessage().getContentRaw();
String[] options = {"rock", "paper", "scissors"};
Random robj = new Random();
int rnum = robj.nextInt(options.length);
System.out.println(rnum);
String conf = options[rnum];
event.getChannel().sendMessage(conf);
System.out.println(conf);
String same = prefix + conf;
String win = "congrats, you won!";
String lose = "lmao, you lost";
if(input.equals(same)) {
event.getChannel().sendMessage("we both kept the same thing");
}
else if(input.equals(prefix + options[0])) {
if(conf.equals(options[1])) {
event.getChannel().sendMessage(lose);
}
else if(conf.equals(prefix + options[2])) {
event.getChannel().sendMessage(win);
}
}
else if(input.equals(prefix + options[1])) {
if(conf.equals(options[0])) {
event.getChannel().sendMessage(win);
}
else if(conf.equals(options[2])) {
event.getChannel().sendMessage(lose);
}
}
else if(input.equals(prefix + options[2])) {
if(conf.equals(options[0])) {
event.getChannel().sendMessage(lose);
}
else if(conf.equals(options[2])) {
event.getChannel().sendMessage(win);
}
}
}
}
The sendMessage method returns a MessageAction. You need to call queue() on that RestAction instance.
Additionally, keep in mind that your bot receives its own messages so you should make sure it ignores those. You can add a if (event.getAuthor().isBot()) return; to the start of your listener method.
See Also:
Troubleshooting Guide: Nothing happens when using X
RestAction Guide
MessageListenerExample
JDA README
I am using Priority Queue in one of my java code (Pair Class). I encountered one minor issue that uses remove function (PQ) which is not giving results. After a while ,I detect my mistake but I don't know the reason behind this issue . Can anyone explain me the logical reason behind this issue(Why last line of my code giving me false)??
I am new to this platform ,Before posting this Question I searched a lot over internet, but not getting suitable reason which would justify the above problem.
import java.util.Comparator;
import java.util.PriorityQueue;
public class PQ_IMP {
static class Pair{
int a ;
int b;
int c;
Pair(int x,int y,int z){
a=x;b=y;c=z;
}
}
public static void main(String[] args) {
PriorityQueue<Pair> name =new PriorityQueue<Pair>(new Comparator<Pair>() {
#Override
public int compare(Pair o1, Pair o2) {
return Integer.compare(o1.a,o2.a);
}
});
Pair n=new Pair(1,2,3);
name.add(n);
System.out.println(name.remove(n)); // Print true
name.add(n);
n=new Pair(1,2,3);
System.out.println(name.remove(n)); // Print False
}
}
This question already has an answer here:
is it is possible to disable the windows keys using java
(1 answer)
Closed 6 years ago.
I am trying to make a small application, similar to a cyber cafe software.
To be specific, what i want to do is that once the app starts, you can't do anything in the computer, and it's impossible to cease the locking, (Alt + F4, Ctrl + Alt + Del, Task Manager, etc.) unless you put up a certain username and password, and once a specific amount of time has passed by, the software will lock the computer again.
I am pretty much a novice in Java, so i couldn't find any answers that i could understand or that were what i was looking for. Is this possible to do?
Thanks in advance!
You'd probably need to use JNA to do things like that, or just change to C++/C#.
Such example as this:
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser.HHOOK;
import com.sun.jna.platform.win32.WinUser.KBDLLHOOKSTRUCT;
import com.sun.jna.platform.win32.WinUser.LowLevelKeyboardProc;
import com.sun.jna.platform.win32.WinUser.MSG;
public class KeyHook {
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
private static User32 lib;
public static void blockWindowsKey() {
if (isWindows()) {
new Thread(new Runnable() {
#Override
public void run() {
lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
if (nCode >= 0) {
switch (info.vkCode){
case 0x5B: //Around here would be where you add all your 0x key codes
case 0x5C:
return new LRESULT(1);
default: //do nothing
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
};
hhk = lib.SetWindowsHookEx(13, keyboardHook, hMod, 0);
// This bit never returns from GetMessage
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
break;
} else {
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
lib.UnhookWindowsHookEx(hhk);
}
}).start();
}
}
public static void unblockWindowsKey() {
if (isWindows() && lib != null) {
lib.UnhookWindowsHookEx(hhk);
}
}
public static boolean isWindows(){
String os = System.getProperty("os.name").toLowerCase();
return (os.indexOf( "win" ) >= 0);
}
}
(That was not mine, ill explain in a bit)
Then see if it is running Windows by 'KeyHook.isWindows()'.
If it is, use things like 'blockWindowsKey()' or make your own functions like it. I put a comment where you'd change the key code.
FYI possible duplicate of is it is possible to disable the windows keys using java
Thats where the code came from.
so I'm trying to code a Chess Program in Java but I'm having some trouble with my getColor() method. I'm relying on some of the code from Gridworld. I've created a class for each piece. I want the piece to work like a critter from Gridworld in the sense that I have a method that creates an ArrayList of possible locations to choose from when moving. This is where I've hit a problem. I've tried to create a getColor() method, but for some reason it is not working. I asked my teacher for help but he was as puzzled as I was. I tried debugging it but I don't see anything wrong with it. The exact error I get is this:
"Cannot find symbol - method getColor()"
Here's all my code, I'm using BlueJ for the record:
import java.util.ArrayList;
import java.awt.Color;
public interface Piece
{
public enum PieceType {pawn, rook, knight, bishop, queen, king}
}
Next is the ChessPiece Abstract Class. I haven't worked on the selectMoveLocation method yet though:
import java.util.ArrayList;
import java.awt.Color;
import info.gridworld.grid.Location;
import info.gridworld.grid.BoundedGrid;
public abstract class ChessPiece implements Piece
{
Color colorOfPiece;
PieceType typeOfPiece;
public BoundedGrid<Object> board;
public Location location;
public ArrayList moveLocations;
public ChessPiece( Color whiteOrBlack, PieceType selectedType)
{
if (whiteOrBlack == Color.BLACK || whiteOrBlack == Color.WHITE)
{
if ((selectedType == PieceType.pawn || selectedType == PieceType.rook || selectedType == PieceType.knight || selectedType == PieceType.bishop ||selectedType == PieceType.queen || selectedType == PieceType.king))
{
colorOfPiece = whiteOrBlack;
typeOfPiece = selectedType;
location = null;
}
}
}
public Color getColor()
{
return colorOfPiece;
}
public void makeMove(Location newLocation)
{
if (board == null)
throw new IllegalStateException("This actor is not in a board.");
if (board.get(location) != this)
throw new IllegalStateException(
"The board contains a different actor at location "
+ location + ".");
if (!board.isValid(newLocation))
throw new IllegalArgumentException("Location " + newLocation
+ " is not valid.");
if (newLocation.equals(location))
return;
board.remove(location);
location = newLocation;
board.put(location, this);
}
public Location getLocation()
{
return location;
}
public BoundedGrid<Object> getBoard()
{
return board;
}
public Location selectMoveLocation(ArrayList<Location> moveLocations)
{
Location selection;
selection = null;
//mouse stuff
return selection;
}
}
And finally, the code that gives me the compiler error. This is just the code for my King piece, though it gives me the error for every piece where I try and implement it:
import java.awt.Color;
import java.util.ArrayList;
import info.gridworld.grid.Location;
import info.gridworld.grid.BoundedGrid;
//must fix problem with getColor()
public class King extends ChessPiece
{
ArrayList<Location> moveLocations;
// private Color colorOfPiece;
public King( Color whiteOrBlack )
{
super(whiteOrBlack, PieceType.king);
//colorOfPiece = whiteOrBlack;
}
public void getMoveLocations()
{
moveLocations.clear();
for (int i = 0; i < 360; i += 45)
{
if ((getBoard().isValid(getLocation().getAdjacentLocation(i))) && (((getBoard().get(getLocation().getAdjacentLocation(i))) == null) || (((getBoard().get(getLocation().getAdjacentLocation(i)))).getColor() == colorOfPiece)))
{
moveLocations.add(getLocation().getAdjacentLocation(i));
}
}
}
}
getBoard().get(..) returns a template type E according to the doc I found online, and in your case, E is type Object (since your board data member in ChessPiece is a collection of Objects.) Object has no getColor() method. You'll want to cast (((getBoard().get(getLocation().getAdjacentLocation(i)))) to a class that has a getColor method. (Or maybe change your board to a collection of ChessPieces)
I'm trying to create a text based game in Java that I will ask for a user's name and insert it into the game. I'm trying to evaluate with the string that they entered has any number. i.e 09452 or asdf1234.
Here is the code that is relative to the problem.
String name, choiceSelection;
int choice;
name = JOptionPane.showInputDialog(null, "Enter your name!");
//CHECKS IF USER ENTERED LETTERS ONLY
if (Pattern.matches("[0-9]+", name))
{
throw new NumberFormatException();
}
else if (Pattern.matches("[a-zA-Z]+", name))
{
if (Pattern.matches("[0-9]+", name))
{
throw new NumberFormatException();
}
}
I'm trying to figure out if any number is in the string and if so, throw a NumberFormatException so that they know they didn't follow the correct prompt.
What is the best way to make sure the user doesn't enter numbers in the name String?
You can use a simpler check:
if (!name.replaceAll("[0-9]", "").equals(name)) {
// name contains digits
}
The replaceAll call removes all digits from the name. The equals check would succeed only when there are no digits to remove.
Note that throwing NumberFormatException in this case would be misleading, because the exception has a very different meaning.
Consider using a JFormattedTextField or input verifier to prevent the user from entering numbers in the first place. It may not be worth losing the JOptionPane simplicity for a throwaway project, but it simplifies things for the end user.
Or, You simply don't let the User to put any numeric value in textField .For that you are needed to create Customized PlainDocument say NonNumericDocument and setting the Document of JTextField object as that customized NonNumericDocument
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
class NonNumericDocument extends PlainDocument
{
#Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{
if (str == null)
{
return;
}
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++)
{
if (Character.isDigit(arr[i]) || !Character.isLetter(arr[i]))//Checking for Numeric value or any special characters
{
return;
}
}
super.insertString(offs, new String(str), a);
}
}
//How to use NonNumericDocument
class TextFrame extends JFrame
{
JTextField tf ;
public void prepareAndShowGUI()
{
tf = new JTextField(30);
tf.setDocument(new NonNumericDocument());//Set Document here.
getContentPane().add(tf,BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater ( new Runnable()
{
#Override
public void run()
{
TextFrame tFrame = new TextFrame();
tFrame.prepareAndShowGUI();
}
});
}
}
You can use this NonNumericDocument with any JTextField in your code without worrying about handling of non-numeric characters explicitly.
If you want to allow the user to only enter letters you can do this:
if (name.matches("\\p{Alpha}+")) {
// name contains only letters
}
Another way to check it is using parseInt( String s ) method:
private boolean isNumber( String s ) {
try {
Integer.parseInt( s );
} catch ( Exception e ) {
return false; // if it is not a number it throws an exception
}
return true;
}