Variable does not exist? - java

So, I have some fairly simple code, but in the second class, neither method can find name. Is this a simple issue of scope?
package rpg;
import java.util.Scanner;
public class Start {
static String name;
public static void main (String args[])
{
Engine test12 = new Engine();
name = test12.gameStart();
System.out.println("So, " + name + " it is!");
}
}
Which calls this class:
package rpg;
import java.util.Scanner;
public class Engine {
static boolean playerNameLike = false;
String name = (" ");
public String gameStart()
{
while (playerNameLike = false)
{
System.out.println("So, whats your name?");
Scanner gameStart = new Scanner(System.in);
name = (gameStart.next());
nameTest();
}
return name;
}
public boolean nameTest()
{
System.out.println("Does " + name + " sound good?");
System.out.println("(Y)es or (N)o?");
Scanner gameStart = new Scanner(System.in);
String yesNo = new String (gameStart.next());
if (yesNo.equals("Y"))
{
playerNameLike = true;
return playerNameLike;
}
if (yesNo.equals("N"))
{
playerNameLike = false;
return playerNameLike;
}
return playerNameLike;
}
}
Does anyone know what I'm doing wrong?

You should make name a local variable in the gameStart method, and pass it to nameTest as a parameter, like this:
public String gameStart()
{
String name = "";
boolean playerNameLike = false;
while (!playerNameLike)
{
System.out.println("So, whats your name?");
Scanner gameStart = new Scanner(System.in);
name = (gameStart.next());
playerNameLike = nameTest(name);
}
return name;
}
public boolean nameTest(String name) // Use your current code from here on
Also, you are assigning false to the variable in the if statement. This is allowed, but it does not do what you want. You should either use ==, or (better) use ! to negate the variable:
while (!playerNameLike) ...

Use == to compare in the condition as:
while (playerNameLike == false)
or just check the negation of it as its a boolean type:
while (!playerNameLike)
Also, move the Scanner instantiation outside the while loop as:
Scanner gameStart = new Scanner(System.in);
while (!playerNameLike)
{
System.out.println("So, whats your name?");
name = (gameStart.next());
nameTest();
}

Related

How to print elements from linked list

I've got a linked list class with a controller class and a test class which is the main class. The code runs and accepts user input, however when I click to display all team members entered it is empty.
Where have I gone wrong? How do I get all the team members to entered to be displayed?
public class TeamMember {
private LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
this.teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
this.teamMembers = new LinkedList<>();
}
}
package com.view;
import com.controller.TeamMemberController;
import com.model.TeamMember;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TeamMemberTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
TeamMemberController teamMemberController = new TeamMemberController();
int userInput;
do {
System.out.println("1. Add a new team member");
System.out.println("2. Find and display a team member");
System.out.println("3. Remove a team member");
System.out.println("4. Display all team members");
System.out.println("0. Quit");
//Validate user input
try {
userInput = scan.nextInt();
scan.nextLine();
} catch (InputMismatchException e) {
//if anything other than an integer is entered.
//The "scan.nextLine" fix above will not be triggered.
//It has to appear in the catch as well.
scan.nextLine();
userInput = 5;
}
switch (userInput) {
case 0:
userInput = teamMemberController.quit();
break;
case 1:
System.out.println("**********\n" + teamMemberController.addTeamMember());
break;
case 2:
System.out.println("**********\n" + teamMemberController.findTeamMember());
break;
case 3:
System.out.println("**********\n" + teamMemberController.removeTeamMember());
break;
case 4:
teamMemberController.displayAllTeamMembers();
break;
default:
System.out.println("*** Please Make another selection ***");
System.out.println("");
break;
}
} while (userInput != 0);
}
}
package com.controller;
import com.model.TeamMember;
import java.util.LinkedList;
import java.util.Scanner;
public class TeamMemberController {
private TeamMember teamMember;
public TeamMemberController() {
String name = null;
this.teamMember = new TeamMember(name);
}
Scanner scan = new Scanner(System.in);
public String addTeamMember() {
System.out.println("To go back press 0");
String name = null;
boolean keepLooping = true;
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//user enters name
while (keepLooping) {
System.out.println("Enter team member name");
//project names MUST be UNIQUE
name = scan.nextLine();
if (name.equals("0")) {
return "team member not added";
}
if (!this.checkIfTeamMemberNameExists(name)) {
keepLooping = false;
} else {
System.out.println("Team Member already exists");
System.out.println("");
}
}
//add team member to collection
teamMembers.add(new TeamMember(name));
teamMember.setTeamMembers(teamMembers);
//returns true when a team member has been successfully added
return "Name: " + name + "\n--Added--";
}
public String findTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if the company has no team members no need to continue
if (teamMembers.isEmpty()) {
return "Sorry no team members";
}
//get here company must have team members
System.out.println("Enter team member name");
String name = scan.nextLine();
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return "Name: " + t.getTeamMembers();
}
}
return "Team member not found";
}
public String removeTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
System.out.println("Enter name of team member to remove");
System.out.println("Enter 0 to exit");
String projectToRemove = scan.nextLine();
boolean removed = false;
if (projectToRemove.equals("0")) {
return "No project removed";
}
//check existing team member names against the user input one
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(removeTeamMember())) {
teamMembers.remove(t);
removed = true;
}
}
if (removed) {
teamMember.setTeamMembers(teamMembers);
} else
return "No team member found";
return removeTeamMember() + " has successfully been removed";
}
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getTeamMembers() + " ");
}
}
public int quit() {
System.out.println("Are you sure you want to quit? y/n");
String userResponse = scan.nextLine();
boolean loop = true;
while (loop) {
if (userResponse.equalsIgnoreCase("y")) {
System.out.println("Program ending");
return 0;
} else if (userResponse.equalsIgnoreCase("n"))
return 5;
}
return 0;
}
public boolean checkIfTeamMemberNameExists(String name) {
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if a team member with the same name already exists return true
if (!teamMembers.isEmpty()) {
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return true;
}
}
}
return false;
}
}
This is the output I'm getting. How do I get it to print the names entered?
[1]: https://i.stack.imgur.com/FVhVm.png
The first problem is that TeamMembers don't remember the names you give them. Add a field for the name, and a method to retrieve it:
private String name;
public TeamMember(String name) {
this.name = name;
this.teamMembers = new LinkedList<>();
}
public String getName() {
return name;
}
The second problem is that displayAllTeamMembers does not display the "name" of the team member. There was no way it could have done it because the team members didn't even have a name, but now they do.
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getName());
}
}
A third possible problem is that each individual "team member" has a list of team members. That just seems confusing to me and makes me wonder if you have misread the instructions for this exercise.
Below is the minimum code change required to make your code work. But I would suggest to follow design patterns before if you a build a working prod ready system around this code.
public class TeamMember {
private static LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
if(teamMembers==null) {
teamMembers = new LinkedList<>();
}
}
}

how to print the default constructor with private variables from another class

I want to print the default private bloodtype and rhfactor which is O+ and + I want to print it from another class which has the main method.
I've already tried creating new objects and printed them but still it says that I'm accessing a private variable. When you input something on the scanner it prints it but if you input none I want to print the constructor with private variables!
public class blooddata {
private String bloodtype;
private String rhFactor;
blooddata(){
bloodtype = "O";
rhFactor = "+";
}
blooddata(String btx, String rhx){
this.bloodtype = btx;
this.rhFactor = rhx;
}
public String getblood (String bloodtype){
return bloodtype;
}
public String getfactor (String rhFactor){
return rhFactor;
}
public void setblood(String bloodtype){
this.bloodtype = bloodtype;
}
public void setfactor(String factor){
this.rhFactor = factor;
}
}
here is the class that has main method
import java.util.Scanner;
public class Runblooddata {
static Scanner sc = new Scanner(System.in);
static String btx;
static String rhx;
public static void main(String[] args) {
System.out.print("Enter blood type: ");
btx = sc.nextLine();
System.out.print("Enter rhFactor: ");
rhx = sc.nextLine();
if (btx.isEmpty() || rhx.isEmpty()){
blooddata asd = new blooddata(); //this is where i am lost
}else{
blooddata bd = new blooddata();
bd.setblood(btx);
bd.setfactor(rhx);
System.out.println(bd.getblood(btx));
System.out.println(bd.getfactor(rhx));
}
}
}
Getters aren't supposed to have parameters.
When you declare a method parameter named the same as a field, the parameter hides the field. You basically return the parameter you take.
6.4.1. Shadowing
A declaration d of a field or formal parameter named n shadows, throughout the scope of d, the declarations of any other variables named n that are in scope at the point where d occurs.
public String getBlood() {
return bloodtype;
}
public String getFactor() {
return rhFactor;
}
I will help you to simplify it a bit.
final class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter blood type: ");
String btx = sc.nextLine();
System.out.print("Enter rhFactor: ");
String rhx = sc.nextLine();
BloodData data = btx.isEmpty() || rhx.isEmpty() ?
new BloodData() :
new BloodData(btx, rhx);
System.out.println(data.getBloodType());
System.out.println(data.getRhFactor());
}
}
final class BloodData {
private final String bloodType;
private final String rhFactor;
BloodData() {
this("O", "+");
}
public BloodData(String bloodType, String rhFactor) {
this.bloodType = bloodType;
this.rhFactor = rhFactor;
}
public String getBloodType() {
return bloodType;
}
public String getRhFactor() {
return rhFactor;
}
}
As Andrew has already explain the design issue what you have in your code, I'll guide you towards the solution what you are seeking for.
blooddata bd = new blooddata();
if (!btx.isEmpty() && !rhx.isEmpty()){
bd.setblood(btx);
bd.setfactor(rhx);
}
System.out.println(bd.getblood());
System.out.println(bd.getfactor());

Calling an object's method defined in List

I'm trying to call addContact method from main method using ArrayList called phone but its not working.
Here's the code:
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
public void addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
}
}
public class Main {
static void menu() {
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone;
while(true) {
menu();
int c = sc.nextInt();
if(c==1) {
phone.add().addContact();
//I'm trying to call addContact()
} else if(c==2) {
break;
}
}
}
}
Why I can't just call phone.add().addContact()?
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
}
public class Main {
static void menu()
{
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone = new Arraylist<A>();
while(true)
{
menu();
int c = sc.nextInt();
if(c==1)
{
System.out.println("Enter name:");
String name = sc.nextLine();
System.out.println("Enter number:");
int num = sc.nextInt();
phone.add(new A(name,num));
}
else if(c==2)
{
break;
}
}
}
}
Just removed you addContact and placed in in the while. Now i create a new Instance of A and add it to the list. This should work now. Please post more precise Questions in the future.
You need to create an instance of your list:
ArrayList<A> phone = new ArrayList<>();
ArrayList <A> phone;
Should be:
ArrayList phone = new ArrayList();
Also, the add() method in this line
phone.add().addContact();
should contain an A object to add to the ArrayList.
you need to return object of A
public A addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
return new A(name,num);
}
and
if(c==1)
{
phone.add(addContact);
}
Your problem starts here:
ArrayList <A> phone;
only declares that list; but doesnt define it. Thus you run into a NullPointerException when you try to run your code.
You need
ArrayList <A> contacts = new ArrayList<>();
instead. I took the freedom to give that variable a reasonable name, too. (this list is about storing contents, it is not storing phones; and it is also not a single phone ... just a list of contact information)
But there is more. You see, you are getting your abstractions wrong. Your Contact class (A is just a terrible name for that class) should not be dealing with a scanner to fetch its data.
Instead, you want to do something like:
class Contact {
private final String name;
private final int number;
Contact(String name, int number) {
this.name = name;
this.number = number;
}
and then, within your main method, you do something like:
boolean loop = true;
while (loop) {
... have user enter a name and a number
if (name.equals("STOP")) {
loop = false;
} else {
Contact contact = new Contact(name, number);
phones.add(contact);
}
}
I can't give the working code. Just check below points to make your program better.
Why you are creating constructor with arguments when you using add contact method.
Where you are created object for class A in class Main.
Try to check how to use ArrayList class. Because you are not using add() properly.

Is there a way to send variables from main class to subclass using user input JAVA

So I'm working on a (supposedly) simple java application that uses console inputs from a user, to change private variables in another class. Now I can change the value of the private variables in the EmpCls class directly from the main class by manually inputting a variable into the object, e.g.
EmpCls empObject1 = new EmpCls("josh"); but how do I get something like this
EmpCls empObject1 = new EmpCls(ctName); to work? where ctName is the variable that the user inputs. here's the relevant code from the main class:
import java.util.*;
public class NewWan {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
EmpCls empObject1 = new EmpCls(ctName);
String ctName = empObject1.getName();
System.out.println("enter name: ");
ctName = console.next();
}
}
And the subclass in question:
public class EmpCls {
private String name;
private String ext;
private int yearStarted = 0;
public EmpCls()
{
}
public EmpCls(String inName)
{
this.name = inName;
}
public void setEmpDetails(String inName) //, String inExt, int inYearStarted)
{
this.name = inName;
// this.ext = inExt;
// this.yearStarted = inYearStarted;
}
public String getName()
{
return this.name;
}
public int getYearStarted()
{
return this.yearStarted;
}
public String getExt()
{
return this.ext;
}
public void displayDetails()
{
System.out.println("Name: " + name);
System.out.println("Ext: " + ext);
System.out.println("Year Started" + yearStarted);
}
}
some parts of the code are commented just to enable easier trouble shooting, other parts are part of a different problem im working on.
You just need to reorder the statements a bit and remove the one that doesn't make sense:
public static void main(String[] args) {
System.out.println("enter name: ");
String ctName = console.next();
EmpCls empObject1 = new EmpCls(ctName);
}
Hum... just to organize your code in the good way ? You use variable before getting value, and before declare it... Strange way ^^
public static void main(String[] args) {
System.out.println("enter name: ");
String ctName = console.next();
EmpCls empObject1 = new EmpCls(ctName);
System.out.println("You just enter " + empObject1.getName());
}

printf statement working for one instance of the same class but not another

this is my first time posting so hopefully all goes well. I am having a problem with the following program.
public class Project3 {
public static String fName = "drum_members.txt";
private static Scanner fin;
private static PrintWriter fout;
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
String membershipLength;
Member m_1 = new Member();
Member m_2 = new Member();
Member m_3 = new Member();
Member m_4 = new Member();
try {
fin = new Scanner(new File(fName));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + fName);
System.exit(1);
}// end try
m_1.Member();
m_1.calculateFreeItems();
m_1.printMember();
m_2.Member();
m_2.calculateFreeItems();
m_2.printMember();
m_3.Member();
m_3.calculateFreeItems();
m_3.printMember();
m_4.Member();
m_4.calculateFreeItems();
m_4.printMember();
}
public static class Member{
public int id;
public String name;
public String nickName;
public int monthsMembership;
public String favoriteItem;
public int freeItems;
public void Member()
{
name = fin.next();
nickName = fin.next();
monthsMembership = fin.nextInt();
favoriteItem = fin.next();
fin.nextLine();
}
private int calculateFreeItems()
{
freeItems = monthsMembership/12 +1;
return (freeItems);
}
public void setFavoriteitem()
{
System.out.print("Enter new favorite item: ");
favoriteItem = keyboard.next();
}
private String calculatemembershipLength()
{
if(monthsMembership < 12)
return (monthsMembership + "months,");
else
return (monthsMembership/12 + " years, " + monthsMembership%12 + " months,");
}
public void printMember()
{
String months = this.calculatemembershipLength();
System.out.printf("Member #1 - NAME: %22s, NICKNAME:%22s, MEMBER SINCE: %22s FAVORITE ITEM:%22s, FREE ITEMS PER MONTH: %d\n",
name, nickName, months, favoriteItem, freeItems);
}
}
}
After debugging all I know is that the printf statement doesn't work the THIRD time, it will work the 4th time no problem. Any help would be greatly appreciated, and thanks for your time.

Categories

Resources