I'm new to java and I've developed a program that allows the user to enter his in- and outcome, and also to see a summary of both (second code sample).
I use text files to store the data (first sample). I'm using two text files per user, one for the income and one for the outcome.
Bonus //category
21 //amount
28/12/2015 //date
Salary
13
03/01/2016
Savings Deposit
33
03/01/2016
The following code sample sums up the in- and outcome of the user (Note: opnEsoda is a scanner):
try {
while (opnEsoda.hasNextLine());
do //I read only the lines with the amounts from textfile
{
String[] entry = new String[3];
int x =0;
for (int i = 0; i < 3; i++)
{
if (opnEksoda.hasNextLine())
{
// Trim removes leading or trailing whitespace.
entry[i] = opnEksoda.nextLine().trim();
}
}
x = Integer.parseInt(entry[1]); // converts string numbers to int
sumeksoda += x ; // addition ... Amounts of the txt file
}
while (opnEksoda.hasNextLine());
// information dialog that show the money spent and got.
JOptionPane.showMessageDialog(null,
"You got: "+sumesoda+" €",
"Your stats",
JOptionPane.INFORMATION_MESSAGE,icon);
} catch (FileNotFoundException e) {
System.out.println("COULD NOT READ FILE!!!");
}
This will print: You got 67 €
My goal is to give out the money spent this week and this month. I also want to know the amount of money spent on each category (optional). What is the best way to do that?
To calculate the income for the current month, you must analyze entry[2] (the date) inside the loop, and sum up only those values whose month is the same.
At the beginning of your program, store the current date:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date()); // store the current date
int curYear = cal.get(cal.YEAR );
int curMonth = cal.get(cal.MONTH);
Then, when reading the file, parse the date and compare the year and month:
cal.setTime(new SimpleDateFormat("dd/MM/yyyy").parse(entry[2])); // parse the date
if( cal.get(cal.YEAR)==curYear && cal.get(cal.MONTH)==curMonth ){
x = Integer.parseInt(entry[1]); // converts string numbers to int
sumeksoda += x ; // addition ... Amounts of the txt file
}
To calculate the income from each category, you must analyze entry[0] (the category). If the categories are known in advance, then simply create several distinct sum variables:
int sumeksodaSalary=0;
int sumeksodaBonus=0;
And then, inside the loop:
if("Salary".equals(entry[0])) sumeksodaSalary += x ;
if("Bonus" .equals(entry[0])) sumeksodaBonus += x ;
Related
I want to do the average of 9 textfields and also the sum of them and place them in 2 other textfields by using a button, currently this code doesnt displays anything in the other textfiels. If i put anything, for example "A" instead of "%.Of" it would display the "A" in the textfield but not the average or the sum. Please i need help with a code that would work, dont mind if i need to change a lot.
This is what im working with:
private void jButton_RankingActionPerformed(java.awt.event.ActionEvent evt) {
double R[] = new double [14];
R[0] = Double.parseDouble(jTextField_Math.getText());
R[1]= Double.parseDouble(jTextField_English.getText());
R[2] = Double.parseDouble(jTextField_Spanish.getText());
R[3] = Double.parseDouble(jTextField_Biology.getText());
R[4] = Double.parseDouble(jTextField_Physics.getText());
R[5] = Double.parseDouble(jTextField_Chemestry.getText());
R[6] = Double.parseDouble(jTextField_PE.getText());
R[7] = Double.parseDouble(jTextField_Humanities.getText());
R[8] = Double.parseDouble(jTextField_Technology.getText());
R[9] = (R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8])/ 9;
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
String Average = String.format("%.Of",R[9]);
jTextField_Average.setText(Average);
String TotalScore = String.format("%.Of",R[10]);
jTextField_TotalScore.setText(TotalScore);
if(R[10]>=50)
{
jTextField_Ranking.setText("Superior");
}
else if (R[10]>=41){
jTextField_Ranking.setText("Alto");
}
else if (R[10]>=34){
jTextField_Ranking.setText("Basico");
}
else if (R[10]<=33){
jTextField_Ranking.setText("Bajo");
Since you mentioned that an A would print, it follows that jButton_RankingActionPerformed is being called. The issue you have is the format string you are using to print the total and average. You have mistakenly chosen the capital letter O rather than the number zero.
Replace this (which contains a capital letter O):
String.format("%.Of",R[9]);
With
1) No decimal will be printed: i.e. 50.2 would be 50
String.format("%.0f",R[9]);
2) Or perhaps you want to see one decimal place like 50.2
String.format("%.1f",R[9]);
Also a very small optimization is:
R[9] = (R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8])/ 9;
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
Could be replaced with:
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
R[9] = R[10] / 9;
or use a loop to calculate R[10]. (to add R[0] to R[8])
I'm new to the Java language (Just started about 2 weeks ago)
Basically, the user enters their year/month/day they were born on in order and I use this information to perform a math calculation that will show their age.
I need numbers from 0-9 to be taken in as 01, 02, 03... So, I searched around and found that I can use Decimal.Format and then print out the format later on.
My code crashes whenever it reaches the println(twodigits.format) part no mater where I put it. There are no errors displayed that I need to address.
Why is it doing this and is there a better way to do this? I need it to be 2 digits at all times or the calculation won't work.
Here's a part of my code, I can provide more if needed.
DecimalFormat twodigits = new DecimalFormat("00");
System.out.println("Calculating...");
Integer CurrentDate2 = Integer.valueOf(CurrentDate);
Integer BirthDate2 = Integer.valueOf(BirthDate);
int a = CurrentDate2.intValue();
int b = BirthDate2.intValue();
int age = (a - b) / 1000;
Thread.sleep(300);
System.out.println(".");
Thread.sleep(300);
System.out.println(".");
Thread.sleep(300);
System.out.println(".");
System.out.println(twodigits.format(CurrentDate));
System.out.println(twodigits.format(BirthDate));
Any help is appreciated!
What types are "CurrentDate" and "BirthDate" because it's not clear from your code? You first use them to set "CurrentDate2" and "BirthDate2". And then you use them in the println().
If I were to guess, I'd say they are of type 'String', and 'twodigits.format()' can't handle Strings, which is why it's crashing.
This takes two dates and split time on "/". It then prints them out in the format that you want.
DecimalFormat twodigits = new DecimalFormat("00");
System.out.println("Calculating...");
String CurrentDate = "01/02/2007";
String BirthDate = "02/03/2007";
String[] currentDateParts = CurrentDate.split("/");
String[] birthDateParts = BirthDate.split("/");
int cdp0 = Integer.parseInt(currentDateParts[0]);
int cdp1 = Integer.parseInt(currentDateParts[1]);
int cdp2 = Integer.parseInt(currentDateParts[2]);
int bdp0 = Integer.parseInt(birthDateParts[0]);
int bdp1 = Integer.parseInt(birthDateParts[1]);
int bdp2 = Integer.parseInt(birthDateParts[2]);
//do your calculations
System.out.println(twodigits.format(cdp0));
System.out.println(twodigits.format(cdp1));
System.out.println(twodigits.format(cdp2));
System.out.println(twodigits.format(bdp0));
System.out.println(twodigits.format(bdp1));
System.out.println(twodigits.format(bdp2));
I'm fetching items from database. I have a few Edit Texts and I need to get text from these editable texts and pass that text, update too objects of a List I get from database. I'm getting values from Edit Texts. This is how it looks in code:
String getNasteMonday = etNasteMonday != null ? etNasteMonday.getText().toString() : null;
String getInsulinMondayBeforeBreak = etInsulinMondayBeforeBreak != null ? etInsulinMondayBeforeBreak.getText().toString() : null;
List<Day> days = mDatabase.getAllDaysByWeek(week.getTitle());
double nasteValue = convertStringToDouble(getNasteMonday);
double insulinBeforeBreakValue = convertStringToDouble(getInsulinMondayBeforeBreak);
for (Day day : days) {
day.setNaste(nasteValue);
day.setInsulinBeforeBreak(insulinBeforeBreakValue);
mDatabase.updateDay(day);
}
In this case I have three tables in database, one for storing days, and one for storing weeks and one for storing days by weeks. I'm fetching data in this case by week name and every Week object has 7 days and I need to store different values for each day in that Week. Now, what I'm getting is that in this foreach loop I'm storing the same value for all 7 days and I don't want that. I want to do something like this for example:
for (Day day1 : days) {
day1.setNaste(nasteValue);
}
for (Day day2 : days) {
day2.setNaste(nasteValue2);
}
EDIT:
How to show text in EditText when i have fetched data from database:
I should set text from an array of Strings.
List<String> values = new ArrayList<>();
int[] ids = new int[]{R.id.et_naste_monday, R.id.et_insulin_monday_before_breakf, R.id.et_posle_dorucka_monday, R.id.et_pre_rucka_moday,
R.id.et_insulin_monday_pre_rucka, R.id.et_posle_rucka_monday, R.id.et_pre_vecere_moday, R.id.et_insulin_monday_pre_vecere, R.id.et_posle_vecere_monday,
R.id.et_pred_spavanje_moday, R.id.et_insulin_monday_pred_spavanje};
List<Day> days = mDatabase.getAllDaysByWeek(week.getTitle());
int count = 0;
for (int id : ids) {
EditText t = (EditText) findViewById(id);
values.add(t.getText().toString());
t.addTextChangedListener(this);
applyChangedEditTextColor(false, values, t);
// Here i should implement some logic like and apply for all edittexts
// for (Day day : days) {
//
// }
}
Since you have a lot of EditText to use. I would create some Arrays to store the instance an recover those in a loop.
EditText[] nasteEdit = new EditText[]{ /* your seven instance of editText for naste value in correct order */};
List<Day> days = mDatabase.getAllDaysByWeek(week.getTitle());
int cntDays = 0;
for (Day day : days) {
String getNasteMonday = nasteEdit[cntDays] != null ? nasteEdit[cntDays].getText().toString() : null;
double nasteValue = convertStringToDouble(getNasteMonday);
day.setNaste(nasteValue);
// SAME FOR OTHER ATTRIBUTE
mDatabase.updateDay(day);
cntDays++;
}
During the loop, I get the correct EditText and create the value. I keep you for-iterative loop here and use an external counter but this should work.
You just need to do this for every attributes Day have and this will work.
The array need to have the instance of the EditText, so don't waste you time to get the text of each ;)
Hope this will work, I can't test it write now.
I have found a solution. The better approach would be to use regular for loop and using method get() from List, for getting the position of element in a list.
for (int i = 0; i < days.size(); i++) {
Day day1 = days.get(0);
day1.setNaste(3.0);
Day day2 = days.get(1);
day2.setNaste(2.0);
Day day3 = days.get(2);
Day day4 = days.get(3);
Day day5 = days.get(4);
Day day6 = days.get(5);
Day day7 = days.get(6);
}
If you need to update some data from database then you will declare object Day outside the for loop and call that object in update method from database:
database.updateDay(day1);
database.updateDay(day2);
Complete newbie here guys. I'm working on a Java program to prompt the user for 3 variables which are used to calculate a future investment's value. Everything works perfectly, except when it comes time to put both my datatypes into ONE array.
Here's what the output SHOULD look like:
Year Future Value
1 $1093.80
2 $1196.41
3 $1308.65
...
This is what mine looks like:
Year 1
Future Value 1093.81
Year 2
Future Value 1196.41
Year 3
Future Value 1308.65
...
My year is an int value and my Future value is a double (rounded). I've been sitting here racking my brain and all the forums I can find and haven't been successful. Every time I put both value into an array I get an error about putting two different datatypes together. Any insight would be greatly appreciated. Below is the code for my full program:
import java.util.Scanner;
class investmentValue {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter investment amount: $");
double i = s.nextDouble();
System.out.print("Enter percentage rate: ");
double r = s.nextDouble()/100;
System.out.print("Enter number of years: ");
int y = s.nextInt();
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.println("Year " + y);
System.out.println("Future Value " + f);
}
}
public static double futureInvestmentValue (double investmentAmount, double monthlyInterestRate, int years){
double value=1;
value = investmentAmount*Math.pow((1+(monthlyInterestRate/12)),(years * 12));
double roundValue = Math.round(value*100.0)/100.0;
return roundValue;
}
}
One solution is to start by implementing a pad function. Something like,
public static String pad(String in, int len) {
StringBuilder sb = new StringBuilder(len);
sb.append(in);
for (int i = in.length(); i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
Now we can combine that with String.format() to get the dollars and cents, use a consistent printf() for the header and output lines. To get something like,
// Print the header.
System.out.printf("%s %s%n", pad("Year", 12), "Future Value");
for (int y = 1; y <= 30; y++) {
String year = pad(String.valueOf(y), 13); // <-- One more in your alignment.
String fv = String.format("$%.2f", futureInvestmentValue(i,r,y));
System.out.printf("%s %s%n", year, fv);
}
The System.out.println command isn't the only method available to you!
Try this in your loop:
System.out.print(y); // note that we use print() instead of println()
System.out.print('\t'); // tab character to format things nicely
System.out.println(f); // ok - now ready for println() so we move to the next line
Naturally, you'll want to do something similar to put your headings in.
PS - I'm pretty sure this is just an output formatting question - you don't really want to put all these values into a single array, right?
Given that you really are looking for formatted output, it may be better to use the printf() method.
The following inside the loop (instead of the 3 lines I wrote above) should do the trick (untested - I haven't used printf() format strings in a long, long time).
System.out.printf("%i\t$%0.2f", y, f);
EDIT: edited to answer your question in the comments about constructors... You should also check out this for further understanding
You could create a class that will hold both of the arrays...
This would give you a single object, let's call it StockData, that holds two arrays for the two separate types you need. You need to create the object once and then insert the data separately by type.
class StockData {
double[] data1;
int[] data2;
// default constructor
StockData() {
}
// constructor
StockData(double[] data1, int[] data2) {
this.data1 = data1;
this.data2 = data2;
}
// getters, setters...
}
Then you add data to an array of its type:
// using default constructor to add a single value to both arrays
StockData sd = new StockData();
sd.data1[INDEX_X] = YOUR_DOUBLE;
sd.data2[INDEX_X] = YOUR_INT;
// using default constructor to add all data to both arrays
StockData sd = new StockData();
sd.data1 = YOUR_ARRAY_OF_DOUBLE;
sd.data2 = YOUR_ARRAY_OF_INTS;
// using constructor to add all array data directly
StockData sd = new StockData(YOUR_ARRAY_OF_DOUBLE, YOUR_ARRAY_OF_INTS);
You could also have an object that will hold the double and int value, so the object will represent a single stock information of 2 values and then create an array containing those objects...
class StockData {
double data1;
int data2;
// default constructor same as before
// constructor
StockData(double data1, int data2) {
this.data1 = data1;
this.data2 = data2;
}
// getters, setters...
}
// ...
Adding data:
// create an array of StockData objects
StockData[] sd = new StockData[TOTAL_AMOUNT_OF_DATA];
// ... obtain your data
// using default constructor to add a single value to the array
sd[INDEX_X] = new StockData();
sd[INDEX_X].data1 = YOUR_DOUBLE;
sd[INDEX_X].data2 = YOUR_INT;
// using constructor to add all data directly
sd[INDEX_X] = new StockData(YOUR_DOUBLE, YOUR_INT);
If you want the program to have an specific format you could try to change your code and put this where your for is:
System.out.println("Year Future Value");
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.print(y);
System.out.println(" " + f);
}
this way you will have your output in the format you need without using arrays. But if you want to do an array for this you could declare an array of objects and create a new object with two attributes (year and future value)
Also your class name is investmentValue and it is recommended that all classes start with upper case it should be InvestmentValue
I hope that this can help you
A fun data structure you would be able to use here is a Map (more specifically in Java, a HashMap). What you are doing is associating one value with another, an integer to a double, so you could make something that looks like this:
Map<Integer, Double> myMap = new HashMap<>();
This would take the year as the integer, and the double as the price value, and you could iterate over the map to print each value.
Additionally if you really are looking for a "multidata type array," Java automatically casts from integer to double should you need to. For example:
int i = 2;
double[] arr = new double[2];
arr[0] = 3.14
arr[1] = i;
The above code is perfectly valid.
I've created a program that allows a user to enter in Journal entries (up to 7 days) and then allows a person to call up one of those days after they enter in an entry. Unfortunately, this has left me with some weird string error that I'm not familiar with.
Code as follows:
public class eDiary{
public static void main (String args[]){
int[] days = new int[7];//get our days
days[0] = 1;//start with 1 and not 0
days[1] = 2;
days[2] = 3;
days[3] = 4;
days[4] = 5;
days[5] = 6;
days[6] = 7;
String [] events = new String[7];//events for the days
int i = 0;
//asks for input and counts
for(i=0; i<7; i++){
String event = Console.readString("Tell me the major event of day " + days[i] + "\n");
events[i] = event;
}
int journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
while (journal_entry != 0) {
System.out.println(events);
journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
//get r dun!
The input and output:
Tell me the major event of day 1
one
Tell me the major event of day 2
two
Tell me the major event of day 3
thre
Tell me the major event of day 4
four
Tell me the major event of day 5
five
Tell me the major event of day 6
six
Tell me the major event of day 7
seven
Enter what day you want to hear or Enter 0 to stop
1
[Ljava.lang.String;#10181f5b
Enter what day you want to hear or Enter 0 to stop
0
Howdy y'all!
Thanks a lot for the quick responses. One thing it seems to be doing now is when replacing
System.out.println(events);
with
System.out.println(events[journal_entry]);
Now gives me input such as this:
Tell me the major event of day 1
first day
Tell me the major event of day 2
second day
Tell me the major event of day 3
third day
Tell me the major event of day 4
fourth day
Tell me the major event of day 5
fifth day
Tell me the major event of day 6
sixth day
Tell me the major event of day 7
seventh day
Enter what day you want to hear or Enter 0 to stop
1//the day im asking for
second day//spitting out the next day's entry instead of the first day's entry
Enter what day you want to hear or Enter 0 to stop
0//this is me stopping it
It's not an error.
System.out.println(events);
In this line you are trying to print the array, but that statement doesn't print the array contents, it only prints the object class name followed by its hashcode.
To print the array content you have to use
System.out.println(Arrays.toString(events));
Or, if you want, loop through the array and print its values
The [Ljava.lang.String;#10181f5b stuff is what you get when you explicitly or implicitly call Object.toString() and the target object's class doesn't override toString(). In this case, the issue is that Java array types do not override toString().
If you want to output an array, use java.util.Arrays.toString(...) to convert it to a String, then output that.
But in this case, you actually need to output a specific entry, not the entire array. The fix is to change
System.out.println(events);
to
System.out.println(events[journal_entry]);
For the record, the stuff above consists of the classes internal name ("[Ljava.lang.String;") and the object's identity hashcode (in hexadecimal).
This is not a "weird error string".
The output you are getting is because:
In Java, each object has toString() method, the default is displaying the class name representation, then adding # and then the hashcode.
You should use Arrays#toString(), which is implemented this way:
3860 public static String toString(int[] a) { {
3861 if (a == null)
3862 return "null";
3863 int iMax = a.length - 1;
3864 if (iMax == -1)
3865 return "[]";
3866
3867 StringBuilder b = new StringBuilder();
3868 b.append('[');
3869 for (int i = 0; ; i++) {
3870 b.append(a[i]);
3871 if (i == iMax)
3872 return b.append(']').toString();
3873 b.append(", ");
3874 }
3875 }
This will help you to better understand arrays.
Of course you can manually loop on the array and print it:
for(String event: events) {
System.out.println(event);
}
There is nothing wrong and that's not an error message.
Instead, it's the string representation of an array. Consider this line:
System.out.println(events);
You are printing the whole array, so you get that representation -- which happens to be a bit ugly, indeed. You want to print only one element, the one corresponding to the selected day. Use:
System.out.println(events[journal_entry]);
And perform bound checks.
This is not an error. You want to print the value of variable events. [Ljava.lang.String;#10181f5b means that events is an array of type java.lang.String and 10181f5b is hashcode of this variable. What you want to println is event[i] where i is the number of a day.
In java array's are consider as object. you are printing the event array object that's not what you want.
You need to print name of the day in a week. You need to replace
System.out.println(events);
to
System.out.println(events[journal_entry]);
It won't print out the answer correctly because you just pointed System.out.println() to events which is supposed to be an array pointer and not the actual variable. You should just replace this line with
System.out.println(events[journal_entry]);
For it to make sense. Run it with the conmmand and see if it will run properly.
Thanks for all the responses! I was able to resolve the issue. Here's the code if anyone is curious:
public static void main (String args[]){
int[] days = new int[7];//get our days
days[0] = 1;//start with 1 and not 0
days[1] = 2;
days[2] = 3;
days[3] = 4;
days[4] = 5;
days[5] = 6;
days[6] = 7;
String [] events = new String[7];//events for the days
int i = 0;
//asks for input and counts
for(i=0; i<7; i++){
String event = Console.readString("Tell me the major event of day " + days[i] + "\n");
events[i] = event;
int journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
while (journal_entry != 0) {
System.out.println("On day " + days[i = 0] + " " + events[journal_entry - 1]);
journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");