Im having a trouble in java. Im creating a HRRN scheduling. I want to print the integer that I input into a textfield area. Please help me to solve this problem. Thankyou!
private void AWTActionPerformed(java.awt.event.ActionEvent evt) {
int firstprocess=1;
if (bt1.getText().equals("")){
double tempbt1 = Double.parseDouble(bt1.getText());
awttotalprocess = (firstprocess + (tempbt1));
AWTCLICK = 0;
jtf_awt.setText(String.valueOf(awttotalprocess+"ms"));
}
I want to print the awttotalprocess into jtf_awt.
Bracketing issue:
jtf_awt.setText(String.valueOf(awttotalprocess)+"ms");
Many classes come with what's called a .toString() method that prints a pre-specified output when joined with a string. You can concatenate or join a string and a variable -in this case an integer- like this:
int i = 50;
String join() {
return "I'm a string, next is a number: " + 50;
}
Keep in mind that int and Integer are different in that the first is a primitive data type, and the second is the object. This isn't an issue for you in this code but in the future if you try to concatenate a string with an object it may end up printing out the memory address as written in the .toString() default method and would require you to #override the method to specify your own string output. The primitive data types are "easier" to combine and don't require such .toString() overriding or .valueOf() shenanigans.
Related
I have problem, because I have method where I return a variable and I need to compare it, but I don't know how to get it...
My code:
public char setCurrency(String currencyToSet) {
WebElement currencyVal = driver.findElement(By.name(currencyToSet.toUpperCase()));
String currencyName = currencyVal.getText();
System.out.println("Currency Name:" + currencyName);
currencyVal.click();
char[] currencyNameArray = currencyName.toCharArray();
char newCurrencySymbol = currencyNameArray[0];
System.out.println(newCurrencySymbol);
return newCurrencySymbol;
}
public char[] getCurrentCurrencySymbol(){
return currentCurrencySymbol.getText().toCharArray();//string??
}
I want to read in other method newCurrencySymbol.
Updated:
#Test
public void changeCurrency() {
topNav.clickCurrencyDropDown();
char nowa = topNav.setCurrency("eur");
Assert.assertEquals(topNav.getCurrentCurrencySymbol(), nowa);
}
And I get an error:
java.lang.AssertionError: expected [€] but found [[C#74f6c5d8]
should be € but is C#74f6c5d8
But when I print this variable in 8th line, it trow €, but not passing it
I'm changing currency (left top) on enter link description here and want to compare
First of all, you're comparing between a char array (getCurrentCurrencySymbol()) and a char (nowa). Former is an object whereas latter is a primitive data type. When you try to compare the two, you will get some weird values such as C#74f6c5d8 like you see. That's the address of where the char array is actually being stored.
I would suggest that you change from char array to simply a char since they're supposed to be currency notations. This ways, the comparison between the two values will be simplified.
I am fairly new to Java. Over the past few weeks I have been trying to teach myself java. This has been primarily based on tutorials i find online and forums I can find. So keep this in mind and any additional critique you can share is greatly appreciated! I am currently trying to create a calculator that runs off of if-else loops. I'm working on a method that allows the user to derive a function based on the principle that if
f(x)=ax^n+bx^o+cx^p... then f'(x)=anx^n-1+box^o-1+cpx^p-1...
I'm trying to use .split() to separate the parts of the function, perform the changes to the individual parts, and then print them together. I could get most of the way through this but I couldn't convert a string with a negative sign to an integer so I am trying to call a method that uses .substring and then replaceAll to get rid of the negative sign then convert to integer. However, I keep getting a compiling error stating the "actual and formal argument lists differ in length". Can anyone explain why this might be happening?
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class InputInteger
{
public String changeSign(String second) {
String negative = second.substring(0,1);
return negative;
}
public static void splitFunction() {
Scanner o = new Scanner(System.in);
String function = o.next();
String[] parts = function.split("(?=\\+|\\-)");
for (int i = 0; i < parts.length;) {
String[] second = parts[i].split("(?=[0-9]+|[a-z]+|[A-Z]+\\^)");
InputInteger.changeSign();
if (negative = ("-")) {
second = second.replace("-","");
int x = Integer.parseInt(second[0]);
int y = Integer.parseInt(second[2]);
int w = x*y;
int z = y-1;
System.out.println(w + "x^" + z);
i++;
}
}
}
Problem that you are talking about is the method not working . You have to pass argument in the function like
InputInteger.changeSign(function);
or
InputInteger.changeSign(second[i]);
according to requirement
changeSign(String second) should be defined as static
negative variable is not defined
you should compare strings with equals() method
you call .replace(...) on an array, which doesn't have this method
And these are only compile errors, I see at least one runtime problem:
you increase i only in the if which may result in an infinite
loop...
I suggest you use some good IDE like Eclipse or IntelliJ IDEA, which will help you with warnings/errors/etc.
First of all in your code if (negative = ("-")) you have a single "=" and I think you meant to use "==" for comparison. Second, method parseInt() as well as valueOf() (which I prefer to parseInt()) should handle negative numbers just fine. there is no need to remove "-". Yout method changeSign() takes a String argument, also your method ChangeSign() returns String value and you must assign a result to some String: String negative = InputInteger.changeSign(str);. Plus also String class has a method startsWith(String prefix) that fits your better then substring(). Hope this helps. If anything there is an Open source library that provides a Utility for parsing String into Integer (among other things). in That util there is a method
parseStringToInt(String numStr, int defaultValue,
String nullOrEmptyStringErrorMessage, String numberFormatErrorMessage)
That tries to parse a String to Integer and if it does not succeed it returns a default value and never throws an Exception. That method definitely works fine with negative integers. Here is the link to the article about the library.https://www.linkedin.com/pulse/open-source-java-library-some-useful-utilities-michael-gantman?trk=pulse_spock-articles. There you will find the instructions on where to get the library including javadoc and source code.
I am loading strings from a text file, eg;
Sunset Blvd 1950.ogg,Sunset Blvd,Paramount Pictures,1950,110,Billy Wilder,4,William Holden,Gloria Swanson,Erich von Stroheim,Nancy Olson
Now I have a class setup that extends from 2 parent classes (Media > Video > Avi/Ogg/etc). And that class holds the following variables;
public Avi(String title, String fileName, int releaseYear, String studio, String director, String castNames, double runtime, int cast) {
super(title, fileName, releaseYear, studio, director, castNames, runtime, cast);
}
Now I load the text file in using a buffer reader and a loop, but heres the problem, the cast names (Which come last in the text file, are also separated with commas but since I am using a splitter already I am not sure how to get every cast member into a simply string such as "Larry Davis,Eddy Murphy,Etc Etc" that can be returned later on. Also using a different splitter for cast names is not an option
if your cast starts at William Holden, you can do
line.split(",", 8);
I assume that by splitter you mean the String method "split".
If so, does your text file always have the same structure ?
Meaning is there always the same number of elements before the cast names ?
Because the String method "split" can take a second parameter specifying the number of elements to retrieve (cf. link to String API)
None of these solutions worked but heres what I came up with that worked:
String castNames = "";
int splitLength = split.length - 7;
for (int i = 0; i < splitLength; i++) {
castNames += split[7 + i] + ",";
}
Avi avi = new Avi(split[1]/*title*/
, split[0]/*filename*/
, Integer.parseInt(split[3])/*releaseyear*/
, split[2]/*studio*/
, split[5]/*director*/
, castNames/*castnames*/
, Double.parseDouble(split[4])/*runtime*/
, Integer.parseInt(split[6])/*cast*/);
return avi;
Having a symbol as the string separator as well as being valid data is not a good idea and results in code that is prone to errors. Of course you can work around that - some people before me have suggested ways to do it - but I strongly recommend that you change your input and remove the ambiguity.
I'm trying to set an int value using jTextField and the setText method. But of course setText wants a String. How do I get round this? I'll give you a snippet of the code:
private void setAllTextFields(FilmSystem e){
getFilmNameTF().setText(e.getFilmName());
lectureTF.setText(e.getLecture());
ageTF.setText(e.getAge());
priceTF.setText(e.getTicketCost());
seatsTF.setText(e.getNoOfSeats());
seatsTF is a jTextField and getNoOfSeats is a method in another class that returns a int value.
Thanks again for answering this question. Now how would I go about getting the value of the int to do something to do?
public void buyTicket() {
String newFilmName = filmNameTF.getText();
String newLecture = lectureTF.getText();
String newAge = ageTF.getText();
String newPrice = priceTF.getText();
int newSeats = seatsTF.
As you can see the code, the String values I can get easy with getText. I can then print them out or whatever with them. How can I do this with the seats int? Thanks again.
String#valueOf convert your int to String.
String.valueOf(e.getAge()); will return the string representation of the int argument.
seatsTF.setText(String.valueOf(e.Age()));
...
USe
seatsTF.setText(""+e.getNoOfSeats());
OR
seatsTF.setText(String.valueOf(e.getNoOfSeats()));
Normal ways would be
seatsTF.setText(Integer.toString(e.getNoOfSeats()));
or
seatsTF.setText(String.valueOf(e.getNoOfSeats()));
but, this can be achieved with a concatenation like this:
seatsTF.setText("" + e.getNoOfSeats());
Assuming age field is of type int, you could try something like:
ageTF.setText( Integer.toString(e.getAge()) );
Setting an int converting it to a String not a big deal. Displaying a value is a problem. To take care of how the value is displayed properly in the textfield you may use a DecimalFormat to format the numeric value. But may be the number is locale specific then you need NumberFormat instance
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMaximumIntegerDigits(12);
nf.setMaximumFractionDigits(0);
nf.setMinimumFractionDigits(0);
String s = nf.format(e.getNoOfSeats());
seatsTF.setText(s);
You may also need to read the tutorial on how to use the DecimalFormat.
To convert Integer Value to String you should
MedicineTM medicine=tblmedicine.getSelectionModel().getSelectedItem();
txtmedicine.setText(medicine.getMID());
txtDescription.setText(medicine.getDescription());
txtQty.setText(String.valueOf(medicine.getQty())); // this is what i did
cmbApproval.setValue(medicine.getApproval());
I think you should write the code as
seatsTF.setText(e.getNoOfSeats().toString());
I'd like to set a int in a textfield to represent a ID. This int will be incremented when the user clicks the button Next. I'm using awt. I tried to do this but it gives a error because it expects a string. :( Is there a solution?
Thanks
Sounds like you will need to keep an internal int variable which you can increment, then update the textfield with the String representation when it's changed. Similarly make sure to update the int if the user manually edits the textfield.
How about public static String String#valueOf(int)
One can convert an int to a String with either
int i = 100;
String s2 = String.valueOf(i);
String s1 = "" + i;
I believe that valueof() is the preferred approach because it can re-use static data for the value.