So I was wondering if someone could show me how I can call/reference a variable from one method into another method. For example,
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
String p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
String p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
I want to use p1 and p2 from playerNames() inside of coinToss() so I can simply announce who goes first, but I just can't figure out how to call the variables.
My question is not really different compared to others, however I was unable to understand the answers others were given. Once I posted this I got the answer from a bunch of kind people :)
I'm assuming you are new to Java, because it seems you aren't familiar with the concept of fields (i.e. you can put variables outside methods).
public class YourClass {
static String p1;
static String p2;
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
}
what you are searching for is called instance variables, check this out.
https://www.tutorialspoint.com/java/java_variable_types.htm
All I had to do was create the instance/static variables outside! Like this:
static String name1;
static String name2;
It was very easy. Thanks everyone for your help!
Related
I am making a game and a the end of the game I want it to call the user by the name that they put in,, this is the code I have.
private static final Scanner console = new Scanner(System.in);
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation();
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation() {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt();
}
}
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
public static boolean Mascot() {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println("You, have sucsefully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}
I want for it to at the end print * user's name*, you have successfully passed the third riddle.
but it needs to be able to weather the first name was kept, or if this sequence was used.
public static void calledIt() {
System.out.println("I knew it!");
System.out.print("whats your real name? ");
String realName = console.nextLine();
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
and if it has been activated it needs to use the new name.
Change return type of calledIt() to String and return realName from this method
Change return type of confirmation() to String. Initialize a String (String name = null). In the else part, assign the value returned from calledIt() to this string (String name = calledIt()). Return name.
In main, if the value returned from confirmation() is not null, update Name with this new value.
Pass the Name as input to Mascot method. For this, you have to update the Mascot method to accept a String as input.
You can pass the variable into confirmation() and calledIt() like this
public static void main(String[] args) {// follow the prompts.//
System.out.println("Hello user! what is your name? ");
String Name = console.nextLine();
System.out.println("Really? " + Name + " is too weird to be a real name.");
confirmation(Name);
Mascot();
System.out.println("Thank you for playing the demo");
console.close();
}
public static void confirmation(String name) {
System.out.print("is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
} else {
calledIt(name);
}
}
public static void calledIt(String realName){
System.out.println("I knew it!");
System.out.print("whats your real name? ");
System.out.println(
"" + realName + " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
You could do the following change:
public static void main(String[] args) { // follow the prompts.//
System.out.println("Hello user! What is your name? ");
String name = console.nextLine();
System.out.println("Really? " + name + " is too weird to be a real name.");
System.out.print("Is that REALLY your name? (type Y/N) ");
String yN = console.nextLine();
String a = yN;
if (a.toLowerCase().contains("y")) {
System.out.println("I still don't believe you, so you will have to answer 3 riddles before you can continue to the game");
} else {
System.out.println("I knew it!");
System.out.print("Whats your real name? ");
name = console.nextLine();
System.out.println(
"" + name + " sounds like a real one, but you lied the first time so you will need to answer riddles 3 to continue to the game");
}
mascot(name);
System.out.println("Thank you for playing the demo");
console.close();
}
public static boolean mascot(String name) {
System.out.println("what Is our school mascot?");
String b = console.nextLine();
if (b.toLowerCase().contains("tiger")) {
System.out.println("Good, next riddle.");
System.out.println("What runs around the whole yard without moving?");
String c = console.nextLine();
if (c.toLowerCase().contains("fence")) {
System.out.println("Good, next riddle.");
System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
String d = console.nextLine();
if (d.toLowerCase().contains("man")) {
System.out.println(name + ", you have successfully passed the third riddle");
return true;
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
} else {
System.out.println("You have failed");
return false;
}
}
The programme should repeatedly ask the user which and how many of a bird he/she has seen until they say end, it should store the most numerous bird seen then output which bird was seen the most.
When run, the program asks the questions, then when end is typed the output is always "You saw 'x' ; It was the most common bird seen at one time in your garden." The output does not display which bird was most popular-why?
import java.util.Scanner;
class birds {
public static void main(String[] args) {
questions();
}// end main method
public static void questions() {
int largest = 0;
String popularBird = "";
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("Which bird have you seen?");
String answerBird = scanner.nextLine();
if (answerBird.equalsIgnoreCase("end")) {
System.out.println("You saw " + largest + " " + popularBird);
System.out.println("It was the most common bird seen at one time in your garden.");
break;
}//end if statement
System.out.println("How many were in your graden at once?");
int answerNumber = scanner.nextInt();
if(largest < answerNumber) {
largest = answerNumber;
answerBird = popularBird;
}
}//end while loop
return;
}// end method questions
}// end class bird
You should declare the scanner, largest and popularBird variables outside the while loop as in your current code, they are getting overwritten/replaced in each iteration.
You can refer the below code with inline comments:
//declare the variables outside the loop
int largest = 0;
String popularBird = "";
Scanner scanner = new Scanner(System.in);//use the same scanner
try{
while (true) {
System.out.println("Which bird have you seen?");
String answerBird = scanner.nextLine();
if (answerBird.equalsIgnoreCase("end")) {
System.out.println("You saw " + largest + " " + popularBird);
System.out.println("It was the most
common bird seen at one time in your garden.");
break;
}//end if statement
System.out.println("How many were in your graden at once?");
int answerNumber = Integer.parseInt(scanner.nextLine());
if(largest < answerNumber) {
largest = answerNumber;
popularBird = answerBird;
}
}
} finally {
if(scanner != null)
scanner.close();//close the scanner
}
}
For my school I need to create a method which moves a bug in any direction. I have the following code:
package Test;
//imports
import java.util.Scanner;
import java.util.Random;
public class test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ABug[] BugObj = new ABug[4]; //Creating object BugObj of class ABug
int loop = 1;
int i = 0;
do {
BugObj[i] = new ABug(); //creating instance
System.out.println("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Please enter the horizontal position of the bug:");
BugObj[i].horpos = reader.nextInt();
System.out.println("Please enter the vertical postion of the bug:");
BugObj[i].vertpos = reader.nextInt();
System.out.println("_______________ Bug " +(+i+1) + " _______________\n" );
System.out.println("Name: " + BugObj[i].name); //Printing bug information out
System.out.println("Species: " + BugObj[i].species);
System.out.println("Horizontal Position: " + BugObj[i].horpos);
System.out.println("Vertical Postion: " + BugObj[i].vertpos + "\n\n");
move();
i++;
System.out.println("Would you like to enter another bug? \n 0-No, 1-Yes\n");
loop = reader.nextInt();
} while(loop == 1);
}
public static void move() {
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0) {
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
System.out.println(r);
}
}
class ABug { //ABug class
int horpos, vertpos, energy, id;
char symbol;
String species, name;
}
Basically all I need to do is use the values of the bugs position with the random number generated in the method. I am really new to java and am unsure how to do it or even if its possible.
Since objects are passed by reference in java, you can just pass your ABug object to the move function and change the horpos, vertpos attributes. so
move(BugObj[i]);
and
public static void move(ABug bug){
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0)
{
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
int originalHorpos = bug.horpos
int originalVertpos = bug.vertpos
// Now just change the attributes however you see fit. i am just adding r
bug.horpos = originalHorpos + r;
bug.vertpos = originalVertpos + r
/*by the way, we dont need to use variables for the original values. something like this would also work
bug.horpos += r;
bug.vertpos += r;
i just want to explain that in java when you pass objects, they are passed by reference and hence you have access to all of its members.
*/
System.out.println(r);
}
also, you dont need to declare the Scanner object again inside the move function. you can pass that to the move function as well and then read as many times as you like.
So I decided to skirt around the card generator, thanks to another poster on a previous question. I have had a lot of good ideas from the community and I'm trying not to copy paste, and keep the work as genuine as possible.
Which is why some problems aren't fixed yet, and others have popped up.
That said, when I run this version, the totals don't add up properly, I think on the second hit it goes a bit haywire. So I would love a little more encouragement :)
import java.util.Random;
import java.util.Scanner;
class blackj
{
public static void main(String[] args)
{
Random r = new Random();
Scanner keyboard = new Scanner(System.in);
String name;
boolean playing = true;
boolean notPlaying = true;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int dcard1 = 1 + r.nextInt(11);
int dcard2 = 1 + r.nextInt(11);
int ptotal = card1 +card2;
int dtotal = dcard1 +dcard2;
{
System.out.println("Welcome to Blackjack ! " );
System.out.println("Score as close to 21 without going over to win ");
System.out.println("What is your name?");
name = keyboard.nextLine();
System.out.println("Hello " + name);
System.out.println("Let's play some BlackJack!");
System.out.println("The dealer shows: \n\t\t" +dcard1 );
System.out.println("Your first card is: \n\t\t " +card1 );
System.out.println("Your second card is: \n\t\t" +card2 );
System.out.println("Giving you a grand total of: " +ptotal );
while (playing)
{
System.out.println("Would you like to (H)it or (S)tick?");
Scanner hit1 = new Scanner(System.in);
String a = hit1.nextLine();
if(a.equals("h"))
{
int newCard = 1 + r.nextInt(11);
System.out.println("Your next card is " +newCard );
int pcurrent = ptotal +newCard;
System.out.println("Giving you a new total of "+pcurrent);
if ((pcurrent >=22))
{
System.out.println("You Busted! \nSorry! you lose");
playing = false;
}
playing = true;
if(a.equals("s"))
{
System.out.println("You stick at " +pcurrent );
System.out.println("Now it's the dealers turn\n Dealer must draw until 17");
}
}
else
{
System.out.println("Please press H or S");
}
}
}
}
}
I modified your code a bit and now it works.
import java.util.Random;
import java.util.Scanner;
class Blackjack
{
public static void main(String[] args)
{
Random r = new Random();
String name;
Scanner scannerIn = new Scanner(System.in);
boolean playing = true;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int dcard1 = 1 + r.nextInt(11);
int dcard2 = 1 + r.nextInt(11);
int ptotal = card1 +card2;
int dtotal = dcard1 +dcard2;
System.out.println("Welcome to Blackjack ! " );
System.out.println("Score as close to 21 without going over to win ");
System.out.println("What is your name?");
name = scannerIn.nextLine();
System.out.println("Hello " + name);
System.out.println("Let's play some BlackJack!");
System.out.println("The dealer shows: \n\t\t" +dcard1 );
System.out.println("Your first card is: \n\t\t " +card1 );
System.out.println("Your second card is: \n\t\t" +card2 );
System.out.println("Giving you a grand total of: " +ptotal );
while (playing)
{
System.out.println("Would you like to (H)it or (S)tick?");
String a = scannerIn.nextLine();
if(a.toLowerCase().equals("h"))
{
int newCard = 1 + r.nextInt(11);
System.out.println("Your next card is " +newCard );
ptotal = ptotal +newCard;
System.out.println("Giving you a new total of "+ptotal);
if ((ptotal >=22))
{
System.out.println("You Busted! \nSorry! you lose");
playing = false;
}
}else if(a.toLowerCase().equals("s"))
{
System.out.println("You stick at " +ptotal );
System.out.println("Now it's the dealers turn\n Dealer must draw until 17");
}
else
{
System.out.println("Please press H or S");
}
}
scannerIn.close();
}
}
I made the following changes:
Using only one variable for ptotal, which sums up.
Removing one block { ... }, which had no meaning
Capitalize the class name. (Because it's a java convetion)
Ensure that only one scanner is opened and closed within your program.
Moving the if which checks for the 's' letter, so that it is reachable.
Modifiying your if-else structure to avoid unnecessary checks
Removing the unused variable notPlaying
Ensuring that both capitalized and lower-case inputs are accepted.
So I'm doing a TUI and this was my first iteration.
package bulb.classes;
import java.util.Scanner;
import java.util.ArrayList;
public class RoomTUI {
private ArrayList<Room> rooms;
Scanner scan = new Scanner (System.in);
private int userNumber;
private String userAnswer;
public void run() {
rooms = new ArrayList<Room>();
introduction();
userNumber = 0;
options();
while(userNumber < 5) {
if(userNumber == 1) {
newRoom();
}
if(userNumber == 2) {
addBulbToRoom();
}
if(userNumber == 3) {
clickAllBulbsInRoom();
}
if(userNumber == 4) {
printDescriptionOfBulbs();
}
}
System.out.println("Goodbye");
}
public int getUserInt(String aString) {
System.out.println(aString);
userAnswer = scan.nextLine();
userNumber = Integer.parseInt(userAnswer);
return userNumber;
}
public void displayRooms() {
System.out.println("Possible rooms to choose from.");
String tempString = "";
int roomIndex = 0;
for (int i = 0; i < rooms.size(); i++) {
tempString = tempString + "Room " + roomIndex++ + ": " + rooms.get(i).getDescription() + "\n";
}
System.out.println(tempString);
}
public void introduction() {
System.out.println("Welcome! With this program you can make rooms and design and place the light bulbs for each room you create.");
}
public void options() {
System.out.println("1 : Create a new Room");
System.out.println("2 : Add a bulb to an existing room");
System.out.println("3 : Click all of the bulbs in a particular room");
System.out.println("4 : Display a description of all bulbs in a particular room");
System.out.println("5 : Quit");
getUserInt("What would you like to do?");
}
public void newRoom() {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
rooms.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
public void addBulbToRoom() {
displayRooms();
System.out.println("Which room do you want the bulb in?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println("Please enter the blub's color.");
String color = scan.nextLine();
System.out.println("Please enter the blub's increment amount.");
String incrementS = scan.nextLine();
int incrementI = Integer.parseInt(incrementS);
ThreeWayBulb aBulb = new ThreeWayBulb(color, incrementI);
rooms.get(choiceNumber).addBulb(aBulb);
System.out.println("A " + color + " bulb with and increment of " + incrementI + " was added.");
options();
}
public void clickAllBulbsInRoom() {
displayRooms();
System.out.println("Which room do you want the bulbs clicked?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
rooms.get(choiceNumber).clickAllBulbs();
System.out.println("The bulbs in " + rooms.get(choiceNumber).getDescription() + " have been clicked.");
options();
}
public void printDescriptionOfBulbs() {
displayRooms();
System.out.println("Please enter a room number.");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println(rooms.get(choiceNumber).getDescription() + " with " + rooms.get(choiceNumber).returnSize() + " bulbs: " + "\n" + rooms.get(choiceNumber).toString());
options();
}
}
My instructor wants me to do this without instance variables He said if a method needs the ArrayList that I should make it a parameter and have no instance variables in my TUI. I can't for the life of me figure out how to do that. Also, making it static work fly either. Thanks for any help you can give.
He wants you to declare the ArrayList from a central location (such as the main thread) and then pass it as an argument to the functions that use it. This way if you were to take methods and put them in different classes then it wouldn't break because they're not dependent on this class.
For example if we take your newRoom class:
public void newRoom(List<Room> roomList) {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
roomList.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
EDIT: The easiest way to achieve this is to probably move the declaration of rooms to within your run method. Now for each location in the code that reports "unknown variable rooms" you can modify the function to take an ArrayList as a parameter.
Well, eliminating userNumber and userAnswer as members is trivial; their usage is very localized.
For the list, just pass it around after creating it in your main loop.
The scanner is used multiple places; it could also be passed around, I suppose.