I'm generally new to programming and just started programming in Java a few days ago so I'm not sure if what I'm trying to accomplish is even possible with the way my program is coded.
I'm basically writing a program that asks for a "Strength" value between 0 and 9. It asks you to choose a weapon ((1) Knife is the only one available). It takes that information and generates a random damage ratio between 1-3 plus what ever number your strength is and is supposed to keep subtracting that value from 20 until it hit 0 then quits.
The problem is that I'm stuck in a loop. It subtracts the value from 20, but starts over and keeps subtracting from 20 again rather than storing the subtracted number.
Does anyone have any advice on how something like this would be accomplished? Any help is very much appreciated. This is my code so far....
package untitledgame;
import java.util.Random;
import java.util.Scanner;
public class UntitledGame {
public static void main(String[] args){
int pStrength, wKnife, damage, enemyDamage;
Scanner in = new Scanner(System.in); //used for next to int inputs
System.out.println("Choose Your Strength (0-9)");
pStrength = in.nextInt();
System.out.println("Your Strength Is "+pStrength);
System.out.println("Choose Your Weapon; (1)Knife");
wKnife = in.nextInt();
System.out.println("Press ENTER to battle...");
Scanner scanner = new Scanner(System.in); //waits for users to continue
scanner.nextLine();
if (wKnife == 1){
do {
int enemyHP = 20;
Random rn = new Random(); //Random generator
wKnife = rn.nextInt(3) + 1; //Randomly generates knife damage
damage = wKnife + pStrength; //Damage logic
System.out.println("Attack with knife has done: " ); //Knife damage
System.out.print(+damage);
System.out.print(" damage." );
System.out.println("");
enemyDamage = enemyHP - damage; // Remaing HP
System.out.println("Enemy has ");
System.out.print(+enemyDamage);
System.out.print(" HP left.");
System.out.println("");
System.out.println("Press Enter to Attack...");
scanner.nextLine();
}
while (enemyDamage > 0);
System.out.println("Enemy has been defeated.");
}
}
}
Declare this int enemyHP = 20; outside the do-while loop. Right now, you're resetting enemyHP to 20 every single time you iterate through the loop.
Also, you should not recreate your Random within the do-while loop. Do that before entering the do block.
There are other issues with the logic that Jonah Haney deals with in his answer.
You'll want to initialize your enemyHP variable OUTSIDE of the do-while loop, or it will reset enemyHP back to 20 every time it loops.
Declare int enemyHP = 20 before the beginning of the loop. Then your loop is missing the following line:
enemyHP = enemyHP - damage;
Also, it seems that you want the loop to keep running until the enemy has been defeated. If that is the case, then your condition should check to see if enemyHP has been drained all the way, like this:
}
while (enemyHP > 0); //instead of while (enemyDamage > 0);
EDIT
This is what your code SHOULD look like. I am not saying you should copy it straight into your project. I am saying that you should take a look at the differences and it will help you see the logic problems in your own code:
public static void main(String[] args){
int pStrength, wKnife, damage, enemyDamage;
Scanner in = new Scanner(System.in); //used for next to int inputs
System.out.println("Choose Your Strength (0-9)");
pStrength = in.nextInt();
System.out.println("Your Strength Is " + pStrength);
System.out.println("Choose Your Weapon; (1)Knife");
wKnife = in.nextInt();
System.out.println("Press ENTER to battle...");
in.nextLine();
in.nextLine();
Random rn = new Random(); //Random generator
int enemyHP = 20;
if (wKnife == 1){
do {
System.out.println("Press Enter to Attack...");
in.nextLine();
wKnife = rn.nextInt(3) + 1; //Randomly generates knife damage
damage = wKnife + pStrength; //Damage logic
System.out.println("Attack with knife has done: " + damage + " damage."); //Knife damage
enemyHP -= damage; // Calculate Remaining HP
System.out.println("Enemy has " + enemyHP + " HP left.");
} while (enemyHP > 0);
System.out.println("Enemy has been defeated.");
in.close();
}
}
Related
I am a beginner coder using Netbeans Java. I have created a code that initially asks how many gallons are in your gas tank. Then, it will have a while loop asking how many miles you will be traveling for this first run and how fast are you traveling. This will repeat with a while loop until you input '0' to stop adding trips. I am stumped on how to convert this while loop into only using For loops. I would greatly appreciate the assistance. Here is my code that has while loops.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tank;
double miles;
double speed;
double totalMiles = 0.0;
int choice;
double time;
double totalTime = 0.0;
double fuelConsumption;
System.out.print("How many gallons of gas is in your tank (Integer 1-15)? ");
tank = input.nextInt();
System.out.printf("%s%d%s\n\n" , "You have ", tank , " gallons of gas in your tank.");
System.out.print("Are you going on a trip (1 = Yes or 0 = No)? ");
choice = input.nextInt();
while (choice == 1)
{
System.out.print("How many miles are you traveling? "); // miles
miles = input.nextFloat();
System.out.print("What is your speed for this run (MPH)? "); // speed
speed = input.nextInt();
System.out.print("\n");
totalMiles = totalMiles + miles;
time = (miles/speed);
totalTime += (time*60);
fuelConsumption = (20*(tank/totalMiles));
System.out.print("Is there another leg in your trip (1 = Yes or 0 = No)? "); // asking another leg
choice = input.nextInt();
if (choice == 0)
{
System.out.printf("%s%5.2f%s\n","Your data for this trip is: \n"
+ "You traveled a total of about ", totalMiles , " miles.");
System.out.printf("%s%.2f%s\n" , "You traveled about " , totalTime , " minutes.");
if (fuelConsumption >= 2)
{
System.out.println("Your car has enough gas to return.");
break;
}
else
{
System.out.println("Your car will need more gas to return.");
break;
}
}
}
}
}
That is not a use case for a for loop, where we iterate over a known number of elements for do a known number of iterations. Like, repeat 10 times or such.
Technically it can be solved with a for loop, but that is abusing the concept a bit. The while loop is a perfect fit for that task.
This is not a place to use a for-loop, you use a for loop for something like this:
printAmount = 10;
for (int i = 0; i < printAmount; i++) {
System.out.println("Hello World");
}
Here you are using the for loop to print "Hi" for the amount in printAmount.
Your case is different: You want the while-loop to repeat while the input is "1" so you use a WHILE-loop.
I am somewhat new to Java still and have a lab that needs to simulate a lottery game that generates a number between 1-10. It first asks the user how many tickets do they want to purchase and then asks them if they want the computer to generate the guesses for them, if yes then it will generate the guesses and reveal the winning numbers. If the user says no, then the user will input the guesses themselves and will show the winning numbers.
I am having a problem figuring out how to do the code for when someone enters yes or no. Should I do a do while loop?
Here is what I have as code right now.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double TICKET_PRICE = 2.00;
System.out.println("Welcome to the State of Florida Play10 Lottery Game. Ticket Price: $" + TICKET_PRICE);
System.out.println("How many tickets would you like to purchase?");
int ticketsPurchased = input.nextInt();
System.out.print("Please enter " + (ticketsPurchased) + " to confirm your credit carde charge: ");
int creditCardCharge = input.nextInt();
if (ticketsPurchased != creditCardCharge) {
System.out.println("Wrong number, please enter again: ");
return;
}
if (ticketsPurchased == creditCardCharge) {
System.out.println("Thank you. Your credit card will be charged $" + (ticketsPurchased * 2));
}
int min = 1;
int max = 10;
int winner;
winner = min + (int)(Math.random() * ((max - min) + 1));
System.out.print("Would you like the computer to generate your guesses? Enter 'Y' or 'N': ");
String computerGeneratedGuess = input.nextLine();
int guess = 0;
int winCtr = 0;
String output = "";
}
Here is the algorithm:
1. Get number of tickets to purchase,
calculate and confirm credit card charge.
2. Generate random winning integer and
either generate random guesses or prompt
user for guesses.
3. Report the winning number, the winning
tickets, total winnings, total losses, and
allowable deduction
Here is the lab its self:
Lab05 Lottery game
Generally a boolean is convenient to control a loop like this. Something like:
boolean gameOver = false;
int theGuess = 0;
while (!gameOver) {
if (computerGeneratedGuess == 'Y') {
theGuess = //code to generate a random number
}
else {
theGuess = //code to for user to enter a guess
}
if (theGuess == winner) {
gameOver = true;
}
I am working on this project from the Java Programming book by Joyce Farrell, and I am having an issue with the Randomly Generated number and the user's guesses not being checked correctly. For example the user has 3 guesses, lets say their first guess it 2 and the first randomly generated number is 2 the program will print out You lose. When the guess is actually correct. Please help me. I have added the details of the program plus what I have done so far.
Create a lottery game application. Generate three random numbers (see Appendix D for help in
doing so), each between 0 and 9. Allow the user to guess three numbers. Compare each of the
user's guesses to the three random numbers and display a message that includes the user's
guess, the randomly determined three-digit number, and the amount of money the user has
won as follows.
Matching Numbers Award($)
Any one matching 10
Two matching 100
Three matching, not in order 1000
Three matching, in exact order 1,000,000
No match 0
Make certain that your application accommodates repeating digits. For example, if a user
guesses 1, 2, and 3, and the randomly generated digits are 1, 1, and 1, do not give the user
credit for three correct guesses - just one. Save the file as Lottery.
My Source Code
// Filename: Lottery.java
// Written by: Andy A
// Written on: 14 January 2015
import java.util.Scanner;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
Random ranNum = new Random();
// LIMIT Contains The Numbers From 0 - 9
// TIMES Contains The Number of Time ranNum Should Run
final int LIMIT = 9;
final int TIMES = 3;
// Users Guesses
int usersFirstGuess;
int usersSecondGuess;
int usersThirdGuess;
// Randomly Generated Numbers
final int GenFirst = ranNum.nextInt(LIMIT);
final int GenSecond = ranNum.nextInt(LIMIT);
final int GenThird = ranNum.nextInt(LIMIT);
// User is asked for 3 guesses
System.out.println("Please enter your first guess: ");
usersFirstGuess = userInput.nextInt();
System.out.println("Please enter your second guess: ");
usersSecondGuess = userInput.nextInt();
System.out.println("Please enter your third and final guess: ");
usersThirdGuess = userInput.nextInt();
// Winning Amounts
final double WinTen = 10;
final double WinHun = 100;
final double WinThund = 1000;
final double WinMillion = 1000000;
final int WinZero = 0;
// Shows the randomly generated numbers
for(int x = 0; x < TIMES; ++x)
System.out.print(ranNum.nextInt(LIMIT) + " ");
System.out.println();
// First Generated
if(GenFirst == usersFirstGuess ) {
System.out.println("You have won: $" + WinTen);
}
else if(GenSecond == usersSecondGuess) {
System.out.println("You have won: $" + WinTen);
}
else if(GenThird == usersThirdGuess) {
System.out.println("You have won: $" + WinTen);
}
}
}
You are printing newly generated numbers with ranNum.nextInt(LIMIT), however you are comparing the user input with the numbers stored in the GenXXX variables.
Solution: Print the variables instead.
System.out.println(GenFirst + " " + GenSecond + " " + GenThird);
If you still want to use a loop for printing you can store the numbers in an array.
// generate
final int[] generated = new int[TIMES];
for (int x = 0; x < TIMES; x++)
generated[x] = ranNum.nextInt(LIMIT);
// print
for (int x = 0; x < TIMES; x++)
System.out.print(generated[x] + " ");
This should do the trick.
// Filename: Lottery.java
// Written by: Andy A
// Written on: 14 January 2015
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
Random ranNum = new Random();
// LIMIT Contains The Numbers From 0 - 9
// TIMES Contains The Number of Time ranNum Should Run
final int LIMIT = 9;
final int TIMES = 3;
// Users Guesses
int usersFirstGuess;
int usersSecondGuess;
int usersThirdGuess;
List<Integer> guesses = new ArrayList<>();
// Randomly Generated Numbers
final int GenFirst = ranNum.nextInt(LIMIT);
final int GenSecond = ranNum.nextInt(LIMIT);
final int GenThird = ranNum.nextInt(LIMIT);
// User is asked for 3 guesses
System.out.println("Please enter your first guess: ");
usersFirstGuess = userInput.nextInt();
guesses.add(usersFirstGuess);
System.out.println("Please enter your second guess: ");
usersSecondGuess = userInput.nextInt();
guesses.add(usersSecondGuess);
System.out.println("Please enter your third and final guess: ");
usersThirdGuess = userInput.nextInt();
guesses.add(usersThirdGuess);
// Winning Amounts
final double WinTen = 10;
final double WinHun = 100;
final double WinThund = 1000;
final double WinMillion = 1000000;
final int WinZero = 0;
// Shows the randomly generated numbers
System.out.println(GenFirst + " " + GenSecond + " " + GenThird);
List<Integer> lottery = new ArrayList<>();
lottery.add(GenFirst);
lottery.add(GenSecond);
lottery.add(GenThird);
if (guesses.equals(lottery)) {
System.out.println("You have won: $" + WinMillion);
} else {
int matchCount = 0;
for (Integer guessValue : guesses) {
if (lottery.contains(guessValue)) {
matchCount++;
lottery.remove(guessValue);
}
}
switch (matchCount) {
case 0:
System.out.println("You have won: $" + WinZero);
break;
case 1:
System.out.println("You have won: $" + WinTen);
break;
case 2:
System.out.println("You have won: $" + WinHun);
break;
case 3:
System.out.println("You have won: $" + WinThund);
break;
}
}
}
}
Exactly,
why are you printing
System.out.print(ranNum.nextInt(LIMIT) + " ");
when you should be just printing
System.out.print(GenThird + " ");
System.out.print(GenSecond + " ");
System.out.print(GenFirst + " ");
This is not the problem of the randomly generated numbers, but if your way of showing them to the user.
Before your if / else if statements, in the for-loop you are generating new random numbers. That means, the number compared to the users input (genFirst) can be 3, but the number shown to the user in the for loop is a new random number, for example 2.
To fix this problem, you should display the generated numbers like that:
for (int ranInt : new int[] { GenFirst, GenSecond, GenThird}) {
System.out.println(ranInt);
}
This piece of code creates an array of the generated numbers and loops through them printing them. Obviously, you can also print GenFirst, then print GenSecond and then print GenThird.
I hope this helps!
Maybe this will help!
import java.util.Scanner;
import java.util.Random;
public class Qellonumrat {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Random rand=new Random();
int random_integer=(int) rand.nextInt(10);
System.out.println("Guess the number: ");
int number=sc.nextInt();
while(true){
if(number == random_integer){
random_integer++;
System.out.println("Congrats you won!!!");
break;
}
else{
System.out.println("Try again");
break;
}
}
}
}
I am supposed to write a program that selects a random number between user given constraints, and asks the user to input guesses as to what this number is. The program gives feedback to the user as to whether or not the number is higher or lower than the user's guesses. The number of guesses, the number of games, the total guesses used throughout all of the games, and the lowest number of guesses used in one game are recorded.
These results are printed. The functions that responsible for running the game (playGame()) and the functions responsible for printing these results (getGameResults()) must be in two separate methods.
My problem is, I am not sure how to get the local variables that are modified throughout the course of the method playGame() to the getGameResults() method.
getGameResults() is intended to be called in another method, continuePlayTest(), which tests the user's input to determine whether or not they wish to continue playing the game, so I don't think that calling getGameResults() will work, otherwise this test will not work either. Unless I call continuePlayTest() in playGame(), but continuePlayTest() calls playGame() in its code so that would complicate things.
We can use ONLY the concepts that we've learned. We cannot use any concepts ahead.
So far, we've learned how to use static methods, for loops, while loops, if/else statements and variables. Global variables are bad style, so they cannot be used.
CODE:
public class Guess {
public static int MAXIMUM = 100;
public static void main(String[] args) {
boolean whileTest = false;
gameIntroduction();
Scanner console = new Scanner(System.in);
playGame(console);
}
// Prints the instructions for the game.
public static void gameIntroduction() {
System.out.println("This process allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAXIMUM + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
System.out.println();
}
//Takes the user's input and compares it to a randomly selected number.
public static void playGame(Scanner console) {
int guesses = 0;
boolean playTest = false;
boolean gameTest = false;
int lastGameGuesses = guesses;
int numberGuess = 0;
int totalGuesses = 0;
int bestGame = 0;
int games = 0;
guesses = 0;
games++;
System.out.println("I'm thinking of a number between 1 and " + MAXIMUM + "...");
Random number = new Random();
int randomNumber = number.nextInt(MAXIMUM) + 1;
while (!(gameTest)){
System.out.print("Your guess? ");
numberGuess = console.nextInt();
guesses++;
if (randomNumber < numberGuess){
System.out.println("It's lower.");
} else if (randomNumber > numberGuess){
System.out.println("It's higher.");
} else {
gameTest = true;
}
bestGame = guesses;
if (guesses < lastGameGuesses) {
bestGame = guesses;
}
}
System.out.println("You got it right in " + guesses + " guesses");
totalGuesses += guesses;
continueTest(playTest, console, games, totalGuesses, guesses, bestGame);
}
public static void continueTest(boolean test, Scanner console, int games, int totalGuesses, int guesses, int bestGame) {
while (!(test)){
System.out.print("Do you want to play again? ");
String inputTest = (console.next()).toUpperCase();
if (inputTest.contains("Y")){
playGame(console);
} else if (inputTest.contains("N")){
test = true;
}
}
getGameResults(games, totalGuesses, guesses, bestGame);
}
// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
System.out.println("Overall results:");
System.out.println("\ttotal games = " + games);
System.out.println("\ttotal guesses = " + totalGuesses);
System.out.println("\tguesses/games = " + ((double)Math.round(guesses/games) * 100)/100);
System.out.println("\tbest game = " + bestGame);
}
}
If you cannot use "global" variables, I guess your only option is passing parameters when calling the method. If you don't know how to declare and use methods with parameters, I don't know another answer.
EDIT/ADD
After you specified your question, circumstances and posted your code I got a working solution including comments.
public class Guess {
public static int MAXIMUM = 100;
public static void main(String[] args) {
boolean play = true; // true while we want to play, gets false when we quit
int totalGuesses = 0; // how many guesses at all
int bestGame = Integer.MAX_VALUE; // the best games gets the maximum value. so every game would be better than this
int totalGames = 0; // how many games played in total
Scanner console = new Scanner(System.in); // our scanner which we pass
gameIntroduction(); // show the instructions
while (play) { // while we want to play
int lastGame = playGame(console); // run playGame(console) which returns the guesses needed in that round
totalGames++; // We played a game, so we increase our counter
if (lastGame < bestGame) bestGame = lastGame; // if we needed less guesses last round than in our best game we have a new bestgame
totalGuesses += lastGame; // our last guesses are added to totalGuesses (totalGuesses += lastGame equals totalGuesses + totalGuesses + lastGame)
play = checkPlayNextGame(console); // play saves if we want to play another round or not, whats "calculated" and returned by checkPlayNextGame(console)
}
getGameResults(totalGames, totalGuesses, bestGame); // print our final results when we are done
}
// Prints the instructions for the game.
public static void gameIntroduction() {
System.out.println("This process allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAXIMUM + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
System.out.println();
}
// Takes the user's input and compares it to a randomly selected number.
public static int playGame(Scanner console) {
int guesses = 0; // how many guesses we needed
int guess = 0; // make it zero, so it cant be automatic correct
System.out.println("I'm thinking of a number between 1 and " + MAXIMUM + "...");
int randomNumber = (int) (Math.random() * MAXIMUM + 1); // make our random number. we don't need the Random class with its object for that task
while (guess != randomNumber) { // while the guess isnt the random number we ask for new guesses
System.out.print("Your guess? ");
guess = console.nextInt(); // read the guess
guesses++; // increase guesses
// check if the guess is lower or higher than the number
if (randomNumber < guess)
System.out.println("It's lower.");
else if (randomNumber > guess)
System.out.println("It's higher.");
}
System.out.println("You got it right in " + guesses + " guesses"); // Say how much guesses we needed
return guesses; // this round is over, we return the number of guesses needed
}
public static boolean checkPlayNextGame(Scanner console) {
// check if we want to play another round
System.out.print("Do you want to play again? ");
String input = (console.next()).toUpperCase(); // read the input
if (input.contains("Y")) return true; // if the input contains Y return true: we want play another round (hint: don't use contains. use equals("yes") for example)
else return false; // otherwise return false: we finished and dont want to play another round
}
// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int totalGames, int totalGuesses, int bestGame) {
// here you passed the total guesses twice. that isnt necessary.
System.out.println("Overall results:");
System.out.println("\ttotal games = " + totalGames);
System.out.println("\ttotal guesses = " + totalGuesses);
System.out.println("\tguesses/games = " + ((double) (totalGuesses) / (double) (totalGames))); // cast the numbers to double to get a double result. not the best way, but it works :D
System.out.println("\tbest game = " + bestGame);
}
}
Hope I could help.
Is it a problem passing the variables between functions? ex:
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
// implementation
}
Another option, assuming this is all in one class, is using private static memeber variables. They aren't global. Then again, they might be considered 'global' by your teacher for this assignment.
Given that you've only learnt how to use static methods, your only option is to pass the information from function to function via its arguments.
So I am having an issue figuring out how to create a loop and bring another class over in a dice game application I have to create for a school project. The game has to keep user score for each round 18 is the max score and if a user Rolls over 10 in 1 round his points are lost and he starts the next round at 1 point. The game also has to validate when the user enters Y to Roll or R to stop. Some help on this would be greatly appreciated. Im having problems with setting up a loop in which to continue the game after Y is entered or Tell the user the game has stopped after R is entered. So after Y is entered the loop would Print out "Round1" Roll:6 [Y or R], user entered Y, Print out "Round 2" and so on and i dont know how to validate user input.
import java.util.Scanner;
import java.util.Random;
import java.lang.Boolean;
public class Player {
public static void main(String[] args){
String player;
String playerAnswer;
Boolean answer = true;
int RoundScore;
int TotalScore;
int playerScore;
int Round;
Scanner user = new Scanner(System.in);
System.out.println("Enter your First Name to play!");
player = user.nextLine();
playerAnswer = user.nextLine();
{
System.out.println("Your Name:" + "" + player);
System.out.println("Welcome" + "" + player + "" + "To Dice Game");
System.out.println("Enter Y to Roll or R to STop:[Y or R]" + "" + playerAnswer.toUpperCase());
}
}
}
package Project4;
import java.util.Random;
import java.util.Scanner;
public class Dice{
public static void main(String[] args){
Random dice = new Random();
int number = 0;
for(int counter = 1; counter <= 1; counter++)
number = 1 + dice.nextInt(18);
System.out.println(number + "");
}
}
Something for you to note I don't think there's a (1) die can roll up to 18. The range for 3 dice should be 3 - 18 instead of 1 - 18.
number = 3 + dice.nextInt(16);
For the loop issue use do while loop, and assign a variable to get the and noticed how your playerAnswer should be under the System.out.println.
int rounds = 1;
do {
// codes that you want to loop
System.out.println("Welcome" + "" + player + "" + "To Dice Game");
System.out.println("Round " + rounds); // this will annouce the number of rounds
System.out.println("Enter Y to Roll or R to STop:[Y or R]")
playerAnswer = user.nextLine();
rounds++;
} while (playerAnswer.equalsIgnoreCase("y");
Also, I don't think you can have 2 main method here as you're creating "an" application, not 2 different application. I would suggest that you create a sub method using
public static void rollDice()
{
// codes for rolling the dice
}
and to call the rollDice method just do a
rollDice();
However, the application you're creating seems to be small and doing just the dice roll, if I am you I wouldn't even need to create a method for it.
You are probably trying to learn how to create a class. Seeing your codes, you seems like you aren't that great in Java yet. I would suggest that you re-start learning Java from the basics. I think you need to pay more attention in your school class.