I want to write a calculator that takes the numbers from text fields and adds them together to give them out in a text area.
It works as far as taking the two numbers from the text fields, but when I add them together it will give out: 1+1=11.
How can I add the two strings so it will equal 2?
This is my source code:
private void ButtonPlusActionPerformed(java.awt.event.ActionEvent evt) {
String Nummer1 = Zahl1.getText();
String Nummer2 = Zahl2.getText();
int intZahl1 = Integer.parseInt(Nummer1);
Integer integerZahl1 = new Integer(Nummer1);
int intZahl2 = Integer.parseInt(Nummer2);
Integer integerZahl2 = new Integer(Nummer2);
Result.setText(Nummer1 + Nummer2);
Result is the name of my text area and the divers Nummers are just variables, as you may have noticed already.
You're adding the Strings not the ints. You will want to add integerZahl1 and intZahl2 instead of Nummer1 and Nummer2.
For example,
int intResult = intZahl1 + intZahl2;
Result.setText(String.valueOf(intResult));
Also as an aside, you'll want to learn and follow Java naming conventions. Variable and method names should start with a lower-case letter, and class names should start with an upper-case letter.
Dom states:
Or you could just do Result.setText(intZahl1 + intZahl2); if you only need to display the result.
Dom, please understand that setText(...) requires a String parameter, not an int, so your method call will not be allowed by the compiler. If one tries the trick of
Result.setText("" + intZahl + intZahl2);
they'd get 11 again. For your technique to work, you'd need to do something like,
Result.setText(String.valueOf(intZahl1 + intZahl2));
Edit
Also you will want to use ints and not Integers.
Related
I want to make this so that short inputs can still be detected, such as "Londo" and "Lon", but want to keep it small and use it without basically copying and pasting the code, any tips? thank you.
if (Menu.answer1.equals("London"))
{
if (location.equals("London")) {
System.out.print(location + " ");
System.out.print(date + " ");
System.out.print(degrees + "C ");
System.out.print(wind + "MPH ");
System.out.print(winddirection + " ");
System.out.print(weather + " ");
System.out.println("");
}
You can use startsWith()
String city = "London";
if (city.startsWith("Lon")) {
// do something
}
Also if you need to check some substring, you can use contains method:
Menu.answer1 = "London";
Menu.answer1.contains("ondo"); // true
If you want to check against a fixed set of alternatives, you may use a list of valid inputs using contains:
List<String> londonNames = Arrays.asList("London", "Londo", "Lon");
if (londonNames.contains(Menu.answer1)) {
...
}
You can use (case-insensitive) regex to do the same, e.g.:
(?)Lon[a-z]{0,3} where
(?) = case insensitivity
Lon = Initial 3 characters
[a-z]{0,3} = any number of alphabets between 0 and 3
Here's an example:
String regex = "(?)Lon[a-z]{0,3}";
System.out.println("London".matches(regex));
System.out.println("Lond".matches(regex));
System.out.println("Lon".matches(regex));
If the underlying problem is that the user can enter one of several names, and you want to allow abbreviations, then a fairly standard approach is to have a table of acceptable names.
Given the user input, loop through the table testing "does the table entry start with the string typed by the user?" (like one of the previous answers here). If yes, then you have a potential match.
Keep looking. If you get a second match then the user input was ambiguous and should be rejected.
As a bonus, you can collect all names that match, and then use them in an error message. ("Pick one of London, Lonfoo, Lonbar").
This approach has the advantage (compared to a long chain of if-then-else logic) of not requiring you to write more code when all you want to do is have more data.
It automatically allows the shortest unique abbreviation, and will adjust when a once-unique abbreviation is no longer unique because of newly-added names.
I am a beginner to Java and have written a 260+ line code, menu-driven, procedural-type program. Unfortunately, I must abide by the rules that pertain to Academic Conduct of my university and I cannot paste what code I have here at this exact moment in time, although I will do my best to explain my conundrum in the hopes that more knowledgeable folk can point me in the right direction. I don't necessarily expect solutions in the form of code. My countless Internet searches have been fruitless and I'm kind of lost and frustrated, even with all my reading materials, countless search query combinations and hours poring over forums, including this one.
Basically, my program is almost finished. It's a reservations system that has a few menus asking for user input. There are a few do-while iterations and conditional statements that allow the user to return back to the main menu once they've entered their inputs, along with some basic error validation.
My main issue is with the final submenu; I enter three values using Scanner (all strings) and I can even print those three values to the console prior to being returned to the main menu. If I enter that same submenu again and enter three different inputs, it overwrites the previous set of inputs. Now, I understand that this is to be expected each time the "nextLine" method is invoked but I must capture each individual set of inputs for a reservations summary at the end of the program.
I've tried to store the values in both single and multidimensional arrays along with for (foreach?) loops but they simply fill up the entire index range with the same three values. I've also tried string concatenation, StringBuilder and ArrayLists but the continuous overwriting of those values makes it near impossible for me to achieve anything meaningful with them. Ideally, I just want to enter the values, preserve them somehow, enter and save more values and then retrieve them all at the very end of the program so I can display them using formatted Strings. The maximum number of entries I can make in the submenu is 10. At the risk of asking a vague question, what method would strike you as being the most suitable here? Once I know what tree I have to bark up, I can simply research my way to an answer. This "100 different ways of reaching the same satisfactory outcome" nature of Java - and dare I say programming languages in general - is rather overwhelming for a beginner like me.
An ArrayList would be suitable for the situation. It allows you to add new items to it dynamically, which is exactly what you are trying to do here, isn't it?
But first, I suggest you encapsulate the "three values" that you kept talking about into a class. From what you said, they represent some information about reservations. I'll call this class Reservation:
class Reservation {
// name these variables properly!
private String someValue1;
private String someValue2;
private String someValue3;
#Override // this returns a formatted string representation of a reservation
public String toString() {
return "someValue1: " + someValue1
+ "\nsomeValue2: " + someValue2
+ "\nsomeValue3: " + someValue3;
}
public Reservation(String someValue1, String someValue2, String someValue3) {
this.someValue1 = someValue1;
this.someValue2 = someValue2;
this.someValue3 = someValue3;
}
}
Now you can create an ArrayList<Reservation>:
// put this outside of any method
static ArrayList<Reservation> reservations = new ArrayList<>();
Whenever the user goes to the submenu, you will do something like this, right?
String someValue1 = scanner.nextLine();
String someValue2 = scanner.nextLine();
String someValue3 = scanner.nextLine();
After those lines, create a Reservation:
Reservation reservation = new Reservation(someValue1, someValue2, someValue3);
And put it into the reservations list:
reservations.add(reservation);
When you want to print all the reservations, you just:
for(Reservation r : reservations) {
System.out.println(r);
System.out.println();
}
Not sure I understand the issue, but it seems like you could add your input values to a List<String[]>
List<String[]> data = new ArrayList<>();
// get your first 3 data, add them to the list
data.add(new String[] {"value 1", "value 2", "value 3"});
// get your first 3 new data, add them to the list
data.add(new String[] {"value 4", "value 5", "value 6"});
Then you can print them out
for(String[] values: data) {
System.out.println(values[0] + " | " + values[1] + " | " + values[2] );
}
Outputs
value 1 | value 2 | value 3
value 4 | value 5 | value 6
I am currently a early CS student and have begun to start projects outside of class just to gain more experience. I thought I would try and design a calculator.
However, instead of using prompts like "Input a number" etc. I wanted to design one that would take an input of for example "1+2+3" and then output the answer.
I have made some progress, but I am stuck on how to make the calculator more flexible.
Scanner userInput = new Scanner(System.in);
String tempString = userInput.nextLine();
String calcString[] = tempString.split("");
Here, I take the user's input, 1+2+3 as a String that is then stored in tempString. I then split it and put it into the calcString array.
This works out fine, I get "1+2+3" when printing out all elements of calcString[].
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
I then convert the integer parts of calcString[] to actual integers by putting them into a integer array.
This gives me "1 0 2 0 3", where the zeroes are where the operators should eventually be.
if (calcString[1].equals("+") && calcString[3].equals("+")) {
int retVal = calcIntegers[0] + calcIntegers[2] + calcIntegers[4];
System.out.print(retVal);
}
This is where I am kind of stuck. This works out fine, but obviously isn't very flexible, as it doesn't account for multiple operators at the same like 1 / 2 * 3 - 4.
Furthermore, I'm not sure how to expand the calculator to take in longer lines. I have noticed a pattern where the even elements will contain numbers, and then odd elements contain the operators. However, I'm not sure how to implement this so that it will convert all even elements to their integer counterparts, and all the odd elements to their actual operators, then combine the two.
Hopefully you guys can throw me some tips or hints to help me with this! Thanks for your time, sorry for the somewhat long question.
Create the string to hold the expression :
String expr = "1 + 2 / 3 * 4"; //or something else
Use the String method .split() :
String tokens = expr.split(" ");
for loop through the tokens array and if you encounter a number add it to a stack. If you encounter an operator AND there are two numbers on the stack, pop them off and operate on them and then push back to the stack. Keep looping until no more tokens are available. At the end, there will only be one number left on the stack and that is the answer.
The "stack" in java can be represented by an ArrayList and you can add() to push items onto the stack and then you can use list.get(list.size()-1); list.remove(list.size()-1) as the pop.
You are taking input from user and it can be 2 digit number too.
so
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
will not work for 2 digit number as your modification is i+=2.
Better way to check for range of number for each char present in string. You can use condition based ASCII values.
Since you have separated your entire input into strings, what you should do is check where the operations appear in your calcString array.
You can use this regex to check if any particular String is an operation:
Pattern.matches("[+-[*/]]",operation )
where operation is a String value in calcString
Use this check to seperate values and operations, by first checking if any elements qualify this check. Then club together the values that do not qualify.
For example,
If user inputs
4*51/6-3
You should find that calcString[1],calcString[4] and calcString[6] are operations.
Then you should find the values you need to perform operations on by consolidating neighboring digits that are not separated by operations. In the above example, you must consolidate calcString[2] and calcString[3]
To consolidate such digits you can use a function like the following:
public int consolidate(int startPosition, int endPosition, ArrayList list)
{
int number = list.get(endPosition);
int power = 10;
for(int i=endPosition-1; i>=startPosition; i--)
{
number = number + (power*(list.get(i)));
power*=10;
}
return number;
}
where startPosition is the position where you encounter the first digit in the list, or immediately following an operation,
and endPosition is the last position in the list till which you have not encountered another operation.
Your ArrayList containing user input must also be passed as an input here!
In the example above you can consolidate calcString[2] and calcString[3] by calling:
consolidate(2,3,calcString)
Remember to verify that only integers exist between the mentioned positions in calcString!
REMEMBER!
You should account for a situation where the user enters multiple operations consecutively.
You need a priority processing algorithm based on the BODMAS (Bracket of, Division, Multiplication, Addition and Subtraction) or other mathematical rule of your preference.
Remember to specify that your program handles only +, -, * and /. And not power, root, etc. functions.
Take care of the data structures you are using according to the range of inputs you are expecting. A Java int will handle values in the range of +/- 2,147,483,647!
So far I have a code that asks for a user input but a part of my code isn't accepting letters as inputs. For example if i type in say woah123 it'll give me a number format exception. Any way to get around this? Error is at the second line int i = Integer.parseInt(sentence).
Sentence is the user input
sentence.replaceAll("\\D", "");
int i = Integer.parseInt(sentence);
i = i * 2 ;
woah.replaceAll("\\d", "" + i);
System.out.println(woah);
Strings are immutable.
Generally, every modification you made on an immutable object will "give" you another immutable object.
So it should be :
sentence = sentence.replaceAll("\\D", "");
Indeed you have to do the same for woah.
You may read about what is an immutable object.
I'm used to python and django but I've recently started learning java. Since I don't have much time because of work I missed a lot of classes and I'm a bit confused now that I have to do a work.
EDIT
The program is suppose to attribute points according to the time each athlete made in bike and race. I have 4 extra tables for male and female with points and times.
I have to compare then and find the corresponding points for each time (linear interpolation).
So this was my idea to read the file, and use an arrayList
One of the things I'm having difficulties is creating a two dimensional array.
I have a file similar to this one:
12 M 23:56 62:50
36 F 59:30 20:60
Where the first number is an athlete, the second the gender and next time of different races (which needs to be converted into seconds).
Since I can't make an array mixed (int and char), I have to convert the gender to 0 and 1.
so where is what I've done so far:
public static void main(String[] args) throws FileNotFoundException {
Scanner fileTime = new Scanner (new FileReader ("time.txt"));
while (fileTime.hasNext()) {
String value = fileTime.next();
// Modify gender by o and 1, this way I'm able to convert string into integer
if (value.equals("F"))
value = "0";
else if (value.equals("M"))
value = "1";
// Verify which values has :
int index = valor.indexOf(":");
if (index != -1) {
String [] temp = value.split(":");
for (int i=0; i<temp.length; i++) {
// convert string to int
int num = Integer.parseInt(temp[i]);
// I wanted to multiply the first number by 60 to convert into seconds and add the second number to the first
num * 60; // but this way I multiplying everything
}
}
}
I'm aware that there's probably easier ways to do this but honestly I'm a bit confused, any lights are welcome.
Just because an array works well to store the data in one language does not mean it is the best way to store the data in another language.
Instead of trying to make a two dimensional array, you can make a single array (or collection) of a custom class.
public class Athlete {
private int _id;
private boolean _isMale;
private int[] _times;
//...
}
How you intend to use the data may change the way you structure the class. But this is a simple direct representation of the data line you described.
Python is a dynamically-typed language, which means you can think of each row as a tuple, or even as a list/array if you like. The Java idiom is to be stricter in typing. So, rather than having a list of list of elements, your Java program should define a class that represents a the information in each line, and then instantiate and populate objects of that class. In other words, if you want to program in idiomatic Java, this is not a two-dimensional array problem; it's a List<MyClass> problem.
Try reading the file line by line:
while (fileTime.hasNext())
Instead of hasNext use hasNextLine.
Read the next line instead of next token:
String value = fileTime.next();
// can be
String line = fileTime.nextLine();
Split the line into four parts with something as follows:
String[] parts = line.split("\\s+");
Access the parts using parts[0], parts[1], parts[2] and parts[3]. And you already know what's in what. Easily process them.