Why can't I call a private variable in main method? - java

this code is supposed to receive a full name string example "Billy Bob Smith" in an input dialog box and output the initials as a monogram example "BBS" in a message dialog box. but for some reason the main method won't let me acces the fullName variable.
import javax.swing.*;
public class HardMonogram {
//---------- ATTRIBUTES ----------//
private String fullName;
private String monogram;
private String first;
private String middle;
private String last;
//---------- METHODS ----------//
public String getInitial(String seperateName) {
return seperateName.substring(0, 1);
}
public void getSeperateName(String fullName) {
first = fullName.substring(0, fullName.indexOf(" "));
middle = fullName.substring(fullName.indexOf(" ") + 1, fullName.length());
last = middle.substring(middle.indexOf(" ") + 1, middle.length());
middle = middle.substring(0, middle.indexOf(" "));
}
public void setMonogram() {
monogram = getInitial(first) +
getInitial(middle) +
getInitial(last);
JOptionPane.showMessageDialog(null, monogram);
}
public static void main(String[] args) {
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
HardMonogram myMono = new HardMonogram();
myMono.getSeperateName(myMono.fullName);
myMono.setMonogram();
}
}
gives me this build error
/Users/aaron/School/Fall 2012/CSCI-C 201/Labs/LB08/HardMonogram.java:33: error: cannot find symbol
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
^
symbol: variable myMono
location: class HardMonogram
1 error
[Finished in 1.2s with exit code 1]
it's for my intro to java class but I don't know why I can't acces the variable. I'm obviously overlooking something. any ideas?

Update:
After another read of question, you just need to move first line in main method after instance creation.
HardMonogram myMono = new HardMonogram();
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
myMono.getSeperateName(myMono.fullName);
myMono.setMonogram();

Simply put myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name"); after object declaration (HardMonogram myMono = new HardMonogram();).

MyMono has not been declared in the first line of your main method. Add it to the beginning.
public static void main(String[] args) {
HardMonogram myMono = new HardMonogram();
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
myMono.getSeperateName(myMono.fullName);
myMono.setMonogram();
}

Related

How do I print something out according to a response in Java?

I'm new to Java and I'm making a test program. Here's the code:
import java.util.Scanner;
public class Book {
private String title;
private String author;
private String pages;
public static void main(String[] args) {
// Book #1
// =1=
Book anothermedium = new Book();
anothermedium.title = "Another Medium";
anothermedium.author = "Jen Smith";
anothermedium.pages = "387";
// Book #2
// =2=
Book whateveryouwant = new Book();
whateveryouwant.title = "Whatever You Want";
whateveryouwant.author = "Bob Gray";
whateveryouwant.pages = "424";
System.out.println("Enter the name of a book to see its details ");
System.out.println("or input Catalog to see the catalog.");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
}
}
I'm trying to make it so when you input something like Catalog the response will be something like:
The current catalog consists of the books:
Another Medium
Whatever You Want
I'm sorry if this has already been posted. I searched and I couldn't find anything addressing my question.
Use an if-statement,
if(input.toLowerCase().equals("catalog"){
//do what you need to do here
System.out.println("The current catalog consists of the books: ");
System.out.println(anothermedium.title);
System.out.println(whateveryouwant.title);
}
To make the condition case-sensitive, the input string should be converted to lowercase. If you don't understand the syntax, basically the condition in the if-statement gets evaluated. If if evaluates to true, then whatever's in between the brackets gets exectued. If it evaluates to false, then it skips whatever's in the two brackets to proceed with the rest of the code. Hope this is what you need. Good luck!
I suggest you add each Book to a List<Book> that can looped over for the correct element, or can be used to print the entire catalogue. Something like the following implementation.
This way if you user wants a specific book the else if() can match the title and print the correct Book Otherwise if the user wants to view the enire catalogue they will only be shown the Book Titles
List<Book> listBook = new ArrayList<>();
listBook.add( whateveryouwant );
listBook.add( anothermedium );
System.out.println( "Enter the name of a book to see its details " );
System.out.println( "or input Catalog to see the catalog." );
Scanner scan = new Scanner( System.in );
String input = scan.nextLine();
for( Book book : listBook )
{
if( "catalog".equalsIgnoreCase( input ) )
{
System.out.println( "Title: " + book.getTitle() );
}
else if( book.getTitle().equalsIgnoreCase( input ) )
{
System.out.println( book.toString() );
}
}
You can create an arrayList of these book objects. Add each objects of book in that list.Run this code it should work.
public class Book {
private String title;
private String author;
private String pages;
public void Book(){
}
public String getTitle(){
return title;
}
public static void main(String[] args) {
// Book #1
// =1=
ArrayList<Book> catalog = new ArrayList<Book>();
Book anothermedium = new Book();
anothermedium.title = "Another Medium";
anothermedium.author = "Jen Smith";
anothermedium.pages = "387";
catalog.add(anothermedium);
// Book #2
// =2=
Book whateveryouwant = new Book();
whateveryouwant.title = "Whatever You Want";
whateveryouwant.author = "Bob Gray";
whateveryouwant.pages = "424";
catalog.add(whateveryouwant);
System.out.println("Enter the name of a book to see its details");
System.out.println("or input Catalog to see the catalog.");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
if(input.equals("catalog"))
{
for(int i=0;i<catalog.size();i++)
{
System.out.println(catalog.get(i).getTitle());
}
}
}}
There are a couple different problems you're trying to solve here.
How do I conditionally display a certain output, based on the
user's input text?
How do I iterate over the contents of a List and display their names?
One thing to keep in mind is that Java is Object-Oriented. You almost always want to consider the problem you're trying to solve, and create classes that represent the various types of things within your problem space. You've described a Book entity and a Catalog entity in this case. These are usually separate classes from your main program class (that contains your main method).
You can solve the first problem by using an if statement to compare the input to a constant that your application knows about. You can solve the next problem by defining meaningful classes around your problem structure, and defining toString methods with the output that you want to see.
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class CatalogViewer {
private static final String VIEW_CATALOG_KEY = "catalog";
public static class Book {
private String title;
private String author;
private String pages;
public Book(String title, String author, String pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
#Override
public String toString() {
return title;
}
}
public static class Catalog {
private List<Book> books = new ArrayList<Book>();
public List<Book> getBooks() {
return books;
}
#Override
public String toString() {
StringBuilder message = new StringBuilder();
message.append("The current catalog consists of the books:\n");
for (Book book : books) {
message.append("\n" + book + "\n");
}
return message.toString();
}
}
public static void main(String[] args) {
Catalog catalog = new Catalog();
catalog.getBooks().add(new Book("Another Medium", "Jen Smith", "387"));
catalog.getBooks().add(new Book("Whatever You Want", "Bob Gray", "424"));
System.out.println("Enter the name of a book to see its details ");
System.out.println("or input Catalog to see the catalog.");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
if (input.trim().equalsIgnoreCase(VIEW_CATALOG_KEY)) {
System.out.println(catalog);
}
}
}

How to use Data from an array in another class & method?

I've got a class named "User" which has a method that makes the User type his name. This name is saved in an array that is empty at first.
Question is, how can I use this "stored" name in another class (I want to show the name in this other class)
Here's what I've got (Sorry for the spanish lol)
public class Usuario {
private Scanner entrada = new Scanner(System.in);
private String Usuario[] = new String[20];
private int Posicion = 0;
private int punteo;
public void Datos() {
System.out.println("Ingresa tu nombre");
if(Usuario[Posicion] == null) {
this.Usuario[0] = entrada.nextLine();
Posicion++;
}
}
public String Usuario() {
return Usuario[Posicion-1];
}
And I want to use the name (Usuario[Posicion-1]) for example in a class like this:
public class Score extends Usuario {
Usuario usr = new Usuario();
String[] Name = new String[20];
public void Score () {
Name[0]=usr.Usuario();
System.out.println("------------Scores ------------------");
System.out.println(" Name "+ " Score");
for(int i=0;i<11;i++) {
System.out.println(i+".- " + " "+Name[0] +" 200 ");
}
}
}
But Everytime I try to retrieve this data in this class I get a "null" value or an "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" error, which makes me believe that I can't use the information from the array in another class :(
I'd appreciate any help. (also Sorry for the not-so-good english).
Each new version of a class or an object is not going to have the same values.
you will have to get the name from the object User.name then set it in your other object secondObject.name = User.name

Error Reading Files to Store their Data in an Array

The program that I am writing is in Java. I am attempting to make my program read the file "name.txt" and store the values of the text file in an array.
So far I am using a text file that will be read in my main program, a service class called People.java which will be used as a template for my program, and my main program called Names.java which will read the text file and store its values into an array.
name.txt:
John!Doe
Jane!Doe
Mike!Smith
John!Smith
George!Smith
People.java:
public class People
{
String firstname = " ";
String lastname = " ";
public People()
{
firstname = "First Name";
lastname = "Last Name";
}
public People(String firnam, String lasnam)
{
firstname = firnam;
lastname = lasnam;
}
public String toString()
{
String str = firstname+" "+lastname;
return str;
}
}
Names.java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Names
{
public static void main(String[]args)
{
String a = " ";
String b = "empty";
String c = "empty";
int counter = 0;
People[]peoplearray=new People[5];
try
{
File names = new File("name.txt");
Scanner read = new Scanner(names);
while(read.hasNext())
{
a = read.next();
StringTokenizer token = new StringTokenizer("!", a);
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
People p = new People(b,c);
peoplearray[counter]=p;
++counter;
}
}
}
catch(IOException ioe1)
{
System.out.println("There was a problem reading the file.");
}
System.out.println(peoplearray[0]);
}
}
As I show in my program, I tried to print the value of peoplearray[0], but when I do this, my output reads: "null."
If the program were working corrrectly, the value of peoplearray[0] should be, "John Doe" as those are the appropriate values in "names.txt"
Is the value of peoplearray[0] supposed to be null?
If not, what can I do to fix this problem?
Thanks!
The order of your arguments is wrong:
StringTokenizer token = new StringTokenizer("!", a);
According to API constructor
public StringTokenizer(String str, String delim)
use
StringTokenizer token = new StringTokenizer(a,"!");

Variable not in scope (I think), but not sure how to fix it

What I am doing is just practicing for a test and I thought it was doing just fine, but I am getting, what I think is a scope problem. It says, "teams cannot be resolved to a variable type" and I've tried a few things I thought would fix it, but they didn't work. Here is the code:
import java.util.Scanner;
public class fundamentalsofgame {
public String hteam;
public String cteam;
public String teams(String hometeam, String compteam){
String hteam = hometeam;
String cteam = compteam;
return "The teams are " + hteam + " vs " + cteam;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String hometeam;
String awayteam = "New England Cheatriots";
hometeam = scanner.next();
teams team = new teams(hometeam, awayteam); //error
}
}
teams is a method and not your class name instead it is fundamentalsofgame. So you need to make object of fundamentalsofgame and call teams method on it. Change this:
teams team = new teams(hometeam, awayteam); //error
to
fundamentalsofgame obj = new fundamentalsofgame();
fundamentalsofgame.teams(hometeam, awayteam);

Java code is not letting me call a method from one class to another

Hey guys sorry this is a pretty long question but I cannot call printPASSInfo() to another class using pm.printPASSInfo(). pm is the name I named the class that the method I am trying to call is in. I can call the method pm.printSSNInfo just fine I do not understand what is going wrong. I am sorry this is probably confusing and very long but please try to help. Thanks guys! Heres my code:
import java.util.Scanner;
public class Prog1Methods_FA11 {
String ssn, pw, phoneNumber,line;
Scanner input = new Scanner (System.in);
boolean validPW_Length = true,
validPW_Symbols = true,
validPW_enough_Digits = true;
boolean validSSN_Digits = true,
validSSN_Format = true,
validSSN_Length = true;
boolean validPhone_Symbols = true,
validPhone_Format = true,
validPhone_Length = true;
public Prog1Methods_FA11() {
}
// you may insert a method here to display password status
public void printPASSInfo(){
System.out.println("\t Password Information");
System.out.println("The Password:\t" + pw);
System.out.println("Password Lrngth:\t" + validPW_Length);
System.out.println("Password has minimum number of digits:\t" + validPW_enough_Digits);
System.out.println("Password has correct symbols:\t" + validPW_Symbols);
}
// you may insert a method here to display the phone number status
}
and here is where I am trying to call it:
case 2: System.out.println("Enter a password witha atleast 8 characters and atleast 2 numbers:\t");
pw = input.nextLine();
pm.readAndVerifyPASS(pw);
pm.printPASSInfo();
break;
and the comile error:
MySkeletonProgram1_FA11.java:53: cannot find symbol
symbol : method printPASSInfo()
location: class Prog1Methods_FA11
pm.printPASSInfo();
^
1 error
Where I declare pm object:
public class MySkeletonProgram1_FA11{
public static void main(String[] args)throws Exception {
// Declarations
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in);
Prog1Methods_FA11 pm = new Prog1Methods_FA11();
I'm not sure how well I understood your question.
I just tried to reproduce the error.
So, what I've done.
1. File MySkeletonProgram1_FA11.java
public class MySkeletonProgram1_FA11 {
public static void main(String[] args) throws Exception {
Prog1Methods_FA11 pm = new Prog1Methods_FA11();
pm.printPASSInfo();
}
}
2. File Prog1Methods_FA11.java
import java.util.Scanner;
public class Prog1Methods_FA11 {
String ssn, pw, phoneNumber, line;
Scanner input = new Scanner(System.in);
boolean validPW_Length = true,
validPW_Symbols = true,
validPW_enough_Digits = true;
boolean validSSN_Digits = true,
validSSN_Format = true,
validSSN_Length = true;
boolean validPhone_Symbols = true,
validPhone_Format = true,
validPhone_Length = true;
public Prog1Methods_FA11() {
}
// you may insert a method here to display password status
public void printPASSInfo() {
System.out.println("\t Password Information");
System.out.println("The Password:\t" + pw);
System.out.println("Password Lrngth:\t" + validPW_Length);
System.out.println("Password has minimum number of digits:\t" + validPW_enough_Digits);
System.out.println("Password has correct symbols:\t" + validPW_Symbols);
}
}
3. I've put both files in the same directory.
4. Compilation command
javac MySkeletonProgram1_FA11.java
Compilation finished successfully without errors and warnings.
Does it work for you? If the answer is "No", then I think it's a problem with your JDK. Otherwise you might want to provide additional details. What are you doing differently?
With the class you pasted, this compiles and runs fine:
public static void main(String[] args) {
Prog1Methods_FA11 pm = new Prog1Methods_FA11();
String pw = "foo";
pm.readAndVerifyPASS(pw);
pm.printPASSInfo();
}
Try it, and post any errors you get.
Your code seems fine. The error message may be due to uncompiled code. Try to re-compile/Build and run.

Categories