getFont() method - java

I just wanted to ask a question about the getFont() method, which is in java.awt.Font. I don't understand why the getStyle() is undefined for type string, although it actually should work with strings. In API it says it takes an integer as argument.
import java.awt.Font;
//import java.util.*;
public class NotEqual
{
public static void main(String[] args)
{
//Scanner input = new Scanner(System.in);
//System.out.println("Write something ");
String sentence = "The sentence";
//int x = 2;
//System.out.println(sentence.getFont());
//System.out.println(sentence.getSize());
//System.out.println(sentence.getStyle());
System.out.println(sentence.getFont());
}
}

Style is a integer, defined by the constants Font.PLAIN, Font.BOLD, or Font.ITALIC.
From the docs:
Returns the style of this Font. The style can be PLAIN, BOLD, ITALIC, or BOLD+ITALIC.
It is never a string. A string is not one of the accepted values. (It never has been.)

Your code won't work because Strings don't have fonts. Period. All they are are lists of chars with supporting methods and properties, but no font. To see what methods you can call on String, look at the API as that is the final arbitrator of what you can and cannot do with them. In fact, if you search the text of the String API, you won't even find the word "font" present anywhere.
I still don't understand the part about it "In API it says it takes an integer as argument" though.

One reason might be that the int return value is easier to interpret than either BOLD+ITALIC or ITALIC+BOLD (same style, same int, different String).
Noting also that arguments can be overloaded but return types cannot, it could be argued that the int is the better value to return.

Related

What happens if the first letter of a method in a java program is a capital / upper case letter?

I am aware that in Java language, the first letter of a method should desirably be lower case, but what happens if it becomes a capital letter?
I tried changing the first letter of the methods in my program to capital letters, but it made no difference.
import java.util.Scanner;
class Replace3meth
{
String str, newstr;
int len, vcount;
public void Accept()
{ // obtaining input
System.out.println("\f");//clearing the screen
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
str = sc.nextLine();
str = str.toLowerCase();
} // accept() method ends
public void ReplaceVowel()
{
len = str.length();
newstr = "";
vcount = 0;
char c;
for (int i = 0; i < len; i++)
{ // finding no. of vowels
c = str.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
c = Character.toUpperCase(c);
vcount++;
} // if function ends
newstr = newstr + c;
} // for loop ends
} // replaceVowel() method ends
public void Display()
{ // printing output
System.out.println("Original sentence:" +str);
System.out.println("New sentence: "+newstr);
System.out.println("No. of vowels: "+vcount);
} // display() method ends
public static void Main()
{ // calling all methods
Replace3meth obj = new Replace3meth();
obj.Accept();
obj.ReplaceVowel();
obj.Display();
} // main() method ends
} // class ends
This is a simple program to convert all the vowels in a sentence to upper case. Even after changing all the method names to start with a capital letter, the program worked properly.
PS: I use BlueJ (not VSCode), so I can used main() instead of main(String[] args)
Method names don't have to start with a lower case letter. It's just a shared convention so all developers are on the same page and people reading your code don't have to add extra cognitive load to quickly parse it.
Method names are case-sensitive, though. So if, for any reason, a name is expected to have a certain case it has to be respected.
One example is methods that need to be implemented because they are declared in an interface or abstract class (if the method you have to implement is called doStuff you can't implement it as DoStuff or dostuff).
Another example is the main method, which is the method the JVM expects to call when you run a class. It has to maintain the same case (and the fact that it has to be public, static, void and have an array of strings as its only argument), so you can't call it Main or MaiN. But that is a requirement of the JVM, not of the language.
Nothing happens, the code will still compile. You can name your methods getName, GETname, getNAME, GETNAME, or GeTnAmE and the compiler will not care.
Who will care however are human people reading and trying to understand the code. Make it easy for your fellow programmers and future you to read code.
You could also name them föΘBÄRẞ and your code will still compile. But nobody reading the code could make any sense of it.
Usually nothing special happens to the code itself, but other people used to the conventional style will have troubles understanding it and therefore you will e.g. have a lower rate of answers to your SO-questions if they contain code that doesn't follow the conventions.
But because you mentioned it extra:
To start a java program with the java command (this is the standard way), your main method has to have a defined signature, as stated in the documentation The java Command:
The method declaration has the following form:
public static void main(String[] args)
So in this case, if your main method is named Main and doesn't have that exact give signature (public static, no return value, array of String as parameter), your program will not start.
And of course if you are overloading or overwriting or implementing methods from other classes or interfaces, you have to copy their name exactly and must not change the case - and as e.g. overwriting of equals and hashcode from the Object class are quit common, it would result in a mixture of casing, and from my experience I can say this is super confusing - even if you want to understand your own code a few days after you wrote it.
Syntax wise it wont make any difference but the standard says that you should be following camel case when naming methods or variables.
An Excerpt from official doc.
"Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized."
https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html

Calling substring Method?

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.

Printing integer to textfield area

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.

how do you initialize a variable that is declared?

if (eyeColor == green)
{
System.out.println ("If your eyes are green I recommend buying .... ");
....
}
error says
variable green might not have been initialized
I can't display my whole code since it is for school, but I am just wondering how can I initialized it if the eyeColor from the user input (using scanner) is green?
Not sure what is the type of green but this is how you declare method local variables:
Object green = null;
or
Object green = SOME_DEFAULT_VALUE_BETTER_THAN_NULL;
Initialise eyeColor before you compare it.
If it is a string, simply initialise it as an empty string:
String eyeColor;
eyeColor = "";
Before you perform any checks to see what eyeColor has been specified, you may also want to check to make sure that is is NOT still ""..
Assuming that your variable eyeColor is the input from the user. You could use the following
if("green".equals(eyeColor))
Since green is a string, and it will never change (it is always green), you can just use the string. It is also worth noting that in Java, you need to use .equals() when comparing string values, not '=='.
I would also suggest using .toLowerCase(), so that the comparison is no longer case sensitive. An example check is shown in the code below:
public static void main(String args[]) throws IOException {
String eyeColor = "Green";
if("green".equals(eyeColor.toLowerCase())){
System.out.println ("If your eyes are green I recommend buying .... ");
}
}

Java declaration/ variable scope issues

I'm relatively new to java, and after much searching, I just can't pair up any solutions of related issues to mine. I'm trying to implement a very simple method to write to/ read from an array, and it's not being recognized by the compiler. "Keyboard" is a "variable not recognized" either. Here's a declaration of the array, with the method a bit further down that works on it... (first time long time btw :) Many thanks in advance...
private static void loadMakeModelYear()
import java.util.Scanner;
String [][] makeModelYear = {{"Make", "Model", "Year"},{"Blank", "Blank", "Blank"}};
private static void loadMakeModelYear()
{
for (int i = 0; i < 3; i++)
{
System.out.println("Please enter a " + makeModelYear[i][0]);
makeModelYear [i][1] = keyboard.nextLine();
}
}
This is just a guess, but your code appears to use keyboard with a lowercase k, while your error message uses Keyboard with a capital K. Check the case of your variables.
I juste rewrote your example as it may explain things better here.
import java.util.Scanner;
class SomeClass
public static void main(String...args) {
loadMakeModelyear();
}
static String[][] makeModelYear = new String[][] {
{"Make", "Model", "Year"},
{"Blank", "Blank", "Blank"}
};
private static void loadMakeModelYear() {
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("Please enter a " + makeModelYear[0][i]);
makeModelYear [1][i] = keyboard.nextLine();
}
}
}
There are a lot more resources for Java than there is for C#. One site that is often very useful (to me at least) is Real's howto (check out the Java index).
What IDE are you using for this? NetBeans does a decent job of providing most VS2010 functionality.
I do not see keyboard declared. Do you declare it elsewhere?
"keyboard" is not a special object in Java giving you access to the real life keyboard, if that helps.
My My My ..... Oh my dear, you're grossly confused in the way Java language operates. Lets look at your code more closely.
1.) Firstly, import statement should be the first statement in your file. The only statement which can come before import is the package statement.
but the glaring mistake which you're doing is by declaring methods like this. In java the scope of any method is bound to a class. This is not declarative style programming, where you can declare a stand-alone method. The same argument holds for your array as well, this array and method must be part of some class, even if they are static.
3.) Secondly, you are using a variable keyboard, but you have not declared it anywhere.
I hope you do realize that you're just using the wrong paradigm. Say this after me, "Java is purely OO "
Regards
AViD
I think I see your problem. This is just a guess, and I'm not sure if you have already done this. In the case that you haven't you might want to set your reference variable keyboard to the Scanner class. This can be done by:
Scanner keyboard = new Scanner(System.in);

Categories

Resources