I am developing an Application in Android Studio to that prints how many of each item you can buy with the given amount of currency. It printed flawlessly when run as a Java program in Eclipse but I can not get it to print more than one line in the TextView Box.
I've noticed it will pick the most Expensive item you can afford 1 of and print it alone, leading me to believe it runs through the list and only prints the last one that passes as affordable. I've read about needing to use a StringBuilder and such but have found little information on how to convert my Array.asList over to this. Here is my code.
gCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText diamondInput = (EditText) findViewById(R.id.diamondInput);
try {
int diamonds = Integer.parseInt(diamondInput.getText().toString());
List<Gifts> gift = Arrays.asList(new Gifts[]{new Gifts("Gold star", 10), new Gifts("Love Bear", 10), new Gifts("Lillies", 10), new Gifts("Box Of Chocolate", 20), new Gifts("Taco", 20), new Gifts("Thumbs Up", 30), new Gifts("Panda", 40), new Gifts("Beer", 40), new Gifts("Patriot", 52), new Gifts("Eagle", 52), new Gifts("Gold Chain", 80), new Gifts("Roses", 100), new Gifts("Champagne", 100), new Gifts("Snow", 100), new Gifts("Candy", 100), new Gifts("Kiss", 200), new Gifts("Candy Hearts", 250), new Gifts("Peach", 300), new Gifts("EggPlant", 300), new Gifts("Fireworks", 500), new Gifts("GemDrop", 600), new Gifts("Crown", 600), new Gifts("Cupcakes", 700), new Gifts("Heart Balloon", 800), new Gifts("Sports Car", 1000), new Gifts("Smoke Rings", 1000), new Gifts("purple Diamond", 2500), new Gifts("Cupid", 5000), new Gifts("Gold Watch", 5000), new Gifts("Castle", 5000), new Gifts("Yacht", 10000), new Gifts("Jet", 20000)});
double coins = (double) diamonds / 2.5D;
Iterator var5 = gift.iterator();
while(var5.hasNext()) {
Gifts Gifts = (Gifts)var5.next();
int qty = (int)Gifts.getQty(coins);
if(qty > 0) {
result.setText("You can buy " + qty + " " + Gifts.name);
}
}
}
catch (Exception e) {
// friendly error to the user: field is incorrect
}
I need it to print as this EX:
You can buy X amount of Y
You can buy X amount of Y
You can buy X amount of Y
:end
Printing every item that can be bought and it's quantity.
If you look into Android API documentation (https://developer.android.com/reference/android/widget/TextView.html) , this is what it states:
void setText (CharSequence text) - sets the text to be displayed. - this means that each time you call this method, new text overrides the old one.
It seems that you are looking for append() method:
void append(CharSequence text) - convenience method to append the specified text to the TextView's display buffer, upgrading it to EDITABLE if it was not already editable. append() method doesn't override previously set text.
Another way to append text to the previously stored in TextView is to combine these methods:
result.setText(result.getText() + "text that you want to append to the previous one")
Related
I am currently making a tip calculator and I have hit a wall. My textbook, Big Java, Late Objects, did not have the answer. I scoured stack overflow and a bit of Reddit too but I was only able to partially solve my dilemma. I feel as though I am on the right track. The issue lies within the lambda expression calcTipClick connected to the calculateTipButton. EDIT How can I use the user input from the slider, split check, and checkAmtTextField to do my calculations of the GUI. Sorry
public class TipCalcApp extends Application {
// declare interface controls
Label titleLabel, checkAmtLabel, tipPercentLabel, splitLabel, tipAmtLabel;
Label totalLabel, amtPerPersonLabel;
TextField checkAmtText, tipAmtText, totalText, amtPerPersonText;
Slider tipPercentSlider;
ChoiceBox splitChoiceBox;
Button calcTipButton;
// declare a grid pane (8 rows and 2 columns)
GridPane grid;
#Override
public void start(Stage primaryStage) {
// instantiate labels and their properties
titleLabel = new Label("Tip Calculator");
titleLabel.setMaxWidth(Double.MAX_VALUE);
titleLabel.setAlignment(Pos.CENTER);
checkAmtLabel = new Label("Check Amount");
checkAmtLabel.setMaxWidth(Double.MAX_VALUE);
checkAmtLabel.setAlignment(Pos.CENTER_RIGHT);
tipPercentLabel = new Label("Tip Percent: ");
tipPercentLabel.setMaxWidth(Double.MAX_VALUE);
tipPercentLabel.setAlignment(Pos.CENTER_RIGHT);
splitLabel = new Label("Split");
splitLabel.setMaxWidth(Double.MAX_VALUE);
splitLabel.setAlignment(Pos.CENTER_RIGHT);
tipAmtLabel = new Label("Tip Amount");
tipAmtLabel.setMaxWidth(Double.MAX_VALUE);
tipAmtLabel.setAlignment(Pos.CENTER_RIGHT);
totalLabel = new Label("Total");
totalLabel.setMaxWidth(Double.MAX_VALUE);
totalLabel.setAlignment(Pos.CENTER_RIGHT);
amtPerPersonLabel = new Label("Amount Per Person");
amtPerPersonLabel.setMaxWidth(Double.MAX_VALUE);
amtPerPersonLabel.setAlignment(Pos.CENTER_RIGHT);
// instantiate text fileds and their properties
checkAmtText = new TextField();
tipAmtText = new TextField();
tipAmtText.setEditable(false);
totalText = new TextField();
totalText.setEditable(false);
amtPerPersonText = new TextField();
amtPerPersonText.setEditable(false);
// instantiate a slider and its properties
tipPercentSlider = new Slider();
tipPercentSlider.setPrefWidth(300);
tipPercentSlider.setMin(0);
tipPercentSlider.setMax(25);
tipPercentSlider.setMajorTickUnit(5);
tipPercentSlider.setMinorTickCount(0);
tipPercentSlider.setBlockIncrement(5);
tipPercentSlider.setShowTickLabels(true);
tipPercentSlider.setShowTickMarks(true);
tipPercentSlider.setSnapToTicks(true);
tipPercentSlider.setOrientation(Orientation.HORIZONTAL);
tipPercentSlider.valueProperty().addListener(
(observable, oldvalue, newvalue) ->
{
// show integer values only
tipPercentLabel.setText(String.format("Tip Percent: %2d%s", newvalue.intValue(), "%"));
});
// instantiate a choice box and its properties
splitChoiceBox = new ChoiceBox();
splitChoiceBox.getItems().addAll("1", "2", "3", "4", "5");
splitChoiceBox.setValue("1");
// instantiate a button and its properties
calcTipButton = new Button("Calculate Tip");
calcTipButton.setMaxWidth(Double.MAX_VALUE);
calcTipButton.setOnAction(e -> calcTipClick());
// instantiate a grid pane and its properties
grid = new GridPane();
grid.setHgap(15);
grid.setVgap(15);
grid.setPadding(new Insets(10));
grid.add(titleLabel, 0, 0, 2, 1);
grid.addRow(1, checkAmtLabel, checkAmtText);
grid.addRow(2, tipPercentLabel, tipPercentSlider);
grid.addRow(3, splitLabel, splitChoiceBox);
grid.add(calcTipButton, 0, 4, 2, 1);
grid.addRow(5, tipAmtLabel, tipAmtText);
grid.addRow(6, totalLabel, totalText);
grid.addRow(7, amtPerPersonLabel, amtPerPersonText);
// instantiate the grid pane and put items in in grid
Scene scene = new Scene(grid);
scene.getRoot().setStyle("-fx-font: 15 'Comic Sans MS'");
primaryStage.setTitle("Tip Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
private void calcTipClick() {
//Gather choiceBox
String choiceInput = splitChoiceBox.getValue().toString();
int choiceSelection = Integer.parseInt(choiceInput.substring(0, 1));
//Gather Slider information
String sliderInput;
sliderInput = tipPercentLabel.getValue().toString();
int sliderSelection = Integer.parseInt(sliderInput.substring(0, 1));
//Gather textField amount
}
Not sure if this is what you are asking, but this is an idea of how you can calculate the tip and split it in your calcTipClick() method. You should look at formatters to ensure format, rounding, etc. But this should give you the general idea.
private void calcTipClick() {
//Gather choiceBox
String choiceInput = splitChoiceBox.getValue().toString();
int choiceSelection = Integer.parseInt(choiceInput.substring(0, 1));
//Gather Slider information
Number sliderInput = tipPercentSlider.getValue();
//Gather textField amount
String val = checkAmtText.getText();
NumberStringConverter nsc = new NumberStringConverter();
Number amount = 0;
try {
amount = nsc.fromString(val);
}catch (Exception pe) {
//Need to handle a parse error if the user isn't entering numbers
//Should look at text formatters to ensure amount is only entered valid
amount = 0;
}
Number tipAmount = amount.doubleValue() * sliderInput.doubleValue()/100;
tipAmtText.setText(tipAmount.toString());
Number totalAmount = tipAmount.doubleValue() + amount.doubleValue();
totalText.setText(totalAmount.toString());
Number perPerson = totalAmount.doubleValue() / choiceSelection;
amtPerPersonText.setText(perPerson.toString());
}
I've added a GraphView object and populated it with some data as per the example in the documentation on the website. While I've found out how to change the background colour of the GraphView, I have no idea how to change the grid colour. Any ideas?
This is what I've tried:
public void createGraph(View view){
GraphView graph = (GraphView) view.findViewById(R.id.graph);
GridLabelRenderer gridLabelRenderer = graph.getGridLabelRenderer();
// This works
graph.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
// This does not work
gridLabelRenderer.setGridColor(getResources().getColor(android.R.color.holo_green_light));
// Nor does this
//gridLabelRenderer.setGridColor(15);
// This works
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] {
new DataPoint(0, 1),
new DataPoint(1, 5),
new DataPoint(2, 3),
new DataPoint(3, 2),
new DataPoint(4, 6)
});
graph.addSeries(series);
}
try
graph.getGridLabelRenderer().reloadStyles();
styling example it here
https://github.com/appsthatmatter/GraphView-Demos/blob/master/app/src/main/java/com/jjoe64/graphview_demos/examples/StylingColors.java
I'm searching for a library or an example on how to implement in java a likelihood ratio test like in matlab.
I have two different vector of double values and want to receive a scalar value.
Every value correspond to a feature for my machine learning algorithm so one the first vector is the training pattern and the second one a test.
Could you please help me?
On matlab i just use division on two matrix like LR= test_matrix/training_matrix
I've tryied with apache mahout but i'm not sure i'm using it correctly.
Here the code:
FastByIDMap<FastByIDMap<Long>> timestamps = new FastByIDMap<>();
Collection<Preference> prefs = new ArrayList<>(2);
FastByIDMap<Collection<Preference>> data = new FastByIDMap<>(); //Preferecens for user0
Preference newPrefs = new GenericPreference(0, 0, (float) -0.5);
Preference pref = new GenericPreference(0, 1, 50);
Preference pref2 = new GenericPreference(0, 2, 51);
prefs.add(newPrefs);
prefs.add(pref);
prefs.add(pref2);
data.put(0, prefs);
Collection<Preference> prefs_1 = new ArrayList<>(2);
newPrefs = new GenericPreference(1, 0, (float) -0.5);
pref = new GenericPreference(1, 1, 50);
pref2 = new GenericPreference(1, 2, 51);
prefs_1.add(newPrefs);
prefs_1.add(pref);
prefs_1.add(pref2);
data.put(1, prefs_1);
GenericDataModel model = new GenericDataModel(GenericDataModel.toDataMap(data, true), timestamps);
FastByIDMap<PreferenceArray> us = model.getRawUserData();
System.out.println("us:"+ us.toString());
LogLikelihoodSimilarity l = new LogLikelihoodSimilarity(model);
System.out.println(l.userSimilarity(0, 1));
In this case, user similarity alwasy return 0.
I'm pretty new to java and what i'm trying to do is make a model for a catalog storing available products in a computer parts shop, using collections. My instructor asked for one instance of each product in the catalog. This is what i came up with:
import java.util.*;
public class AvailablesCatalog {
public AvailablesCatalog(List cat1) {
cat1 = new ArrayList();
Motherboard item1 = new Motherboard("MD4652", 1995, "Lenovo", 100.50, "Intel", 32, 5);
CPU item2 = new CPU("MD4652", 1995, "Lenovo", 100.50, 2.9, 6);
Graphics item3 = new Graphics("MD4652", 1995, "Lenovo", 100.50, "AMD", 6);
RAM item4 = new RAM("MD4652", 1995, "Lenovo", 100.50, "DDR2", 4, 1600);
HD item5 = new HD("MD4652", 1995, "Lenovo", 100.50, "SSD", 2.5, 750);
Monitor item6 = new Monitor("MD4652", 1995, "Lenovo", 100.50, "LED", 17.5, "1920x1080", "HDMI");
Keyboard item7 = new Keyboard("MD4652", 1995, "Lenovo", 100.50, "Wireless");
Mouse item8 = new Mouse("MD4652", 1995, "Lenovo", 100.50, "Laser", "Wireless");
Printer item9 = new Printer("MD4652", 1995, "Lenovo", 100.50, "Laser", "Colored");
cat1.add(item1);
cat1.add(item2);
cat1.add(item3);
cat1.add(item4);
cat1.add(item5);
cat1.add(item6);
cat1.add(item7);
cat1.add(item8);
cat1.add(item9);
}
public String toString(List cat1, int i) {
for(i=0; i<cat1.size(); i++) {
System.out.println(cat1.get(i).toString());
}
return "----------------------------------------------------";
}
}
Now, through the shop's mainApp that i'm using to to print the catalog, i have stored an instance of the AvailablesCatalog object type in a variable called av. This is the mainApp:
public class mainApp {
public static void main(String[] args){
/* Variables for Menu System and Sub Menu System */
int MainMenu;
String SubMenu;
String ReturnToMenu;
String SubMenuReturnToMenu;
List cat1 = new ArrayList();
AvailablesCatalog av = new AvailablesCatalog(cat1);
/* Displays menu system to console */
System.out.println("..............MENU...............");
System.out.println("..............1 View All Available Products..............");
System.out.println("..............2 View Orders...................");
System.out.println("..............3 View Sales...................");
System.out.println("..............0 Exit...................");
System.out.print("Please select an option: ");
Scanner sc = new Scanner(System.in);
MainMenu = sc.nextInt();
if(MainMenu == 1){
for(int i = 0; i < cat1.size(); i++) {
System.out.println(av.toString(cat1, i));
}
}
else if(MainMenu == 2) {
System.out.println("lol");
}
else if(MainMenu == 3) {
System.out.println("lol3");
}
else if(MainMenu == 4) {
System.exit(0);
}
}
}
Everything compiles smoothly, and when i run mainApp the menu shows up correctly. But when i press 1 to print the available products catalog, the programm simply ends. Options 2 and 3 are simply placeholders for now btw. Thanks in advance.
You are using two different Lists in your program.
The first one is cat1in your main method (is empty)
The second in your constructor (is filled in the constructor)
You override the reference with the new created list in the constructor and fill that one instead. This is garbage collected after the constructor is finished and no reference is pointing on it.
In the toString method you are printing the the list that is passed via parameter which is the one from main (and empty).
Remove the cat1 = new ArrayList(); line from the constructor. Then it should work.
I'm getting a "TableView(ScrollView).calculateVerticalScrollAmount(XYRect)" exception when trying to create a table using the following code. I've tried simplifying the fields, but nothing seems to help, any thoughts? The code is similar to that in the Tables Demo supplied with the BB 6 SDK.
It looks like a layout issue, but I can't seem to pin down the error.
// Create and apply style
RegionStyles style = new RegionStyles(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 1), Border.STYLE_SOLID), null, null,
null, RegionStyles.ALIGN_LEFT, RegionStyles.ALIGN_TOP);
// Create the view and controller
TableView tableView = new TableView(_tableModel);
TableController tableController = new TableController(_tableModel, tableView);
// Set the controller focus policy to highlight rows
tableController.setFocusPolicy(TableController.ROW_FOCUS);
// Set the behaviour of the controller when a table item is clicked
tableController.setCommand(new CommandHandler()
{
/**
* #see CommandHandler#execute(ReadOnlyCommandMetadata, Object)
*/
public void execute(ReadOnlyCommandMetadata metadata, Object context)
{
Dialog.alert("Command Executed");
}
}, null, null);
tableView.setController(tableController);
// Create a DataTemplate that suppresses the third column
DataTemplate dataTemplate = new DataTemplate(tableView, 2, 3)
{
/**
* #see DataTemplate#getDataFields(int)
*/
public Field[] getDataFields(int modelRowIndex)
{
Object[] data = (Object[]) ((TableModel) getView().getModel()).getRow(modelRowIndex);
Field[] fields = new Field[4];
fields[0] = new BitmapField((Bitmap) data[0]);
fields[1] = new LabelField(data[1], Field.FOCUSABLE);
fields[2] = new LabelField(data[2], Field.FOCUSABLE);
fields[3] = new LabelField(data[3], Field.FOCUSABLE);
return fields;
}
};
// Set up regions
dataTemplate.createRegion(new XYRect(0, 0, 1, 2), style);
dataTemplate.createRegion(new XYRect(1, 0, 2, 1), style);
dataTemplate.createRegion(new XYRect(1, 1, 1, 1), style);
dataTemplate.createRegion(new XYRect(2, 1, 1, 1), style);
// Specify the size of each column by percentage, and the height of a row
dataTemplate.setColumnProperties(0, new TemplateColumnProperties(15, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setColumnProperties(1, new TemplateColumnProperties(15, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setColumnProperties(2, new TemplateColumnProperties(70, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setRowProperties(0, new TemplateRowProperties(ROW_HEIGHT));
dataTemplate.setRowProperties(1, new TemplateRowProperties(ROW_HEIGHT));
// Apply the template to the view
tableView.setDataTemplate(dataTemplate);
dataTemplate.useFixedHeight(true);
add(tableView);
Not sure if you are still struggling with this - may be benefits for others
in the statement
DataTemplate dataTemplate = new DataTemplate(tableView, 2, 3)
you have initialized the DataTemplate with 2 rows and 3 columns (assuming you want to suppress 4th column). But inside the function getDataFields you are returning 4 fields.
This is causing the crash (the internal code is not monkey proof).
Drop the 4th field from array and it should work.