Java Thread

danthrax

Member
Question for you savvy Java folks. I have dabbled in programming in a couple different languages (C#, VisualBasic, and C++) and I would really like to learn and understand Java well enough to write a program to solve a complex problem. I'm interested in Java for several other reasons as well.

My question is, from what sources do you recommend learning Java? I have heard of several different books that are good. I tend to learn well (as I'm sure a lot of programmers do) from examples and trying things on my own. Do any of you know of good online tutorials? I have viewed several tutorials on YouTube that I have enjoyed so far.

I've been reading through the Java thread and some of you are clearly very knowledgeable about the language! So any input is greatly appreciated.

Thanks!
 

Krazyshank

New Member
Need some help with user input (Java)

I am currently trying to make a program that determines what instrument you should play from the users inputs. EX: Do you want to play a wind instrument?
then the user will input true or false. But i have no idea how to right user input to text strings and/or boolean logic variables. Here is my code so far, I am aware that it has many errors spelling/capitalization wise, but I can fix that later. Please just show me how I could accomplish this.
My code:
import java.util.Scanner;

class Instrument {
public static void main(String[] arguments) {
// Guessing Game intro start
System.out.println("Hello there! I am the amazing, fantastic, intreaging guessing galore!")
System.out.println("I will guess your destined instruement!")
// Guessing Game intro end
// Variables
int questionsAsked = 0;
String Saxophone = Saxophone;
String Clairinet = Clairinet;
String Flute = Flute;
String Piano = Piano;
String Barrackas = Barrackas;
String Guitar = Guitar;
String Violin = Violin;
String Viola = Viola;
String Chello = Chello;
String Banjo = Banjo;
String Harp = Harp;
String String = String;
String Drums = Drums;
String Triangle = Triangle;
String Bagpipes = Bagpipes;
String Ocarina = Ocarina;
String String = String;
String Wind = Wind;
String Hands = Hands;
String Sticks = Sticks;
String NoneOfTheFollowing = None Of The Following;
String Answer = " ";
// Boolean Logic
boolean Reed = false;
boolean Guitar = false;
boolean Violin = false;
boolean Viola = false;
boolean Chello = false;
boolean Banjo = false;
boolean Harp = false;
boolean String = false;
boolean Wind = false;
boolean Hands = false;
boolean Sticks = false;
boolean NoneOfTheFollowing = false;
boolean Saxophone = false;
boolean Clairinet = false;
boolean Flute = false;
boolean Piano = false;
boolean Barrackas = false;
boolean Drums = false;
boolean Triangle = false;
boolean Bagpipes = false;
boolean Ocarina = false;
// Questions
System.out.println("Let the questions begin, answer with either /"true/" or /"false/"!");
System.out.println("Do you want use " + Wind to play your instrument?");
int questionsAsked = 1;
// Key listener here, take answer and write to variable "Wind"
System.out.println("I have asked you " + questionsAsked so far");
System.out.println("Do you want to use a " + Reed to play your instrument?");
int questionsAsked = 2;
// Key listener here, take answer and write to variable "Reed"
System.out.println("I have asked you " + questionsAsked so far");
System.out.println("Do you want to use your " + Hands to play your instrument?");
int questionsAsked = 3;
// Key listener here, take answer and write to variable "Hands"
System.out.println("I have asked you " + questionsAsked so far");
System.out.println("Do you want to use " + Sticks to play your instrument?");
int questionsAsked = 4;
// Key listener here, take answer and write to variable "Sticks"
System.out.println("I have asked you " + questionsAsked so far");
System.out.println("Do you not want to use any of the following stated? " + NoneOfTheFollowing to play your instrument?");
int questionsAsked = 5;
// Key listener here, take answer and write to variable "NoneOfTheFollowing"
System.out.println("I have asked you " + questionsAsked so far. Now I am ready to present my answer");
// End questioning
// Method Statements here
System.out.println("Your favorite instrument is " + Answer")
System.out.println("Is that the correct answer?")
// Answer Key listener here

-----------------------------------------------
its not done and the import is not being used but as far as I know, its needed for the java scanner. so where it says // Key listener here, take answer and write to variable, I want it to take the userinput and store it to teh string so I can use it later. im 13 so this code is good so far :/
 

Cromewell

Administrator
Staff member
I've merged your thread into our java thread.

First, what is going on with your variable declarations? You don't need to say String String = String;. This particular one is also important because you are trying to name a variable with a reserved word. Your string declarations can simply be String InstrumentName; or if you want to explicitly initialize String InstrumentName = "";.
Also, you're redeclaring questionsAsked a lot, that'll generate a compiler error.

The Java API doc is actually a pretty good reference guide (http://download.oracle.com/javase/6/docs/api/index.html). You do have to know what you are looking for though. In this case it's easy: Scanner.

There are some user input examples in this thread already but here's a quick rundown again:

Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextString(); //userInput now has a string read from standard in

Like with all user input you'll have to test to make sure that they gave you what you asked for (pesky users always want to break your code).
 

Krazyshank

New Member
I've merged your thread into our java thread.

First, what is going on with your variable declarations? You don't need to say String String = String;. This particular one is also important because you are trying to name a variable with a reserved word. Your string declarations can simply be String InstrumentName; or if you want to explicitly initialize String InstrumentName = "";.
Also, you're redeclaring questionsAsked a lot, that'll generate a compiler error.

The Java API doc is actually a pretty good reference guide (http://download.oracle.com/javase/6/docs/api/index.html). You do have to know what you are looking for though. In this case it's easy: Scanner.

There are some user input examples in this thread already but here's a quick rundown again:

Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextString(); //userInput now has a string read from standard in

Like with all user input you'll have to test to make sure that they gave you what you asked for (pesky users always want to break your code).

Thanks alot! But for the String String = String thing, the string data (Which is also the word string lol) was mean to be like for stringed instruments.

But anyway,
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextString(); //userInput now has a string read
So waht will that write the input to? The next string under it?
Oh and what could I use to fis the questionsAsked problem? And one more thing, so far does the code seem to be PARTIALY on the correct track for where I am going? DO i even need all those strings? I just put them in there just incase I needed them for declaring the answer.
 
Last edited:

Cromewell

Administrator
Staff member
Thanks alot! But for the String String = String thing, the string data (Which is also the word string lol) was mean to be like for stringed instruments.
What I mean is, in general, you don't want to write a variable declaration like String name = name;. I figured out that you meant the string section of an orchestra but in that case you'll need a different name :)
But anyway,
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextString(); //userInput now has a string read
So waht will that write the input to? The next string under it?
The input is stored in the userInput variable. When you write String userInput = scanner.nextString(); you are declaring a String variable named userInput and assigning it the value of a string read from scanner.
Oh and what could I use to fis the questionsAsked problem?
Just remove the int from all lines but the initial declaration.
class Instrument {
public static void main(String[] arguments) {
// Guessing Game intro start
System.out.println("Hello there! I am the amazing, fantastic, intreaging guessing galore!")
System.out.println("I will guess your destined instruement!")
// Guessing Game intro end
// Variables
int questionsAsked = 0;
// Questions
System.out.println("Let the questions begin, answer with either /"true/" or /"false/"!");
System.out.println("Do you want use " + Wind to play your instrument?");
questionsAsked = 1; //// <------------------Notice no int at the start of this line, you could also write this as an incremetal operation.......i.e. questionsAsked++;
DO i even need all those strings? I just put them in there just incase I needed them for declaring the answer.
Depends on the requirements. Say I wanted to return all the answers they provided, in that case I would need to store all of their answers in a bunch of variables.
 

Krazyshank

New Member
What I mean is, in general, you don't want to write a variable declaration like String name = name;. I figured out that you meant the string section of an orchestra but in that case you'll need a different name :)

The input is stored in the userInput variable. When you write String userInput = scanner.nextString(); you are declaring a String variable named userInput and assigning it the value of a string read from scanner.
Just remove the int from all lines but the initial declaration.
class Instrument {
public static void main(String[] arguments) {
// Guessing Game intro start
System.out.println("Hello there! I am the amazing, fantastic, intreaging guessing galore!")
System.out.println("I will guess your destined instruement!")
// Guessing Game intro end
// Variables
int questionsAsked = 0;
// Questions
System.out.println("Let the questions begin, answer with either /"true/" or /"false/"!");
System.out.println("Do you want use " + Wind to play your instrument?");
questionsAsked = 1; //// <------------------Notice no int at the start of this line, you could also write this as an incremetal operation.......i.e. questionsAsked++;

Depends on the requirements. Say I wanted to return all the answers they provided, in that case I would need to store all of their answers in a bunch of variables.

Ok sweet, I will keep that in mind! I have also rewritten the program with the scanner in it and I used if and else statements to make things easier to understand and the program shorter.

Ill reply back with the results later.
 

Krazyshank

New Member
What I mean is, in general, you don't want to write a variable declaration like String name = name;. I figured out that you meant the string section of an orchestra but in that case you'll need a different name :)

The input is stored in the userInput variable. When you write String userInput = scanner.nextString(); you are declaring a String variable named userInput and assigning it the value of a string read from scanner.
Just remove the int from all lines but the initial declaration.
class Instrument {
public static void main(String[] arguments) {
// Guessing Game intro start
System.out.println("Hello there! I am the amazing, fantastic, intreaging guessing galore!")
System.out.println("I will guess your destined instruement!")
// Guessing Game intro end
// Variables
int questionsAsked = 0;
// Questions
System.out.println("Let the questions begin, answer with either /"true/" or /"false/"!");
System.out.println("Do you want use " + Wind to play your instrument?");
questionsAsked = 1; //// <------------------Notice no int at the start of this line, you could also write this as an incremetal operation.......i.e. questionsAsked++;

Depends on the requirements. Say I wanted to return all the answers they provided, in that case I would need to store all of their answers in a bunch of variables.

Hey, how can I make the scanner work for integers?
is it just
Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextint();

???

and also, can I change
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextString();

The userInput string from that to any name?
 

Cromewell

Administrator
Staff member
Hey, how can I make the scanner work for integers?
is it just
Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextint();
The doc page tells you all the methods on scanner, but yes it's just nextInt() :) http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html

You'll have to be careful about reading numeric types because it will throw exceptions if it doesn't find what it's looking for. You just need to use a try/catch block but if you are just starting out you may not have learned about those yet.
The userInput string from that to any name?
Yes, the variable you are reading into can be whatever name you want.
 

Krazyshank

New Member
Okay, got another program here.
Its a calculator. I didnt look online to see what methods people used to code theres so here it is

import java.util.Scanner;

class Calculator
public static void main(String[] argments) {
int answer = 0;
System.out.println("Please type your starting number.");
Scanner scanner = new Scanner(System.in);
int firstNumber = scanner.nextInt();
System.out.println("Please type /n/"+/" for addition /n/"-/" for subtraction /n/"//" for division /n or /"*/" for multiplication.");
Scanner scanner = new Scanner(System.in);
String type = scanner.nextint();
if (type = +) {
System.out.println("What number would you like to add to " + firstNumber?");
Scanner scanner = new Scanner(System.in);
int secondNumber = scanner.nextInt();
int answer = firstNumber + secondNumber;
System.out.println(" + firstNumber plus " + secondNumber equals " + answer.");
else if (type = /)
System.out.println("What number would you like to divide " + firstNumber by?");
Scanner scanner = new Scanner(System.in);
int secondNumber = scanner.nextInt();
int answer = firstNumber / secondNumber;
System.out.println(" + firstNumber divided by " + secondNumber equals " + answer.");
else if (type = -)
System.out.println("What number would you like to subtract from " + firstNumber?");
Scanner scanner = new Scanner(System.in);
int secondNumber = scanner.nextInt();
int answer = firstNumber - secondNumber;
System.out.println(" + firstNumber minus " + secondNumber equals " + answer.");
else if (type = *)
System.out.println("What number would you like to multiply " + firstNumber by?");
Scanner scanner = new Scanner(System.in);
int secondNumber = scanner.nextInt();
int answer = firstNumber + secondNumber;
System.out.println(" + firstNumber multiplied by " + secondNumber equals " + answer.");
}
}
}


For some reason,when I compile i get 67 errors!!11 D=
wahts wrong?
 

Cromewell

Administrator
Staff member
There's a whole host of things. The compiler should tell you what they are and the line number. Some of which we've already talked about, such as redeclaring variables.

Another thing, the escape character is \ not / which may cause cascading errors.

For one more I goofed on the scanner, to read a string it's just .next(); not .nextString();

Additionally, to compare non-primitives (int, float, double, etc) in Java use the .equals method otherwise you aren't doing the operations you think you are. Using == you are actually comparing the reference and testing if 2 objects are the same.
 

Bananapie

New Member
So I just got a program from my teacher. It started off as a basic airline reservation program. Show diagram of plane, show empty seats/taken seats without displaying info about that person. Menu driven/user input(We decide what info to collect)

I collected the Name of the person, the seat they plan to reserve, and their phone number.

I hand it in, get 100%. Well this program we were told was going to be built on incrementally. No problem, had a good feel for it.

Next class day, she gives us someone elses program and the new requirements that we have to meet... the new requirements are:
-Have user enter name, telephone number, address, city, state, and zip.
-Name cannot have any numbers
-Must issue an ID number to allow look-up of passenger in menu
-Must be able to search by phone number or id number in case the passenger forgets their seat.
-Change size of plane from 8 rows(4 columns) to 5 rows(4 columns)

Well the person's program I got was built SPECIFICALLY for the first requirements, and making it entirely far to difficult to make any changes to... and did a lot of unnecessary garbage in the mean time.

It would be far easier to write an entirely new program to meet the requirements than edit this idiots program, but sadly that is not one of the requirements. :( I know who's program it is, and really want to hurt them because they KNEW it would be built on.

Did I mention that he does this on an EXAM program? Meaning it's a pretty large part of my grade.

/end rant. fml :|
 

Troncoso

VIP Member
Soo...looking for some java guys here.

I'm making a board game into a computer game. You choose a character and a path to follow. You roll the dice to move down the path and pick up attack cards and health cards along the way. You also have a chance of landing on a special ability, in which case a special ability card is added to your deck. <<<<< This is were my trouble is at the moment.

I have a method called drawCard() when I land on such spaces. the method chooses a random card, displays what it is, and adds it to an arrayList<Integer>.
Now, I have 2 methods that use this method. 1 Is playerTurn() and the other is computerTurn(). When I execute these methods independent of actually running the game, the draw card method works fine. I know this, because after the player or the computer has reached the end, it prints their stats along with all the cards in their deck. BUT, when I just play the game, it runs fine, but when a player reaches the end, it doesn't print which cards they have. Here is the code for all relevant classes:

MainGame
Code:
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;

/**
* Write a description of class MainGame here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class MainGame
{
    // instance variables - replace the example below with your own
    private Scanner input;
    private Random rand;
    private Character player, computer;
    private Path chosenPath, computerPath;
    private int spaces, computerSpaces, numTurns = 0;
    private int atkBonus, hpBonus, computerAtk, computerHp;
    private ArrayList<Integer> cardDeck, computerDeck;
    private SpecialCard specialCardDeck;
    private boolean playerTurn = true;
    private boolean lostTurn = false;
    private boolean compLostTurn = false;

    /**
     * Constructor for objects of class MainGame
     */
    public MainGame()
    {
        input = new Scanner(System.in);
        rand = new Random();
        showMenu();
        
    }
    
    /**
     * Display the instructions
     */
    public void showInstructions()
    {
        System.out.println("To begin playing, first choose a character.");
        System.out.println("Each character has different stats, so choose wisely");
        System.out.println("Once you've chosen a character, choose a path.");
        System.out.println("Each path contains a different amount of upgrades for your character.");
        System.out.println("These upgrades include attack, health and special abilities.");
        System.out.println("Which path you choose is up to you.\n");
        System.out.println("when the game starts, you will roll a dice.");
        System.out.println("The dice will show how many spaces you move.");
        System.out.println("If you land on an attack or health space, you will receive a bonus");
        System.out.println("If you land on a special ability space, a special ability card will \nbe added to your deck.");
        System.out.println("This will continue until you reach the arena. At that time, the \nrules for the arena will be displayed.");
        input.nextLine();
        showMenu();
    }
    
    /**
     * Show the menu
     */
    public void showMenu()
    {
        int choice = 0;
        
        System.out.println("1. New Game");
        System.out.println("2. Continue");
        System.out.println("3. Instructions");
        System.out.println("4. Quit\n");
        if (input.hasNextInt())
            choice = input.nextInt();
        input.nextLine();
        
        while (choice < 1 || choice > 4)
        {
            System.out.println("This choice is not valid. Please choose 1 through 4.\n");
            if (input.hasNextInt())
                choice = input.nextInt();
            input.nextLine();
        }
        
        if (choice == 1)
        {
            startGame();
        }
        else if (choice == 2)
        {
            continueGame();
        }
        else if (choice == 3)
        {
            showInstructions();
        }
        else if (choice == 4)
        {
            quit();
        }
    }
    
    public void startGame()
    {
        /****************
         * player setup *
         ****************/
        int choice = 0;
        System.out.println("Welcome! Before starting the game, please select your character:\n");
        System.out.println("1. Warrior:   20 Health  8-Sided Die");
        System.out.println("2. Soldier:   35 Health  6-Sided Die");
        System.out.println("3. Defender:  50 Health  4-Sided Die");
        System.out.println("4. Return to menu\n");
        if (input.hasNextInt())
                choice = input.nextInt();
        input.nextLine();
       
        while (choice < 1 || choice > 4)
        {
            System.out.println("This choice is not valid. Please choose 1 through 4.\n");
            if (input.hasNextInt())
                choice = input.nextInt();
            input.nextLine();
        }
        
        if (choice == 1)
        {
            player = new Character(20, 8, "Warrior");
        }
        else if (choice == 2)
        {
            player = new Character(35, 6, "Soldier");
        }
        else if (choice == 3)
        {
            player = new Character(50, 4, "Defender");
        }
        else if (choice == 4)
        {
            quit();
        }
        
        System.out.println("Now you must choose which path you will take:\n");;
        System.out.println("1. Balanced Path: Upgrades are even");
        System.out.println("2. Attack Path:   Mostly attack upgrades");
        System.out.println("3. Defense Path:  Mostly health upgrades");
        System.out.println("4. Special Path:  Less upgrades, more special abilities\n");
        if (input.hasNextInt())
                choice = input.nextInt();
        input.nextLine();
       
        while (choice < 1 || choice > 4)
        {
            System.out.println("This choice is not valid. Please choose 1 through 4.\n");
            if (input.hasNextInt())
                choice = input.nextInt();
            input.nextLine();
        }
        
        if (choice == 1)
        {
            chosenPath = new Path(.40, .40, .15, "Balance");
        }
        else if (choice == 2)
        {
            chosenPath = new Path(.60, .20, .15, "Attack");
        }
        else if (choice == 3)
        {
            chosenPath = new Path(.20, .60, .15, "Defense");
        }
        else if (choice == 4)
        {
            chosenPath = new Path(.35, .35, .24, "Special"); 
        }
        /******************
         * computer setup *
         ******************/
        int decision = rand.nextInt(3) + 1;
        if (decision == 1)
        {
            computer = new Character(20, 8, "Warrior");
        }
        else if (decision == 2)
        {
            computer = new Character(35, 6, "Soldier");
        }
        else if (decision == 3)
        {
            computer = new Character(50, 4, "Defender");
        }
        
        int decision2 = rand.nextInt(4) + 1;
        if (decision2 == 1)
        {
            computerPath = new Path(.40, .40, .15, "Balance");
        }
        else if (decision2 == 2)
        {
            computerPath = new Path(.60, .20, .15, "Attack");
        }
        else if (decision2 == 3)
        {
            computerPath = new Path(.20, .60, .15, "Defense");
        }
        else if (decision2 == 4)
        {
            computerPath = new Path(.35, .35, .24, "Special"); 
        }
        
        System.out.println("The computer chooses to be a " + computer.getCharType());
        System.out.println("and will travel the " + computerPath.getPathName() + " path\n");
        /******************
         * Start the game *
         ******************/
        spaces = chosenPath.getNumSpaces();
        computerSpaces = computerPath.getNumSpaces();
        System.out.println("Let the game begin!\n");
        input.nextLine();
        while (spaces > 0 || computerSpaces > 0)
            playGame(player, chosenPath, computer, computerPath);
    }
    
    public void continueGame()
    {
        System.out.println("Continuing game\n");
        input.nextLine();
        showMenu();
    }
    
    public void quit()
    {
        System.out.println("Ending game\n");
        input.nextLine();
        System.exit(0);
    }
    
    public void playGame(Character charChosen, Path pathChosen, Character computerChar, Path computerPath)
    {
        cardDeck = new ArrayList<Integer>();
        computerDeck = new ArrayList<Integer>();
        specialCardDeck = new SpecialCard();
        
        
        if (playerTurn == true)
        {
            if (spaces > 0)
            {
                if (lostTurn == false)
                {
                    playerTurn(player, chosenPath);
                    playerTurn = false;
                    System.out.println("************************\n");
                }
                else
                {
                    System.out.println("You lose this turn\n");
                    System.out.println("************************\n");
                    playerTurn = false;
                    lostTurn = false;
                }
            }
            else
            {
                System.out.println("You have reached the arena\n");
                System.out.println("************************\n");
                playerTurn = false;
            }
                
        }
        else
        {
            if (computerSpaces > 0)
            {
                if (compLostTurn == false)
                {
                    computerTurn(computer, computerPath);
                    playerTurn = true;
                    numTurns += 1;
                    System.out.println("************************\n");
                }
                else
                {
                    System.out.println("Computer loses this turn\n");
                    System.out.println("************************\n");
                    playerTurn = true;
                    compLostTurn = false;
                    numTurns += 1;
                }
            }
            else
            {
                System.out.println("The computer has reached the arena\n");
                System.out.println("************************\n");
                playerTurn = true;
                numTurns += 1;
            }
        }
        
    }
    
    
    private int rollMoveDice()
    {
        int roll = rand.nextInt(4) + 1;
        return roll;
    }
    
    /***************
     * player turn *
     ***************/
    public void playerTurn(Character charChosen, Path pathChosen)
    {
        String curSpace;
        System.out.println("Press enter to roll the die.");
        input.nextLine();
        int movement = rollMoveDice();
        int bonus = 0;
        System.out.println("You rolled a " + movement);
        input.nextLine();
        if (spaces - movement > 0)
        {
            spaces -= movement;
            curSpace = pathChosen.spaceValue();
            System.out.println("You landed on a " + curSpace + " space.");
            
            if (curSpace == "Attack")
            {
                bonus = rand.nextInt(3) + 1;
                atkBonus += bonus ;
                System.out.println("You gain " + bonus + " attack.\n");
            }
            else if (curSpace == "Defense")
            {
                bonus = rand.nextInt(3) + 4;
                hpBonus += bonus;
                System.out.println("You gain " + bonus + " health.\n");
            }
            else if (curSpace == "Special Ability")
            {
                drawSpecialCard(specialCardDeck, "You draw", cardDeck);
            }
            else if (curSpace == "Lose Turn")
            {
                lostTurn = true;
                System.out.println("You lose your next turn.\n");
            }
        }
        else
        {
            spaces = 0;
            System.out.println("You have reached the arena!\n");
            System.out.println("Total Attack bonus: " + atkBonus);
            System.out.println("Total Health bonus: " + (player.getInitHealth() + hpBonus));
            System.out.println("Special Cards in deck: ");
            for (int card = 0;card < cardDeck.size();card++)
            {
                System.out.println(cardDeck.get(card));
            }
        }
    }
    /*****************
     * Computer turn *
     *****************/
    public void computerTurn(Character charChosen, Path pathChosen)
    {
        String curSpace;
        System.out.println("Computer rolls the die.\n");
        int movement = rollMoveDice();
        int bonus = 0;
        System.out.println("Computer rolled a " + movement);
        if (computerSpaces - movement > 0)
        {
            computerSpaces -= movement;
            curSpace = pathChosen.spaceValue();
            System.out.println("The computer landed on a " + curSpace + " space.");
        
             if (curSpace == "Attack")
            {
                bonus = rand.nextInt(3) + 1;
                computerAtk += bonus ;
                System.out.println("Computer gains " + bonus + " attack.\n");
            }
            else if (curSpace == "Defense")
            {
                bonus = rand.nextInt(3) + 4;
                computerHp += bonus;
                System.out.println("Computer gains " + bonus + " health.\n");
            }
            else if (curSpace == "Special Ability")
            {
                drawSpecialCard(specialCardDeck, "The computer draws", computerDeck);
            }
            else if (curSpace == "Lose Turn")
            {
                compLostTurn = true;
                System.out.println("Computer loses next turn.\n");
            }
        }
        else
        {
            computerSpaces = 0;
            System.out.println("Computer has reached the arena!\n");
            System.out.println("Total Attack bonus: " + computerAtk);
            System.out.println("Total Health bonus: " + (computer.getInitHealth() + computerHp));
            System.out.println("Special Cards in deck: ");
            for (int card = 0;card < computerDeck.size();card++)
            {
                System.out.println(computerDeck.get(card));
            }
            
        }
    }
    
   
    
    public void drawSpecialCard(SpecialCard deck, String player, ArrayList<Integer> playerDeck)
    {
            deck.chooseCard();
            playerDeck.add(deck.getCard());
            System.out.println(player + " a special ability card:");
            System.out.println(deck.getCardDesc());
            System.out.println("Type: " + deck.getCardType() + "\n");
        
    } 
    
    public void resetSpaces()
    {
        spaces = 10;
        computerSpaces = 10;
    }
}

Path:
Code:
import java.util.Random;
/**
* Write a description of class Path here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class Path
{
    // instance variables - replace the example below with your own
    private double atkChance, defChance, spChance;
    private double loseTurnChance = .05;
    private int numSpaces = 30;
    private String pathName;
    private String[] valuesOfSpaces;
    private Random rand;
    

    /**
     * Constructor for objects of class Path
     */
    public Path(double atkChance, double defChance, double spChance, String pathName)
    {
        this.atkChance = atkChance;
        this.defChance = defChance;
        this.spChance = spChance;
        this.pathName = pathName;
        generateSpaceValues();
        rand = new Random();
    }
    
    public double getAtkChance()
    {
        return atkChance;
    }
    
    public double getDefChance()
    {
        return defChance;
    }
    
    public double getSpChance()
    {
        return spChance;
    }
    
    public String getPathName()
    {
        return pathName;
    }
    
    public int getNumSpaces()
    {
        return numSpaces;
    }
    
    public void generateSpaceValues()
    {
        int tally = 0;
        double totalAtk = atkChance * 100;
        double totalDef = defChance * 100;
        double totalSp = spChance * 100;
        double totalLoseTurn = loseTurnChance * 100;
        valuesOfSpaces = new String[100];
        double defenseTally, spTally, loseTurnTally;
        
        for(int i = 0;i <totalAtk;i++)
        {
            valuesOfSpaces[i] = "Attack";
            tally += 1;
        }
        //tally += 1;
        defenseTally = tally + totalDef;
        for (int i = tally;i<(int)defenseTally;i++)
        {
            valuesOfSpaces[i] = "Defense";
            tally += 1;
        }
        //tally += 1;
        spTally = tally + totalSp;
        for (int i = tally;i<(int)spTally;i++)
        {
            valuesOfSpaces[i] = "Special Ability";
            tally += 1;
        }
        //tally += 1;
        loseTurnTally = tally + totalLoseTurn;
        for (int i = tally;i<(int)loseTurnTally;i++)
        {
            valuesOfSpaces[i] = "Lose Turn";
            tally += 1;
        }
        
    }
    
    public String spaceValue()
    {
        int value = rand.nextInt(100);
        return valuesOfSpaces[value];
    }

SpecialCard
Code:
import java.util.ArrayList;
import java.util.Random;
/**
* Write a description of class SpecialCard here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class SpecialCard
{
    // instance variables - replace the example below with your own
    private ArrayList<Integer> cards;
    private ArrayList<String> cardDesc;
    private ArrayList<String> cardType;
    private Random rand;
    private int pickedCard;
    private String pickDesc;
    private String pickType;
    private int cardRemove;
    private int totalCards = 25;

    /**
     * Constructor for objects of class SpecialCard
     */
    public SpecialCard()
    {
        cards = new ArrayList<Integer>();
        cardDesc = new ArrayList<String>();
        cardType = new ArrayList<String>();
        rand = new Random();
        createCards();
    }
    
    private void createCards()
    {
        for(int i = 0; i < 25; i++)
        {
            cards.add(i);
        }
        
        cardDesc.add("+1 Attack for next turn");
        cardDesc.add("+1 Attack for next turn");
        cardDesc.add("+2 Attack for next turn");
        cardDesc.add("+2 Attack for next turn");
        cardDesc.add("+3 Attack for next turn");
        cardDesc.add("+3 Attack for next turn");
        cardDesc.add("+4 Attack for next turn");
        cardDesc.add("+5 Attack for next turn");
        cardDesc.add("Regain 5 Health");
        cardDesc.add("Regain 5 Health");
        cardDesc.add("Regain 10 Health");
        cardDesc.add("Regain 10 Health");
        cardDesc.add("Regain 15 Health");
        cardDesc.add("Parry. Player rolls against opponent attack. \nIf the player rolls higher, the oponent takes damage \ninstead equal to the player's roll");
        cardDesc.add("Parry. Player rolls against opponent attack. \nIf the player rolls higher, the oponent takes damage \ninstead equal to the player's roll");
        cardDesc.add("Block. Opponent's next attack does no damage");
        cardDesc.add("Block. Opponent's next attack does no damage");
        cardDesc.add("Steal. Take an Attack bonus from the opponent \nand add it to your own Attack");
        cardDesc.add("Steal. Take a Health bonus from the opponent \nand add it to your own Health");
        cardDesc.add("Leech. You and the opponent swap all remaining health");
        cardDesc.add("Leech. You take 15 health from the opponent \nand add it to your own");
        cardDesc.add("Speed. Attack 2 times in one turn");
        cardDesc.add("Speed. The oponent's attack only does half damage");
        cardDesc.add("Reflect. When the opponent attacks you, they \nalso recieve damage equal to half of their attack");
        cardDesc.add("Revive. Play this card when you are killed to \ncome back to life with 15 Health");
        
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
    }
    
    public void chooseCard()
    {
        int card = rand.nextInt(totalCards);
        pickedCard = cards.get(card);
        pickDesc = cardDesc.get(card);
        pickType = cardType.get(card);
        cardRemove = card;
    }
    
    public int getCard()
    {
        return pickedCard;
    }
    
    public String getCardDesc()
    {
        return pickDesc;
    }
    
    public String getCardType()
    {
        return pickType;
    }
    
    public void removePick()
    {
        cards.remove(cardRemove);
        totalCards -= 1;
    }


Thank you for any help you might be able to give. If you need more info, let me know.
 

Cromewell

Administrator
Staff member
This probably isn't all of the problem but you are using Character with a constructor of taking int, int, string. But Character is a class wrapper for the char primitive.

I can't even build your project to try and see what's going on without your Character class.
 

Troncoso

VIP Member
Oh, haha. I forgot to add that. But I figured out the problem. I do have another issue though.

I'm copying information from a text file to an array of objects of Cards.
Some of the records have a new line character (\n) in the text file itself, but not all of them.
When I try to print the elements of the array, it prints the new line characters instead of going to the next line. So...

The Cards class, that just outlines the attributes of the objects:

Code:
/********************************************
 * Outlines the fields of a card as well as *
 * defining methods to retrieve the fields. *
 ********************************************/
public class Cards
{
    private int cardNum;
    private String cardName;
    private String cardDesc;
    private String cardType;

    public Cards(int cardNum, String cardName, String cardDesc, String cardType){
        this.cardNum = cardNum;
        this.cardName = cardName;
        this.cardDesc = cardDesc;
        this.cardType = cardType;
    }
    
    public int getCardNum(){
        return cardNum;
    }
    
    public String getCardName(){
        return cardName;
    }
    
    public String getCardDesc(){
        return cardDesc;
    }
    
    public String getCardType(){
        return cardType;
    }
}

This is CardDecks that creates the array of Cards and reads off "cards.txt" to initialize the objects:

Code:
import java.io.*;
import java.util.*;

/**************************************************************
 * Creates an array with all 25 of the special ability cards. *
 **************************************************************/
public class CardDecks
{
    private Cards[] deck;
    private File retrieveCards;
    private Scanner readFile, pressEnter;
    private Random rand;
    private int pickedCard, totalCards = 25;

    /******************************************************************
     * Open the "cards.txt" file, create the deck, and close the file *
     ******************************************************************/
    public CardDecks(){
        deck = new Cards[25];
        retrieveCards = new File("cards.txt");
        pressEnter = new Scanner(System.in);
        rand = new Random();
        openCardsFile();
        generateDeck();
        closeCardsFile();
    }
    
    /*******************************
     * Open the file, if it exists *
     *******************************/
    private void openCardsFile(){
        try{
            readFile = new Scanner(retrieveCards);
        }
        catch(Exception e){
            System.out.println("cards.txt file not found");
            pressEnter.nextLine();
            System.exit(0);
        }
    }
    
    /******************
     * Close the file *
     ******************/
    private void closeCardsFile(){
        readFile.close();
    }
        
    /************************************************************************
     * Uses the file to create each Card object with the appropriate fields *
     ************************************************************************/
    private void generateDeck(){
            for (int i = 0; i < deck.length; i++){
                deck[i] = new Cards(Integer.parseInt(readFile.nextLine()), readFile.nextLine(), readFile.nextLine(), readFile.nextLine());
            }  
    }
    
    /************************************************
     * Chooses a random card and returns it's index *
     ************************************************/
    public int randomCard(){
        pickedCard = rand.nextInt(26) - 1;
        return pickedCard;
    }
    
    /***************************************************************************
     * Get methods to return information about a card in the deck at index num *
     ***************************************************************************/
    public int getCardNum(int num){
        return deck[num].getCardNum();
    }
    
    public String getCardName(int num){
        return deck[num].getCardName();
    }
    
    public String getCardDesc(int num){
        return deck[num].getCardDesc();
    }
    
    public String getCardType(int num){
        return deck[num].getCardType();
    }
}

And this is the actual text file "cards.txt":

Code:
1
+1 Attack
+1 Attack for next turn
Before Attack
2
+1 Attack
+1 Attack for next turn
Before Attack
3
+2 Attack
+2 Attack for next turn
Before Attack
4
+2 Attack
+2 Attack for next turn
Before Attack
5
+3 Attack
+3 Attack for next turn
Before Attack
6
+3 Attack
+3 Attack for next turn
Before Attack
7
+4 Attack
+4 Attack for next turn
Before Attack
8
+5 Attack
+5 Attack for next turn
Before Attack
9
+5 Health
Regain 5 Health
Before Attack
10
+5 Health
Regain 5 Health
Before Attack
11
+10 Health
Regain 10 Health
Before Attack
12
+10 Health
Regain 10 Health
Before Attack
13
+15 Health
Regain 15 Health
Before Attack
14
Parry
Player rolls against opponent attack.\nIf the player rolls higher, the oponent takes damage \ninstead equal to the player's roll
After Oponent Attack
15
Parry
Player rolls against opponent attack.\nIf the player rolls higher, the oponent takes damage \ninstead equal to the player's roll
After Oponent Attack
16
Block
Opponent's next attack does no damage
After Oponent Attack
17
Block
Opponent's next attack does no damage
After Oponent Attack
18
Steal Attack
Take an Attack bonus from the opponent\nand add it to your own Attack
Before Attack
19
Steal Health
Take a Health bonus from the opponent\nand add it to your own Health
Before Attack
20
Swap Health
You and the opponent swap all remaining health
Before Attack
21
Leech Health
You take 15 health from the opponent\nand add it to your own
Before Attack
22
Double Attack
Attack 2 times in one turn
Before Attack
23
Dodge
The oponent's attack only does half damage
After Oponent Attack
24
Reflect Attack
When the opponent attacks you, they\nalso recieve damage equal to half of their attack
After Oponent Attack
25
Revive
Play this card when you are killed to\ncome back to life with 15 Health
After Oponent Attack

And finally! the method I'm trying to use in MainGame to print the card info:

Code:
public void drawSpecialCard(CardDecks deck)
    {
        int chosenCard = deck.randomCard();
        System.out.println("Player draws a special ability card:\n");
        System.out.println(" ------------------------------------------------------");
        System.out.println("|\t" + deck.getCardName(chosenCard));
        System.out.println("|\t" + deck.getCardDesc(chosenCard));
        System.out.println("|\tType: " + deck.getCardType(chosenCard));
        System.out.println(" ------------------------------------------------------\n");
    }

The problem is, when a record off the file is written to an object that has the "\n", it doesn't print properly.

So instead of going from:

Code:
line1
line2
line3. \nAnother line

to

Code:
line1
line2
line3.
Another line

it prints

Code:
line1
line2
line3. \nAnother line
 

NyxCharon

Active Member
Care to say a bit more?

Yup, I'll give you a full example when I'm off work. I had a similar issue when i was writing a notepad like program, and using a buffered reader over a scanner worked to fix my problem. I'd write one out now, but I can't remember the exact code :p

Edit: You are saying that it IS printing the "/n" character correct?
 
Top