String index out of range: 4 - java

I am a beginner here to Java. So I tried to run this code here, but it kept giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4.
I need some help. Here is my code:
import java.util.Scanner;
public class TestFour
{
public static void main(String[]args)
{
String inp= new String();
Scanner scan = new Scanner(System.in);
System.out.println("Enter Word ");
inp = scan.nextLine();
int output = 1;
int [] board = new int[40];
int points = 0;
int totalpoints = 0;
int input;
//start of for loop
for(int i = 0; i < 5; i++)
{
input = scan.nextInt();
for (int j = 0; j < inp.length(); j++)
{
//values of letters
if(inp.charAt(i) == 'a' || inp.charAt(i) == 'e')
{
points = 1;
}
else if(inp.charAt(i) == 'd' || inp.charAt(i) == 'r')
{
points = 2;
}
else if(inp.charAt(i) == 'b' || inp.charAt(i) == 'm')
{
points = 3;
}
else if(inp.charAt(i) == 'v' || inp.charAt(i) == 'y')
{
points = 4;
}
else if(inp.charAt(i) == 'j' || inp.charAt(i) == 'x')
{
points = 8;
}
else
{
points = points;
}
//checking if double letter or triple letter and executing program
if ( input % 3 == 0 && input % 6 != 0)
{
points = points * 2;
}
else
{
points = points;
}
if (input % 5 == 0 && input != 15)
{
points = points * 3;
}
else
{
points = points;
}
totalpoints = totalpoints + points;
input = input + 1;
}//end of for loop
input = input - 4;
//checking if double word or triple word and executing program
for (int k = 0; k < inp.length(); k++)
{
if (input % 7 == 0 && input != 21 && input != 25)
{
totalpoints = totalpoints * 2;
}
else
{
totalpoints = totalpoints;
}
if (input % 8 == 0 && input != 40)
{
totalpoints = totalpoints * 3;
}
else
{
totalpoints = totalpoints;
}
input = input + 1;
}
}
System.out.println(totalpoints);
}
}
The problem starts at the for loop the fifth time I enter the input. Thank you for your time. I really don't get how to fix it even though I know what is going on.

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Related

Creating a number rectangle in Java using a nested for loop with one number input

I'm new to Java and have an assignment that requires me to create a rectangle of numbers where the numbers start from the 'user input' number and reduce to 1 in the middle (See example).
I've created a very simplified code that can do it, but I would have to create an 'else if' for each number up to the 'user input' number.
Obviously, there is a way to repeat the code using some variable, but I can't seem to figure out how to do it. Can I get some help? Here is the code I am at right now:
import java.util.Scanner;
public class Assign {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Select rectangle size:");
int user = scan.nextInt();
for (int row = 1; row <= ((user*2)-1); row++) {
for (int col = 1; col <= ((user*2)-1); col ++) {
if ((row == 1) || (col == 1) || (row == (user*2)-1) || (col == (user*2)-1)) {
System.out.printf("%2d",user);
}else if ((col == (2)) || col == (user*2)-(2) || row == 2 || row == (user*2)-(2)) {
System.out.printf("%2d",user - (1));
}else if ((col == (3)) || col == (user*2)-(3) || row == 3 || row == (user*2)-(3)) {
System.out.printf("%2d",user - (2));
}else if ((col == (4)) || col == (user*2)-(4) || row == 4 || row == (user*2)-(4)) {
System.out.printf("%2d",user - (3));
}else if ((col == (5)) || col == (user*2)-(5) || row == 5 || row == (user*2)-(5)) {
System.out.printf("%2d",user - (4));
}
}
System.out.println();
}
input.close();
}
}
I have a solution for this problem. I hope It can help you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please select your max number:");
int userChoice = input.nextInt();
int end = userChoice * 2 - 1;
int decrement = 0;
int increment = 0;
for (int i = 0; i < end; i++) {
for (int j = 0; j < end; j++) {
if(end - i - 1 < j) {
increment++;
}
System.out.print(userChoice - decrement + increment);
if(decrement < i) {
decrement++;
}
}
decrement = 0;
increment = 0;
System.out.println();
}
input.close();
}

my do-while loop seems to be running forever even though i change the value of the condition

boolean onGoing = true;
do {
String p1 = "playing";
while (p1.equals("playing")) {
System.out.println("Player 1, enter hit row/column:");
int a = sc.nextInt();
int b = sc.nextInt();
if (a >= 0 && a < 5 && b >= 0 && b < 5) {
if (history1[a][b] == '-') {
p1 += " no more";
if (board2[a][b] == '#') {
history1[a][b] = 'X';
board2[a][b] = 'X';
String status = check(board2);
if (status.equals("win")) {
System.out.println("PLAYER 1 WINS! YOU SUNK ALL OF YOUR OPPONENT'S SHIPS!");
onGoing = false;
printBattleShip(board1);
printBattleShip(board2);
break;
} else {
System.out.println("PLAYER 1 HIT PLAYER 2's SHIP!");
}
} else if (board2[a][b] == '-') {
System.out.println("PLAYER 1 MISSED!");
history1[a][b] = 'O';
board2[a][b] = 'O';
}
} else {
System.out.println("You already fired on this spot. Choose different coordinates.");
}
} else {
System.out.println("Invalid coordinates. Choose different coordinates.");
}
}
String p2 = "playing";
while (p2.equals("playing")) {
System.out.println("Player 2, enter hit row/column:");
int c = sc.nextInt();
int d = sc.nextInt();
if (c >= 0 && c < 5 && d >= 0 && d < 5) {
if (history2[c][d] == '-') {
p2 += " no more";
if (board1[c][d] == '#') {
history2[c][d] = 'X';
board1[c][d] = 'X';
String status = check(board1);
if (status.equals("win")) {
System.out.println("PLAYER 2 WINS! YOU SUNK ALL OF YOUR OPPONENT'S SHIPS!");
onGoing = false;
printBattleShip(board2);
printBattleShip(board1);
break;
} else {
System.out.println("PLAYER 2 HIT PLAYER 1's SHIP!");
}
} else if (board1[c][d] == '-') {
history2[c][d] = 'O';
board1[c][d] = 'O';
System.out.println("PLAYER 2 MISSED!");
}
} else {
System.out.println("You already fired on this spot. Choose different coordinates.");
}
} else {
System.out.println("Invalid coordinates. Choose different coordinates.");
}
}
} while (onGoing);
private static String check(char[][] arr1) {
int sum = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1.length; j++) {
if (arr1[i][j] == '#') {
sum += 1;
}
}
}
if (sum == 0) {
return "win";
} else {
return "keep playing";
}
}
// I declared and initialized a boolean variable called ongoing before a do-while loop. Then I create a while loop inside the do while loop. And inside the while loop, there are a series of conditional statement. Eventually, I changed the value of the boolean variable and feed it back to the while statement, letting it evaluate it. But it doesn't seem to change the value. Is it because the scope of the variable? How can I fix it?
edit: check method added

im having trouble in while loop

I'm making a simple "Whack a mole" game in Java. For simplicity I have created a 10*10 box and placed 10 moles in random boxes. I want to exit the game when the user spent his 50 inputs or found all 10 moles, but there seems to be a problem in terminating the while loop even when the user attempts specified inputs.
Is it Instance variable scope problem? Why it is not working?
public class WhackAMole {
int score = 0, molesLeft = 10, attempts;
char[][] moleGrid = new char[10][10];
int numAttempts, gridDimension;
public WhackAMole(int numAttempts, int gridDimension) {
// TODO Auto-generated constructor stub
this.numAttempts = numAttempts;
this.gridDimension = gridDimension;
}
boolean place(int x, int y) {
return (x == 2 && y == 5)
|| (x == 1 && y == 3)
|| (x == 8 && y == 4)
|| (x == 5 && y == 10)
|| (x == 6 && y == 9)
|| (x == 10 && y == 7)
|| (x == 3 && y == 7)
|| (x == 2 && y == 9)
|| (x == 4 && y == 8)
|| (x == 9 && y == 5);
}
void whack(int x, int y) {
if (place(x, y)) {
if (moleGrid[x - 1][y - 1] == 'W') {
System.out.println("Already attempted! \'try other co-ordinates\' \n");
} else {
moleGrid[x - 1][y - 1] = 'W';
this.score ++;
this.molesLeft --;
}
}
}
void printGridToUser() {
System.out.println("your score is " + score + " and " + molesLeft + " moles are left. \n");
System.out.println("input x = -1 and y = -1 to quit the game! \n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
System.out.print(" " + moleGrid[i][j] + " ");
}
System.out.println("\n");
}
}
void printGrid() {
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
this.moleGrid[i][j] = '*';
}
}
}
public static void main(String[] args) {
WhackAMole game;
System.out.println("Lets play the Whack A Mole!\n");
game = new WhackAMole(50, 100);
game.printGrid();
game.printGridToUser();
Scanner scanner = new Scanner(System.in);
while ((game.numAttempts > 0) || (game.molesLeft > 0)) {
System.out.println("Enter box co-ordinate\n");
System.out.println("x co-ordinate: \n");
int x = scanner.nextInt();
System.out.println("y co-ordinate: \n");
int y = scanner.nextInt();
if (x == -1 && y == -1) {
break;
} else if ((x < 1 || y < 1) || (x > 10 || y > 10)) {
System.out.println("please enter values of x and y greater than 0 and less than 11! \n");
} else {
game.whack(x, y);
game.numAttempts--;
game.gridDimension--;
System.out.println("you can have upto " + game.numAttempts + " out of " + game.gridDimension + " boxes \n");
game.printGridToUser();
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (game.place(i+1, j+1) && game.moleGrid[i][j] != 'W'){
game.moleGrid[i][j] = 'M';
}
}
}
game.printGridToUser();
scanner.close();
System.out.println("game over!!!\n");
}
}
Your while loop is not ending because you are using || in your while loop. The || is making your loop run until the attempts allowed i.e. 50 and the right guessing i.e. finding moles correct both are met. So even when a gamer has finished his allowed attempts and hasn't guessed all the right moles positions, the loop will not end
The simple solution would be to replace || with &&
while ((game.numAttempts > 0) && (game.molesLeft > 0))
And avoid using fixed numbers i.e. 10 in your for loops instead use
for (int i = 0; i < game.gridDimension; i++) {
for (int j = 0; j < game.gridDimension; j++) {
I hope it helps
Your loop is using an or for the test function. This means both condition mist be false in order for it to stop. In your case. How its written you must exhaust the numtries and have no moles left.
Change to use && vs ||.

Simple mars rover example

The robot starts from coordinates (0,0) while pointing in the north direction.
User input = string such as LRLRLLFRRFRLRF. Here L = point left, R =
point right, F = move forward one unit.
Output = (5,6) = final
coordinates of the robot.
I am using Java Scanner class to get input from user. But the output is blank.
Here is my complete code:
public static void printLocation() {
// index 0 = North, index 1 = East, index 2 = South, index 3 = West
System.out.println("Enter the sequence"); //eg - LRFFRRLRLF
Scanner scan = new Scanner(System.in);
int index=0, x=0, y=0;
while(scan.hasNext()) {
String token = scan.next();
if(token.equals("R")) {
index=index+1;
}
if(token.equals("L")) {
index=index-1;
}
if(index > 3 && index%3 !=0) {
index = index%3-1;
}
else if(index > 3 && index%3 == 0) {
index = 3;
}
if(token.equals("F")) {
if(index == 0) {
y=y+1;
}
if(index == 1) {
x=x+1;
}
if(index == 2) {
y=y-1;
}
if(index == 3) {
x=x-1;
}
}
}
System.out.println("("+x+","+y+")");
}
What am I doing wrong ? A little help please.
You need to read the contents of the entered string like this
String pathSequence = sc.next();
And then iterate over each letter in the string pathSequence
Your output is blank, because the program expects another input to enter when you use scan.hasNext(). One of the ways is to read the whole string using scan.nextLine(), convert it to char array and then parse it symbol by symbol.
public static void printLocation() {
// index 0 = North, index 1 = East, index 2 = South, index 3 = West
System.out.println("Enter the sequence"); //eg - LRFFRRLRLF
Scanner scan = new Scanner(System.in);
String sequence = scan.nextLine();
char[] sequenceArray = sequence.toCharArray();
int index = 0, x = 0, y = 0;
int i = 0;
while (i < sequenceArray.length) {
String token = String.valueOf(sequenceArray[i]);
i++;
if (token.equals("R")) {
index = index + 1;
}
if (token.equals("L")) {
index = index - 1;
}
if (index > 3 && index % 3 != 0) {
index = index % 3 - 1;
} else if (index > 3 && index % 3 == 0) {
index = 3;
}
if (token.equals("F")) {
if (index == 0) {
y = y + 1;
}
if (index == 1) {
x = x + 1;
}
if (index == 2) {
y = y - 1;
}
if (index == 3) {
x = x - 1;
}
}
}
System.out.println("(" + x + "," + y + ")");
}
However, you should check to logic of your code yourself. I can't be sure it is correct. If you enter LRLRLLFRRFRLRF, the output will be (1,1). So test it yourself.

Creating a random colour grid with all adjacent colours different

So I have the following problem set to me: Write a program that takes an integer command-line argument N, and uses two nested for loops to print an N-by-N board that alternates between 6 colours randomly separated by spaces. The colours are denoted by letters (like 'r' for RED, 'b' for BLUE). You are not allowed to have two of the same colour next to eachother.
So, I know I probably need arrays to get around this problem. I tried several methods that all came up wrong. The following is one of my recent attempts, but I am unsure as how to now go through the grid and correct it. What the code does is make every row randomized with no colour left or right the same, but the columns are not fixed.
Note that I am a first year CS student with no programming history. I am guessing the solution to this problem isnt too complex, however, I cant see a simple solution...
int N = StdIn.readInt();
int array1[] = new int[N];
for (int column = 0; column < N; column++) {
int x = 0;
for (int row = 0; row < N; row++) {
int c = (int) (Math.random() * 6 + 1);
while (x == c) {
c = (int) (Math.random() * 6 + 1);
array1[row] = c;
}
if (c == 1) {
System.out.print("R ");
}
if (c == 2) {
System.out.print("O ");
}
if (c == 3) {
System.out.print("Y ");
}
if (c == 4) {
System.out.print("G ");
}
if (c == 5) {
System.out.print("B ");
}
if (c == 6) {
System.out.print("I ");
}
x = c;
}
System.out.println();
}
}
this was my solution for the problem. Quite convoluted though, but the logic behind it is straightforward. Each time you assign a new colour to your 2D array, you need only check the value of the array to the top and to the left of the position where you want to assign a new colour. You can only do this after you have assigned colours to the first row of the array however so you need to create separate conditions for the first row.
public class ColourGrid {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
char[][] clrGrid = new char[N][N];
char colours[] = {'r','b','y','w','o','g'} ;
for (int counter = 0 ; counter < N; counter++) {
for (int counter2 = 0 ; counter2 < N; counter2++) {
if (counter == 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
else if (counter != 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter == 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)][counter2-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter != 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2] || clrGrid[counter][counter2] == clrGrid[counter][(counter2)-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
}
for (int counter = 0 ; counter < N; counter++) {
System.out.println("");
for (int counter2 = 0 ; counter2 < N; counter2++) {
System.out.print(clrGrid[counter][counter2] + " ");
}
}
}
}

Categories