Java Input as Variable Name [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to make a program to get information from a list, by entering a code. E.G:
'Enter the code:'
My input: d001
Then I want to print out information that belongs to this code. The information belongs to the String named 'd001', so in this case I want my input to be the name of the variable I am going to print out. How do I do this? Or is there a better solution to get information from a database list by entering the code name for it?
I could make a huge switch statement, but this is not efficient coding. I got this now:
public class Main {
public static Scanner idScanner = new Scanner(System.in);
public static int diseaseId = 0;
/** ID Scanning and reading: */
public static void executeId() {
diseaseId = idScanner.nextInt();
switch (diseaseId) {
case 001:
System.out.println(IdListener.d001);
break;
case 002:
System.out.println(IdListener.d002);
break;
case 003:
System.out.println(IdListener.d003);
break;
case 004:
System.out.println(IdListener.d004);
break;
case 005:
System.out.println(IdListener.d005);
break;
}
}
public static void main(String args[]) {
System.out.println(LayoutListener.titleString); /** Title String Display */
System.out.print(LayoutListener.idField); /** ID field Display */
executeId();
}
}
public class IdListener {
public static String d001 = "[Neuroblastomia]: Tumor that grows on the nerves of the spine.";
public static String d002 = "[Anorexia]: Mental disease to avoid eating and consuming.";
public static String d003 = "[TEMP3]: TEMP3.";
public static String d004 = "[TEMP4]: TEMP4.";
public static String d005 = "[TEMP5]: TEMP5.";
}

Using a Map may be a better solution to what you want to do.
Map<String, String> diseases = new HashMap<String, String>(); // Map<ID, Description>
diseases.put("d001", "[Neuroblastomia]: Tumor that grows on the nerves of the spine.");
diseases.put("d002", "[Anorexia]: Mental disease to avoid eating and consuming.");
// the rest of your diseases
So that when String disId = "d001" it will make things a lot simpler and you will not have a giant switch statement.
if(diseases.containsKey(disId))
System.out.println(diseases.get(disId));
else
System.out.println("That id does not exist!");

Use reflection
Field f= IdListener.class.getDeclaredField("d"+input);
f.get(null);

Very confusing question.
You mention databases but show no code or explanation for that.
Octal
One important flaw in your code: Do no use leading zeros on a numeric literal. The leading zero means the number should be interpreted as an octal number (base-8) rather than as a decimal (base-10).
So, case 001: should be case 1:.
Enum
If you have only a few of these disease codes, and they do not change during the runtime of your app, learn to use an enum. The enum facility in Java is much more powerful and flexible than in other languages.
Map
If the set of disease codes may change during runtime, and you have few enough of these to all fit comfortably into memory, then use a Map collection. A map tracks a bunch of objects ("keys") each of which is associated with another object (a "value"). Like a common dictionary book which tracks a bunch of words, and each word is assigned the text of a definition; each word is a key mapped to a value (it's definition).
In your case an Integer key (code number) maps to a String value (disease title/description). If you know a code number, you can ask the map to locate the matching disease title.
Database
If you have many of these diseases, too many to all fit into memory, use a database. For example the H2 Database.
Whenever you have a code number, query the database for the matching disease title.
You will need to learn about SQL and JDBC.

Related

Objects and attribute values [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I need help with my homework. Please note that I have finished the code below myself, but am not sure if I am doing it correctly, especially the last sentence of my homework assignment.
My homework assignment:
Define a class called Building with the following properties. Every Building has a square footage (area) and stories. The constructor creates a Building with these two attributes. The methods get_squarefootage(), get_stories(), set_square_footage(), and set_stories() will be used to get and set the respective attribute values. The method get_info() will return all the current attribute values of the Building. Write a program that lets a user create Building objects and change their attribute values.
package building_hw2;
import java.util.Scanner;
public class Building {
int area;
int stories;
int get_squarefootage() { //get values of the area
return area;
}
int get_stories() { //get values of the stories
return stories;
}
void set_square_footage(int area) { //set values of the area
this.area = area;
}
void set_stories(int stories) { //set values of the stories
this.stories = stories;
}
void get_info() { //return all the current attribute balues of the building
System.out.println("The square footage of the building is " + area);
System.out.println("The building has " + stories + " stories");
}
//main method
public static void main(String[] args) {
Building Bldg = new Building(); //create a building object
Bldg.area = 40000;
Bldg.stories = 5;
Bldg.get_info(); //display the current values of the building
//get user input to create building object
Scanner keybd = new Scanner(System.in);
System.out.println("Please enter the square footage(area) of the building : ");
int bldgArea = keybd.nextInt();
System.out.println("Please enter the stories : ");
int bldgStories = keybd.nextInt();
Bldg.set_square_footage(bldgArea);
Bldg.set_stories(bldgStories);
Bldg.get_squarefootage();
Bldg.get_stories();
Bldg.get_info();
}
}
You seem to be doing it correctly. However I would like to point out a few things. First you should declare the member variables as private for better encapsulation of your class. You already have setter methods for changing the attribute value.
int area;
int stories;
In your main you can set building values as follows :
Bldg.set_square_footage_area(40000);
Bldg.set_stories(5);
The requirement for get_info is not very clear you should ask what exactly should be returned (some string representation of the attributes or just print current values of all attributes)
You're confusing "returning" and "printing to the console". The get_info() method should return something. It shouldn't print anything.
Fields should be private. Methods, in this case, should be public, since you want any other class to be able to call them. And you forgot to provide a constructor, althoughh your teacher asked you to provide one.
Please kindly inform your teacher that naming conventions exist in Java, and that teaching other conventions is not a good idea at all. A whole lot of frameworks and APIs assume the respect of the standard conventions. get_squarefootage() should be named getSquareFootage(). Same for the setter. Use real words, starting with a lowercase letter, for your variables: building, and not Bldg.
get_info should either return a String or be renamed to printBuildingAttributes.
You have Bldg.area, but why not have a setter method for this field? That would jive with your getter/setter paradigm. It looks like you already have it, so use it. Make the fields themselves private and only accessible thru your getter/setter methods.
If you are going to retrieve the number of stories or area of a building, you need to store it in a variable. Right now, you are retrieving it and throwing it away.
Also, get_info or get_area is not the right Java convention for method naming.

Generate multiple Unique IDs using algorithm with single input string/pattern [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there any algorithm or api to generate multiple Unique IDs with single input string/pattern, so that if we input any of the resulted IDs , it should match the pattern/String(ie, we could validate the resulted IDs against input pattern/String)
Any idea?
You could use an insecure hash function. Your "single pattern" could be a hash value. Your multiple IDs could then be any input that gave that hash value when passed to the insecure hash function. The hash function needs to be insecure so you can drive it backwards to generate new IDs.
For example, your hash could be just XORing all the bytes together. If your single pattern is 0x2A, then any string that XORs to that value can be an ID.
You will need to judge how insecure the hash function needs to be depending on your needs. There are plenty of cryptographically insecure hash functions, of varying degrees of reversibility, that you could use.
Just as the answer above an idea is to use a hash table, make your own hash function, or simply use Object.hashCode(). However note that you must handle collisions somehow. This means that id´s are not always unique, and you must handle that case. Javas built in hashTable handles this as they compare the String entered if there are several strings that get the same id when entered.
static void saveTable(UUID h1, Object x,Hashtable ht)
{
if(ht.get(h1) == null)
{
ht.put(h1, x);
}
else
{
Object ref=h1;
Object ref2=new Object();
while(ref!=null)
{
if(ref!=null)
{
ref2=ref;
}
ref=ht.get(ref);
}
ht.put(ref2,x);
}
}
static ArrayList loadTable(UUID h1,Hashtable ht)
{
Object x=ht.get(h1);
Object ref=h1;
ArrayList al=new ArrayList();
if(ht.get(h1)!=null)
{
while(ref!=null)
{
if(ref!=h1)al.add(ref);
ref=ht.get(ref);
}
}
return al;
}
Then in main:
public static void main(String[] args)
{
Hashtable ht=new Hashtable();
UUID h1=UUID.randomUUID();
UUID h2=UUID.randomUUID();
saveTable(h1, "this is",ht);
saveTable(h1, "inefficient",ht);
saveTable(h2, "but",ht);
saveTable(h2, "saves",ht);
saveTable(h2, "the day",ht);
saveTable(h2, "at least",ht);
Object[] al=loadTable(h1,ht).toArray();
Object[] al2=loadTable(h2,ht).toArray();
for(int i=0;i<al.length;i++)
{System.out.println(al[i]);}
for(int i=0;i<al2.length;i++)
{System.out.println(al2[i]);}
}
Output:
this is
inefficient
but
saves
the day
at least
Ofcourse I used strings as targets and UUID as keys. You can use alter the methods to accept strings as keys and UUID as targets.

Searching for suitable data structure in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
We are working on a game and looking to develop a functionality which will allow us to mix various items in a manner similar to "alchemy" game. The main idea is that we have a number of elements, which can be split into three groups: basic, intermediate and final. Basic resources can be merged together and make an intermediate resource, intermediate resources can be merged with intermediate and basic resources and make final and so on.
So, we are thinking about having 2 HashMaps: one would have a indicate what each resource is combinable with, second one would map what each resource would be made of. Is there a better way to do this? Any data structure that we are not aware of?
Thanks
Just write your own Datastructure like this
public class Element {
enum Type{BASIC, INTERMEDIATE, FINAL};
private Type type;
private String name;
private List<Element> combinable;
}
What you want is an enum containing all your elements, with a couple of methods. Here is an example, feel free to use it if it suites your needs.
If desired, you can also make a second enum for Type (as Templar suggested) and add it as a field in you Element enum.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public enum Element {
//Example instances, replace with what is appropriate for your game.
WATER, // Basic
WOOD, // Basic
IRON, // Basic
STONE, // Basic
FIRE, // Basic
CARBON(WOOD, FIRE), //Intermediate
FORGE(STONE, IRON), // Intermediate
STEEL(FORGE, IRON); // Final
private Element[] parts;
private Element() {
//instantiates parts to prevent NullPointerException
this.parts = new Element[0];
}
private Element(Element... parts) {
this.parts = parts;
}
/**
* return all the parts of this Element.
* #return
*/
public List<Element> getParts() {
return Arrays.asList(parts);
}
/**
* find all elements that have this Element listed as one of their parts.
*
* #param part
* #return
*/
public List<Element> getComposites() {
List<Element> composites = new ArrayList<Element>();
// Iterate through all Elements
for (Element composite : Element.values()) {
// Iterate through each Element's parts
for (Element part : composite.parts) {
// If the element has a part equal to the argument,
// Add the element to the list of composites.
if (part == this) {
composites.add(composite);
}
}
}
return composites;
}
}
You should use the Composite design pattern.
In your case BasicResource is a leaf class.
intermediate and final are composites.
I would actually separate elements and their combinability - if each element has to contain a list of elements it's combinable with, whenever you want to add a new element you have to go back and add it to all old elements you want it to combine with.
I'd separate the concept out into something like "Elements" and "Formulas" -
class Element {
enum Type{NULL, BASIC, INTERMEDIATE, FINAL};
private Type type;
private String name;
// ....
}
class Formula {
private List<Element> requires = new ArrayList<Element>();
private Element produces;
public Formula(List<Element> requires, Element produces) {
Collections.copy(requires, this.requires);
this.produces = produces;
}
public final List<Element> requiredElements() {
return Collections.unmodifiableList(requires);
}
public final boolean applyFormula(List<Element> ingredients) {
for (Element e : requires) {
if (!ingredients.contains(e)) {
// ingredients doesn't contain a required element - return early.
return false;
}
}
for (Element e : requires) {
ingredients.remove(e);
}
ingredients.add(produces);
return true;
}
}
If you're creating a game, having this data hard-coded in your Java source code is going to make things a pain. You'll have to recompile every time you want to add a new element, change a relationship (what is composed of what), etc.
Instead, I'd recommend storing all of your element information in an external source and then reading it in / accessing it from your program. You could do this with a database, but I have a feeling that's a little bit overkill (at least for now). Instead, you could use a nice readable, plain-text, standardized format like JSON to define your elements and their relationships externally, and then import all the data using a library (I'd suggest GSon) for easy access in your program.
As for the data structure, I think your choice of HashMaps would work just fine. Since JSON is built on two basic types of data structures—lists [] and maps {}—that's what Gson would convert things to anyway. Here's a very simple example of what how I'd envision your element specification:
{
"elements" : {
"iron" : "basic",
"carbon" : "basic",
"steel" : "intermediate"
},
"formulae" : {
"steel" : [ "iron", "carbon" ]
}
}
You could read that in with Gson (or whatever JSON library you choose), and then build whatever other data structures you need from that. If you can figure out how to get Gson to create the data structures you want directly (I know this is possible, but I don't remember how hard it is to do the configuration), then that would be even better. For example, if you could turn the "formulae" value into a BidiMap (the Apache Commons bi-directional map) then that might be very useful (but you'd also need to turn the components list into a set to keep it order-agnostic, e.g. iron+carbon is the same as carbon+iron).
For even more dynamic behavior, you could add a feature into your program to allow you to reload all of your elements data while your game is still running! (This might make debugging easier.)
I know this isn't exactly what you were asking, but I hope you find my suggestions helpful anyway!

java codes for a restaurant multiple steps [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Question 1:
Assuming “OOP Restaurant” owner has engaged you to write a Java
program to take the restaurant customer order. The beverage menu of
the restaurant is as shown in Table 1. This program must allow customer
to decide how many items he/she wish to order. Then, it will let the
customer to choose the each item according to his/her preference. Upon
completion of the ordering, the program will display the total amount of
the order to the customer. Then, the program must ask the customer
whether to do another set of ordering.
In your code, you must create a method to process the item choice and
return the price of the item using the following method signature:
double processItem(int input)
The sample out is as shown in Figure 1.
Beverage | Price
Fried Rice | RM5.50
Chicken Rice | RM5.00
Toast Bread | RM2.00
Mixed Rice | RM3.80
Table 1
How do i even start this? i'm a law student but got forced to do this please do help me out your kindness would be repayed thanks in advance
Having written the answer out this is quite a complex task for a non-programmer. There's concepts of how a program should be structured to contend with after which comes the compilation and running.
This answer is in just that order, first I'll explain what I think the key points are (sure I've missed some, as much of this is second nature) then I'll give you pointers on how to run the code.
Step 1.
Think about what's involved if you were going to do this on paper - you'd have a list of beverages each with a name and a price (the menu). An order comprises of one or more beverages from the menu in varying quantities. You multiple the price of each beverage by the quantity to get the cost of the order.
Step 2.
Modern computer languages use a technique call Object Orientation, which in a nutshell involves describing the entities in general terms to create what is known as classes. When presented with a problem, like that in step 1, a good rule of thumb in deciding what the classes should be is to look at the nouns - in this case beverage, menu and order look like good candidates. A class typically has attributes (the data that will make instances unique) and behaviour (operations based on that data) though you'd don't neccessarily have to have both as you can see from the code below.
Step 3.
I imagine to a non-programmer, step 2 doesn't make much sense, so here's some code (which I hope makes it a bit clearer):
/**
* This is the way classes are defined in Java, the public bit just says it's visible
* to every other class in the system.
*/
public class Beverage
{
//These are the attributes (fields) of the class. It's good practice to make them
//private so that they can only be accessed from within the class.
private String name;
private BigDecimal cost;
/**
* This is the constructor, which is used to create instances of the class. In
* this case it takes the arguments used to initialize the attributes of the class.
*/
public Beverage(String name, BigDecimal cost)
{
this.name = name;
this.cost = cost;
}
/**
* This is a getter, which provides access to the attributes from outside of the
* class.
*/
public BigDecimal getCost()
{
return this.cost;
}
public String getName()
{
return this.name;
}
}
public class Order
{
//This line is assigning an instance of HashMap (a standard data structure class
//in Java). A map is a bit like a dictionary, you have a key in this case the
//beverage that allows you to look-up another value, the quantity.
private Map<Beverage, Integer> beverages = new HashMap<Beverage, Integer>();
public BigDecimal getTotal()
{
BigDecimal total = BigDecimal.ZERO;
//Loop over all the beverages that have been added to the map summing the cost.
for (Beverage beverage : this.beverages.keySet())
{
//Convert the quantity in the map to a BigDecimal needed for the multiply method.
BigDecimal quantity = new BigDecimal(this.beverages.get(beverage));
total = total.add(beverage.getCost().multiple(quantity));
}
return total;
}
public void add(Beverage beverage, Integer quantity)
{
//Store the quantity against the beverage.
this.beverages.put(beverage, quantity);
}
}
These two classes are all you need to solve the problem. Menu is abscent because Java provides a class for a list of items. Next you need to use them in a program.
Step 4.
In Java any class can be 'run' providing it has a special method called main. Again, it's probably easier with an example:
public class Restaurant
{
/**
* The main method is static meaning it can be accessed without creating an instance
* of the Restaurant class.
*/
public static void main(String[] args)
{
Map<String, Beverage> menu = new HashMap<String, Beverage>();
//Create the instances of Beverage and add them to the menu.
menu.put("Fried Rice", new Beverage("Fried Rice", new BigDecimal(5.50)));
menu.put("Chicken Rice", new Beverage("Chicken Rice", new BigDecimal(5.00)));
menu.put("Toast Bread", new Beverage("Toast Bread", new BigDecimal(2.00)));
menu.put("Mixed Rice", new Beverage("Mixed Rice", new BigDecimal(3.80)));
//Create an order and add items from the menu to it.
Order order1 = new Order();
order1.add(menu.get("Fried Rice"), 2);
order1.add(menu.get("Toast Bread"), 3);
order1.add(menu.get("Mixed Rice"), 1);
System.out.println("Total for order 1: " + order1.getTotal());
//Create another order and add items from the menu to it.
Order order2 = new Order();
order2.add(menu.get("Chicken Rice"), 1);
order2.add(menu.get("Mixed Rice"), 1);
order2.add(menu.get("Toast Bread"), 2);
System.out.println("Total for order 2: " + order2.getTotal());
}
}
Step 5.
That's all the code I think you'll need. But in order to run it there's a few further steps. First is to install the Java Development Kit, which can be download from Oracle. Then, in Java, each class is typically declared in a text file that has the same name as the class with a .java extension - you'll end up with Beverage.java, Order.java and Restaurant.java. Next you need to compile your program - in basic terms this is the process of verifying the code you have written and converting it to something the Java Runtime can understand. I won't attempt to explain that, it's pretty well covered in the Getting Started Guide, which also explains how to run a Java program - ultimately you'll be looking for a command line that looks something like:
java -cp [path to class files] Restaurant

Java how can I pass array values from one method to another [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
As the title of the question suggests, I would like to know how to share array values between methods. My main objective is this. I have a method where the user inputs are stored in an array and then this method will basically check the user input values (validation process)
say something like this
(please ignore the syntax)
public void validation()
{
String[] accnumbers = new String[20];
Scanner sc = new Scanner(System.in);
System.out.print("Enter the account number:");
accno = sc.nextLine();
int j;
for (j = 0; j < accnumber.length; j++)
if (accnumber[j] == null) break;
if (j==accnumber.length)
{
System.out.print("limited.");
}
else
{
accnumber[j]=accno;
}
}
//so that is for the vaidation part and as you can see that there is a accnumbers array now i want to share that in the following method, which basically searches for a accnumber that is valid in the string
public void search(String[] acnumbAry,BigDecimal[] acbalanceArray,String accnumbinput)
{
if(Arrays.asList(acnumbAry).contains(accnumbinput))
{
System.out.println("The value is contained");
}
else
{
System.out.println("The value is not contained");
}
}
// but in the Main method I have a display menu that gives the user an option to either validate or search, so when the user chooses to search then I am not sure how to get the array values(if any) from the validate method.
Don't use arrays!!! Java ain't C!
Unless you are coding some low-level code that needs to be super fast, use the Collections API. If this is homework (I suspect it is) and your professor has told you to use arrays, demand that the Dean of the faculty to remove him immediately from teaching before he does any more damage! Arrays are a terrible choice for nearly all situations.
In this case, use a List, which grows in size automatically. No need to check for size etc. Then return the List from your method. Your code will shrink to this:
public List<String> validation() {
List<String> accnumbers = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter account numbers (blank to finish):");
while (true) {
String accno = sc.nextLine();
if (accno.equals("")) { // blank ends input
return accnumbers;
}
accnumbers.add(accno); // will take any number of account numbers
}
}
You don't even need your search method, just use list.contains() in line.
You could return the array in your method:
public String[] validation()
{
String[] accnumbers = new String[20];
// your validation code
return accnumbers;
}
Let me, however, suggest you some changes to your code:
You could populate the array before validating it, and then passing it to your validation method. I'd too suggest you to call it validate rather: bool validate(String[] values). It would feel more intuitive to me, because validating and receiving data are generally two different things. As Anon writes, you could store the accnumbers in an instance field.
As you are working with contains in your sample, you might be better of using a Set instead of an array or List, since searching sets in generally quicker.
I would have rather dropped String[] acnumbAry in member list of the class and have initialized it with a constructor.
Copying the array during function calls will only hamper the performance.

Categories