Java string connection [closed] - java

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
can anyone tell me how can i connect one string with a group of strings and each string have certain value.
for exampe:
String car = new String()
//i give it a value of say 10 dollars
and then i have this group of Strings/Objects
for example:
String frontWindow = new String()
//i set a value for it
String backWindow = new String()
//i set a value for it
String wheel = new String()
//i set a value for it
And i want to calculate the sum of the car with some or all of the string above.I thought about usint the print method but then i would be able to choose only all strings.So does anyone know how can i make this work in the console output?

That's not very clear, but it seems like you want to make a Car class and access variables inside of it.
public class Car{
public String frontWindow, wheel;
public Car(String frontWindow, String wheel){
this.frontWindow = frontWindow;
this.wheel = wheel
}
}
then, from inside an other class you can access it like this:
Car myCar = new Car("this is my front window", "this is my wheel");
System.out.println(myCar.wheel);
if you want those variables to hold values instead of strings, make them "double"s or "int"s.
Look up the difference between storing Strings (text) and Numbers (int, double, long, float, etc.)
Also look up Object Oriented programming for how that all works. Try a google search for "how to create a new object in java", or something like that. Then you also might be able to use getters and setters for those variables you want.

You can combine strings like so:
String totalSum = car + frontWindow + backWindow + wheel;
However, given this example:
String car = "10.00";
String frontWindow = "2.00";
String backWindow = "2.00";
String wheel = "1.00";
They would add together end-to-end and be like so: "10.002.002.001.00"
int and double are actually meant to have number operations done to them instead of String.
int i = 5; // int's are whole numbers, no decimals allowed
int j = 3;
int total = i + j; //Total is 8
double d1 = 1.1;
double d2 = 2.5;
double dTotal = d1 + d2; //Total is 3.6
You can still print them out to the console by doing System.out.println(dTotal);
Probably out of scope, but if you plan on dealing with money in a serious business app, you should check into the BigDecimal class because of tiny rounding errors that can occur with doubles and floats.

Related

trying to get an int and a double from my main method to a non-static method [closed]

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 last year.
Improve this question
I'm working on a project for school and I've run into a wall where I need to get a user inputted Int and double from my main method to a required non-static method. this non-static method is supposed to be used for the calculation and printing of the answer based on the price (double) and the amount paid (int).
public static void main (String[] args){
Scanner check = new Scanner(System.in);// import of the scanner
char cents = '\u00a2';//Unicode of cent symbol
System.out.print("Your item costs (25" + cents + " minimum, Increments of 5" + cents + "): ");
Double price = check.nextDouble(); //price of the item
System.out.println("You paid (whole dollars only): ");
int paid = check.nextInt(); //amount paid
VendingChange newVend = new VendingChange();//creates a copy of the class
newVend.Secondary();// calls the nonstatic
that's the main method
public void Secondary () {
System.out.println("your change is " +/*this is where the equation is supposed to go*/ );
and this is the non-static
I've tried adding an extra static method, which eliminated the errors, but the int and double still wouldn't go through. meaning I can't use the int and double in any other method, because it doesn't recognize the names.
try replacing
Double price = check.nextDouble();
with
double price = check.nextDouble();
or even
String price1 = check.nextLine(); // gets input in form of string
double price = Double.parseInt(price1); // converts to double
Similarly, integers can also be changed:
int paid = check.nextInt();
to
String paid1 = check.nextLine();
int paid = Integer.parseInt(paid1);
I would also recommend reading (as mentioned in the comments) tutorials and really understanding the difference with static and non-static methods (instance).
(uppercase represents the class, while lowercase represents an instance)
Let's say we have a Person class. A static method would be like
Person.getPopulation(). That would return the population. This method is not instance (person) specific, rather it applies to the type of thing a person is.
An instance method would be better when you have something like person.changeName(). This would change the name of a person. An instance of a person. However, if you create it static, like Person.changeName(), which person's name would you be changing?
Think of the class Person like a type of object. People are objects (in this analogy). Person class is a type. Every person instance is every person that lives (in the program).
This same 'type of thing' vs actual 'thing' that exists under that type can be applied to a lot of things in programming, and is the basis of Object Oriented Programming (OOP).

What is the best data structure that represents the following data type? [closed]

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 have data type of the following format:
Popularity:xx
Name:xx
Author:xx
Sales:xx
Date Published: xx
I am free to choose whatever way I can store my data in.
I will need to perform some queries on the data, for example
What are the top 'N' Books for the year 'M'
What are the average sales of the top 'N' songs for author 'X'?
It should be kept in mind that further queries may be added.
What will be the different ways to represent the data to perform the queries (in Java)? What will be the merits?
Note: (Not looking for a DB solution)
JDK comes bundled with Java DB and seems perfectly fine for your use case.
Edit: Sorry I misread the question as a dB solution because it seems you need it. That said you should look for a DB solution where you just query your books from.
If you actually do want to perform queries on data-structures in memory you can use Apache Commons Collections which support filtering.
If you do want to use a data-structure like a Vector which seems like a solution, you need to build indexes to improve performance. Then lookup in the indices and get the book needed. If you know which searches are necessary you can group chosen indexes and create a block to easily search. Essentially creating your own cube data-structure. Could be a nice project.
Arraylist of a class. Create a class with those variables as, well, class variables, then instantiate an Arraylist of said object. Then you can perform searches based on the values of certain variables. For example:
//replace "ClassName" with the name of the class
ArrayList<"ClassName"> array = new ArrayList<"ClassName">();
ArrayList<"ClassName"> results = new ArrayList<"ClassName">();
for("ClassName" obj:array)
{
if(obj.getAuthor().equals("Author Name"))
{
results.add(obj);
}
}
There are many ways to sort the results, including using Collections.sort(); which seems to be the best way to go about it.
Sort ArrayList of custom Objects by property
EDIT: I went ahead and gave you an example based on the specific case you outlined in the comments. This should help you out a lot. As stated before, I had a similar issue for a lab in University, and this was a way I did it.
You could use a Bean to wrap your data:
public class Record {
int popularity;
String name;
String author;
int sales;
int yearPublished;
public Record(int popularity, String name, String author, int sales, int yearPublished) {
super();
this.popularity = popularity;
this.name = name;
this.author = author;
this.sales = sales;
this.yearPublished = yearPublished;
}
//getter and setter...
public String toString(){
return name;
}
And this is a typical usage querying with java8:
Record Record1 = new Record(10,"Record 1 Title","Author 1 Record",10,1990);
Record Record2 = new Record(100,"Record 2 Title","Author 2 Record",100,2010);
Record Record3 = new Record(140,"Record 3 Title","Author 3 Record",120,2000);
Record Record4 = new Record(310,"Record 4 Title","Author 1 Record",130,2010);
Record Record5 = new Record(110,"Record 5 Title","Author 5 Record",140,1987);
Record Record6 = new Record(160,"Record 6 Title","Author 1 Record",15,2010);
Record Record7 = new Record(107,"Record 7 Title","Author 1 Record",4,1980);
Record Record8 = new Record(1440,"Record 8 Title","Author 8 Record",1220,1970);
Record Record9 = new Record(1120,"Record 9 Title","Author 9 Record",1123,2010);
List<Record> Records = Arrays.asList(Record1,Record2,Record3,Record4,Record5,Record6,Record7,Record8,Record9);
//top 2 record of year 2010
int m = 2;
int year = 2010;
System.out.println(Arrays.toString(Records.stream().filter(s -> s.getYearPublished() == year).sorted((r1, r2) -> Integer.compare(r2.popularity, r1.popularity)).limit(m).toArray()));
//average top 2 record of Author 1 Record
String author= "Author 1 Record";
int n = 2;
System.out.println(Records.stream().filter(s -> author.equals(s.getAuthor())).sorted((r1, r2) -> Integer.compare(r2.popularity, r1.popularity)).limit(n).mapToInt(Record::getSales).average().getAsDouble());
This prints:
[Record 9 Title, Record 4 Title]
72.5
Having a collection of objects you can use stream api to collect/filter/reduce your results. There is not so much to it.
The main problem is to not load all of the objects to memory and to be able to retrieve them from whatever store efficiently by using indexes, reverse-indexes.
One of the frameworks which came to my mind is Apache spark

Scanner + TesterClass? [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 6 years ago.
Improve this question
So for this I have to create a program in Java that asks the user to input all three points of a triangle, and then I must find the sides and area. All the math must be done separately from the tester class, where I will prompt the user with the questions...
- how do I ask the user to input something in the tester class but get those integers back in the original program?
In the tester class's main method, you can make an instance of the non-tester class containing the functions where you do the math, i.e.:
TriangleMath tMath = new TriangleMath();
// where TriangleMath is the name of the other class, and "tMath" is
// an instance of it. then:
Scanner keyboard = new Scanner(System.in);
int point1 = (int) keyboard.nextLine().charAt(0);
int point2 = (int) keyboard.nextLine().charAt(0);
int point3 = (int) keyboard.nextLine().charAt(0);
int area = tMath.area(point1, point2, point3);
in this, you're making an object of the class containing all of the math functions and stuff, then getting the input in the main method of the tester class, then passing the inputs into the area function of the instance of the TriangleMath class (tMath).
The .charAt(0) turns it into a char, and the (int) casts it as an int.
I hope I was of some help!
Scanner s = new Scanner();
double x1 = s.nextDouble();
double y1 = s.nextDouble();
and so on...
and pass those variables in the functions that you have created.
I hope it will help you.
Thanks

JAVA Square Footage Calculation [closed]

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 7 years ago.
Improve this question
I have to Write a program in Java that will take the dimensions of two different homes and calculate the total square footage. The program will then compare the two values and print out a line of text appropriately stating whether it is larger or smaller than the other one.
I am not sure where to even begin. I am new to Java and have only done a Hello World
The first thing you have to do is take input from your user of the length and width of the object. Then you must calculate the sqr ft using the formula :
Length * Width = # of Sqr ft
If you want to do this to two houses you will just need to take two inputs for the second house of the length and width and display that homes total area the same way we did to the first house.
import java.util.*;
public class SqrFoot {
public static void main(String[] args) {
//creates a scanner object
Scanner scan = new Scanner(System.in);
//takes input
System.out.println("Enter the length : ");
double length = scan.nextDouble();
System.out.println("Enter the width : ");
double width = scan.nextDouble();
//calculates and displays answer
System.out.println(length*width + " Sqr ft");
}
}
Does this program take input from the user? If it does, you'll want to use a Scanner to accept user input, as such:
Scanner input = new Scanner(System.in);
You can then use the nextDouble() method to input the house dimensions, like so:
double length1 = input.nextDouble();
Then you can calculate the area of each house:
double area1 = length1 * width1;
Finally, you can use an if-else block to compare the two areas. Here's an example of how you could do it:
if (area1 > area2) {
System.out.println("House 1 is larger than house 2.");
} else if (area1 < area 2) {
System.out.println("House 1 is smaller than house 2.");
} else {
System.out.println("House 1 is the same size as house 2.");
}
This sounds like homework, so I'm not going to do it for you, but I will help you with syntax and let you put it all together.
To store a number you need to declare a variable. Variables come in all different types. There is a:
String Which like the name suggests, is a string of characters like "Hello World". To declare a String named hello that contains "Hello World", type the following:
String hello = "Hello World";
Some important things: String is capitalized. You will learn why later, but just remember it for now. The stuff you were storing in hello started with and ended with a ". As you will see, this is only the case for Strings. Finally, like you may already know, almost every line ends with a ;.
char Which is short for character and stores a single letter (or symbol, but worry about that later). To store the letter 'P' in a variable named aLetter, type the following:
char aLetter = 'P';
Some important things: char like the rest of the variable names I will tell you about, is lowercase. Also, a char starts and ends with an '. Next, I stored a capital P which in Java's mind is completely different than a lowercase p (the point I'm trying to make is everything in Java is case sensitive). Finally, even though my variable name aLetter is two words, I didn't put a space. When naming variables, no spaces. ever.
int Which is short for integer. An int stores a whole number (no decimal places) either positive or negative (The largest number an int can hold is around 2 billion but worry about that later). To store the number 1776 in an int named aNumber, type the following:
int aNumber = 1776;
Some important things: this is pretty straightforward, but notice there aren't any "'s or ''s. In Java "1776" is NOT the same as 1776. Finally, I hope you are noticing that you can name variables whatever you want as long as it isn't a reserved word (examples of reserved words are: int, String, char, etc.)
double Which is pretty similar to int, but you can have decimal points now. To store the number 3.14 in a double named aDecimal, type the following:
double aDecimal = 3.14;
boolean Which is a little harder to understand, but a boolean can only have 2 values: true or false. To make it easier to understand, you can change in your head (not in the code) true/false to yes/no. To store a boolean value of true in a variable named isItCorrect, type the following:
boolean isItCorrect = true;
There are tons more, but that is all you have to worry about for now. Now, lets go to math. Math in Java is pretty self explanatory; it is just like a calculator except times is * and divide is /. Another thing to make sure of, is that you are storing the answer somewhere. If you type 5-6; Java will subtract 6 from 5, but the answer wont be saved anywhere. Instead, do the following:
int answer = 0;
answer = 5-6;
Now, the result (-1) will be saved in the int named answer so you can use it later.
Finally, we have decision making. In computer science, you change sentences like "If the person's age is at least 21, let them into the bar. otherwise, don't let them in." In decision making, you need to turn all of your questions into yes/no questions. When you need to decide a yes/no question, use what are called if statements. The way to write if statements are a little weird: you write the word if then you ask your question in parentheses and you don't but a ;. Instead you put a set of curly braces {}, inside which you write your code that will run if the question in the if statement is true. For example, the bar example above would be, in code, the following:
int age = 25;
boolean letHimIn = false;
if(age>=21)
{
letHimIn = true;
}
Now, the question is, how do you ask a question. To do so, you use the following: <,>,<=,>=,==,!=. These are called comparators because they the things on either side of them. They do the following: < checks if the number on the left is less than the number on the right, > checks if the number on the left is greater than the number on the right, <= checks less than or equal, >= checks greater or equal, == checks if the two numbers are equal, and != checks if the two numbers are not equal. So if(age>=21) asks the question, is the number stored in age greater or equal to 21? If so, do the code in curly braces below. If not, then skip the code. As one more example, the code checks if age is exactly equal to 21 and if so, set letHimInTheBar to true.
int age = 25;
boolean letHimInTheBar = false;
if(age==21)
{
letHimInTheBar = true;
}
Since age is equal to 25 not 21, the code to make letHimInTheBar true never ran which means letHimInTheBar. The final thing to know about decisions is you can use a boolean variable to ask a question directly. In the following example, we are only letting people whose age is NOT equal to 30 into the bar and if we let them into the bar we will print "Welcome to the bar." and if we didn't then we will print "Stay away.". As a reminder ! in Java means not. Meaning that it will flip true to false and false to true.
int age = 25;
int badAge = 30;
boolean letHimIn = false;
if(age!=badAge)
{
letHimIn = true;
}
if(letHimIn)
{
System.out.println("Welcome to the bar.");
}
if(!letHimIn)
{
System.out.println("Stay away.");
}

how to compile java code in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert String to code
I need to evaluate a string containing valid Java code
eg. I should be able to get 6 from String code="Math.abs(2*3);";
This sounds like quite an interesting idea, can I ask what the purpose of your application will be?
The best bet is to build up a dictionary of known patterns you will support.
My first idea is that you should create an ArrayList of accepted patterns. So for example:
ArrayList<String> acceptedPatterns = new ArrayList<String>();
acceptedPatterns.add("math.abs");
acceptedPatterns.add("math.acos");
etc.
Then you can evaluate this list when you get hold of the string.
String foundPattern = null;
String myStringFromInput = editText.getText();
for (String pattern : acceptedPatterns){
if (myStringFromInput.contains(pattern){
// we have recognised a java method, flag this up
foundPattern = pattern;
break;
}
}
At this point you would have "Math.abs" in your foundPattern variable.
You could then use your knowledge of how this method works to compute it. I can't think of a super efficient way, but a basic way that would at least get you going would be something like a big if/else statement:
int result = 0;
if (foundPattern.contains("Math.abs"){
result = computeMathAbs(myStringFromInput);
}else if (foundPattern.contains("Math.acos"){
// etc
}
And then in your computeMathAbs method you would do something like this:
private int computeMathAbs(String input){
int indexOfBracket = input.indexOf("(");
int indexOfCloseBracket = input.indexOf(")");
String value = input.subString(indexOfBracket,indexOfCloseBracket);
int valueInt = computeFromString(value);
int result = Math.abs(valueInt);
return result;
}
You could then display the result passed back.
The computeFromString() method will do a similar thing, looking for the * symbol or other symbols and turning this into a multiplication like the abs example.
Obviously this is a basic example, so you would only be able to compute one java method at a time, the complexity for more than one method at a time would be quite difficult to program I think.
You would also need to put quite a bit of error handling in, and recognise that the user might not enter perfect java. Can of worms.
You can use Groovy http://groovy.codehaus.org/api/groovy/util/Eval.html
import groovy.util.Eval;
...
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("a", 2);
params.put("b", 3);
Integer res = (Integer) Eval.me("param", params, "Math.abs(param.a * param.b)");
System.out.println("res with params = " + res);
System.out.println("res without params = " + Eval.me("Math.abs(2*3)"));

Categories

Resources