Having trouble creating an object - java

When i try to create a specific object for the bot class I get the following error, and i do not understand what the problem is:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at Bot.<init>(Bot.java:10)
at PlayGame.<clinit>(PlayGame.java:5)
My code for my main class is as follows:
import java.util.Scanner;
public class PlayGame {
static GameLogic GLObject = new GameLogic();
static Bot botObject = new Bot();
public static void main(String [] args){
System.out.println("Enter the file name and extension in the form file_name.extension:");
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
Map mapObject = new Map();
mapObject.readMap(fileName);
while(true){
getMove();
}
}
public static void getMove(){
System.out.println("Enter what you wish to do:");
Scanner scanner_1 = new Scanner(System.in);
String move = scanner_1.nextLine();
move = move.toUpperCase();
useMove(move);
}
public static void useMove(String move){
if(move.equals("N")){
GLObject.MOVE('N');
}
else if(move.equals("E")){
GLObject.MOVE('E');
}
else if(move.equals("S")){
GLObject.MOVE('S');
}
else if(move.equals("W")){
GLObject.MOVE('W');
}
else if(move.equals("HELLO")){
GLObject.HELLO();
}
else if(move.equals("PICKUP")){
GLObject.PICKUP();
}
else if(move.equals("LOOK")){
GLObject.LOOK();
}
else if(move.equals("QUIT")){
GLObject.QUIT();
}
else if(move.equals("BOT")){
botObject.getMap();
}
else{
System.out.println("This is not a valid input!!");
}
}
}
The code for the bot class currently is:
public class Bot {
GameLogic GLObject = new GameLogic();
char [][] Array;
int Column = GLObject.Column;
int Row = GLObject.Row;
boolean goldMarker = false;
int goldNumber = Integer.parseInt(Map.goldNumber);
int goldCount = 0;
boolean exitSet = false;
public void getMap(){
Array = GameLogic.mapArrayGlobal;
GameLogic.printArray(Array);
traverseMap();
}
public void traverseMap(){
int direction = (int) (Math.random() * 4);
if(direction == 0){
MOVE('N');
}
else if(direction == 1){
MOVE('S');
}
else if(direction == 2){
MOVE('E');
}
else if(direction == 3){
MOVE('W');
}
}
Could anyone advise as to what is causing this problem.
Thank very much :)

Your problem is that Map.goldNumber is not an integer when you construct the Bot, causing the initialization to fail when you try to use parseInt. It should work if you make sure that there is a valid numerical string in Map.goldNumber.

Related

Need to make a Counter using enum ordinals

I need to make a counter array for a Rock Paper Scissors game but can not figure out how to make user input call the enum, and i need to make the moves for the game a counter for them to be used and compared to.
This is my enum
public enum Moves {
Rock(1),
Paper(2),
Scissors(3),
Lizard(4),
Spock(5), ;
private int countOf = 0;
private int moveVal;
private ArrayList<Moves> movesList = new ArrayList<>();
Moves(int moveVal) {
}
public int getmoveVal() {
return moveVal;
}
public int getCountOf() {
for(Moves moveList : Moves.values()) {
countOf++;
}
return countOf;
}
And this is my class that would call it
public static void main(String[] args) {
RockPaperScissorGame rsg = new RockPaperScissorGame(3);
Moves move[] = Moves.values();
int playerMove = 0;
for(int i = 0; i < move.length; i++) {
}
boolean continueGame = true;
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
while(continueGame)
{
System.out.println(rsg.moveChoices());
System.out.println("Enter Move:(1,2,3,4 or 5):");
playerMove = keyboard.nextInt();
rsg.playRound(move);
System.out.printf("AI %s!%n", rsg.getAIOutcome().toString());
System.out.printf("Player %s!%n", rsg.getPlayerOutcome().toString());
System.out.println(rsg.moveOutcome());
System.out.println(rsg.currentScore());
if(rsg.isGameOver())
{
System.out.println(rsg.currentWinTotal());
System.out.println("Do you want to Play Again(1 - Yes , 2 - No):");
int answer = keyboard.nextInt();
if(answer == 2)
{
continueGame = false;
}
else
{
rsg.reset();
}
}
}
You can iterate through values to find a Move matching that moveVal:
public Move fromMoveVal(int moveVal) {
for (Move m : Move.values()) if (m.moveVal == moveVal) return m;
return null;
}

NZEC error for ACODE spoj

I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.

Hangman checking used guesses form user

I am looking for some help scanning the array for the used letters in the user input and tell them, so I am lost at this point.
/**
*
*/
package Hangman;
import java.io.IOException;
/**
* #author
*
*/
public class Hangman {
static int choice;
static String solve;
static String promt;
static String guess;
static char chaGuess;
static char[] guesses = new char[25];
static char[] check;
static int counter = 1;
static boolean contine;
public static void main(String[] args) throws IOException, InterruptedException {
playerOne();
for (int i = 0; i < 300; i++) {
System.out.println(" ");
}
while (contine = true) {
playerTwo();
choiceMade(choice);
}
}
public static String playerOne() throws IOException {
System.out.println("Welcome player one");
promt = ConsoleUI.promptForInput("Enter a Phrase or word for Player Two to guess", true);
return promt;
}
public static int playerTwo() throws IOException {
String[] ask = new String[3];
ask[0] = "Give up";
ask[1] = "Guess a letter";
ask[2] = "Solve the puzle";
choice = ConsoleUI.promptForMenuSelection(ask, true);
return choice;
}
public static void choiceMade(int c) throws IOException {
if (c == 0) {
contine = false;
System.out.println("Thank you for playing");
System.exit(0);
}
if (c == 1) {
guess = ConsoleUI.promptForInput("Enter your guess", true);
guessChar(guess);
contine = true;
} else if (c == 2) {
solve = ConsoleUI.promptForInput("Enter your answer", true);
if (solve.equals(promt)) {
System.out.println("You solved it you're amazing");
contine= false;
} else {
System.out.println("Sorry you guessed it wrong.");
System.exit(0);
contine= false;
}
}
}
public static char guessChar(String g) {
chaGuess = g.charAt(0);
promt = promt.replace(" ", "");
check = promt.toCharArray();
if(guesses[counter -1] != chaGuess)
if (chaGuess >= 'a' && chaGuess <= 'z' || chaGuess >= 'A' && chaGuess <= 'Z') {
guesses[counter] = chaGuess;
System.out.println(guesses);
}
if(guesses[counter - 1] == chaGuess)
{
System.out.println("You all ready guessed that");
}
}
counter++;
return chaGuess;
}
}
Use a string, append each used guess to the end of it, and then just use indexOf()

Java Input Validation

So I am working with a program that is supposed to incorporate try-catch blocks for exception handling. What I can't figure out is how to write a simple if statement for checking input from the user via Scanner to make sure it is a double and not a letter or a character so that if it is the program will catch it, display the error message, and tell the user to re-enter another value until a suitable input is entered. What I am looking for is a simple if(_width equals a letter/character) then return false along with an error message to go along with my already present if statement that checks whether the input is greater than zero.
my current code is below:
public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if( !isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if ( !isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
if ()
}
public boolean isValidHeight(double _height) {
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
My class is being called by another test program that i have written correctly. Any help is appreciated! Thank you.
maybe something like:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
try {
Double.parseDouble(str);
}
catch( Exception e ){
System.out.println(errorMessage);
}
or iterate through the input and check if each character is digit:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i=0;i<str.length();i++){
char token = str.charAt(i);
if(!Character.isDigit(token) && token!='.' ) {
System.out.println(token + " doesnt work");
break;
}
}
On declaring your scanner you could also:
double num;
String errorMessage = "error";
while(true) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
num = in.nextDouble();
System.out.println(num);
break;
}
else System.out.println(errorMessage);
}
Maybe this code helps you:
double Input=0;
while(!(Input > 0)){{
System.out.println("Enter Valid Number");
Input = new Scanner(System.in).nextDouble();
}

I get an error message as follows: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));

Categories