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.
Related
I have solved hackerrank Java Map Problem but I had timeout result for 2 cases. When I changed just the printf line problem solved. However I could not understand why it is ? Here my code:
import java.util.*;
import java.io.*;
class Solution{
private static HashMap<String, Integer> phoneBook = new HashMap<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String search = "";
int n=in.nextInt();
in.nextLine();
for(int i=0; i<n; i++) {
String name=in.nextLine();
int phone=in.nextInt();
phoneBook.put(name, phone);
in.nextLine();
}
while(in.hasNext()) {
search = in.nextLine();
if (phoneBook.get(search) != null)
System.out.printf(search + "=" + phoneBook.get(search) + "\n"); // this works
// System.out.printf("%s=%d\n", search, phoneBook.get(search)); // this does not work why ?
else
System.out.println("Not found");
}
}
Formatter.format() takes time
Formatter.format() (and its shortcut System.out.printf()) requires parsing, validating and formatting. All that takes a huge amount of time.
So just dump the data as quick as possible. Hackerrank requires you to make fast programs, so just do that: a fast program. Concatenate your items instead of formatting them. Also, if you have no parameter, just use System.out.println() instead of System.out.printf.
When you do a formatting output, java parses the string to format ("%s=%d\n" in your case) to put values instead placeholders. It takes at least O(n) complexity, which is important in your case.
Also you call phoneBook.get(search) twice. Try to keep the result in a variable. It also can speed up the program.
To break the string into separate lines, we need to use %n specifier in printf statement.
System.out.printf("%s=%d%n", search, phoneBook.get(search));
OR you can use the String.format() shown in the below statement.
System.out.println(String.format("%s=%d",s,p));
Short Answer: Lookup performance of Hashmap + Formatting the fetched value from the HashMap was computationally more Intensive than just concatenating the string without any format.
To be a bit verbose, the HashMap Implementation which is designed for an amortized complexity of O(1) for get(Key) functions does have a nasty complexity of O(n) (stressing the term worst case :) ) if either all or most of the keys share a common hash. Such occurrences, although not very common would've occurred when the test case feeder gave an enormous test case input with multiple duplicate values. Such a situation combined with simultaneous formatting would've resulted in a crash.
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.
Following is a small section of the code I am using, along with the syntax of the text file I am using. (I am fairly sure both are grossly overcomplicated, but I am not exactly sure how to simplify them.)
while((line = bufferedReader.readLine()) != null)
{
if(line.split("##")[0].equals(lineNumber))
{
numberOfLines = Integer.parseInt(line.split("##")[1]);
spaceSkip = 1;
worked = 0;
}
if(spaceSkip == 0)
{
if(numberOfLines > 0)
{
System.out.println(line);
numberOfLines--;
}
}
spaceSkip = 0;
}
And the format of the text file is:
1##2##3##0
Text goes below it,
and can span multiple lines.
The 3 and 0 do not come into play here. The intent is for the program to search for the number selected and match it to the first number, 1 in this case. The second number is the number of lines to read. In the code, I have "spaceSkip" so that it does not read the indexing line.
Explanations aside, the issue I am having is that line.split("##")[0].equals(lineNumber) seems to be reading false. I have printed both out to the screen at the same time, and both equal 1, but it is still returning an error message I included. ("worked = 0;" is what keeps the error from triggering.) I am certain it is a stupidly simple mistake I am making here, but I still am unable to figure it out. Thank you in advance.
Whenever a comparison doesn't return what you think it should, check that the types are what you think they are.
String#split returns an array of Strings. For your given input the first element of that array will be "1". If lineNumber is something other than a String, say an int, then equals will still work (the primitive int gets autoboxed to a java.lang.Integer, which is a subclass of java.lang.Object, which is the type the equals method takes as a parameter), but the comparison ("1".equals(1)) will always return false. JavaScript is OK with equating a string and an int ("1" == 1 returns true), but Java is not.
The easiest fix would be to convert the lineNumber to a String, by calling String#valueOf passing in lineNumber. It would be better to convert lineNumber to a String than try to convert the split output to an Integer, because the Integer parsing could fail on bad input, and I'd rather avoid having to manage that possibility.
The cut-n-pasting of the split call is unfortunate mostly because of redundancy, you should do the split once into a local variable like:
String[] parts = line.split("##");
if (parts[0].equals("1")) {
numberOfLines = Integer.parseInt(parts[1]);
...
Without seeing the initialization of the variables it is hard to tell, but it is possible that you are comparing a String to an Integer in this if statement.
You may want to try casting the second argument to a String as follows.
if(line.split("##")[0].equals(String.valueOf(lineNumber)))
I have been searching here for some time but haven't been able to find the answer to it.
I am basically required to use an array for this assignment from college. And then I am supposed to check that the input (which is also a String) matches whatever's stored within the String array.
I know one can easily compare Strings by using the .equals() method. However, the same method is not working with the String array.
I created the following example of code for the purpose of StackOverflow so you can use it to explain it to me, if you'd like.
What am I doing wrong?
import java.util.Scanner;
class IdiocyCentral {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
/*Prints out the welcome message at the top of the screen*/
System.out.printf("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf("%55s", "=================================\n");
String [] codes = {"G22", "K13", "I30", "S20"};
System.out.printf("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2], codes[3]);
System.out.printf("Enter one of the above!\n");
String usercode = in.nextLine();
if (codes.equals(usercode)) {
System.out.printf("What's the matter with you?\n");
}
else {
System.out.printf("Youda man!");
}
}
}
I apologize if this has been asked before and I just missed it, if its a double question, I will remove it.
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.
if(Arrays.asList(codes).contains(userCode))
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
Iterate over the codes array using a loop, asking for each of the elements if it's equals() to usercode. If one element is equal, you can stop and handle that case. If none of the elements is equal to usercode, then do the appropriate to handle that case. In pseudocode:
found = false
foreach element in array:
if element.equals(usercode):
found = true
break
if found:
print "I found it!"
else:
print "I didn't find it"
If I understand your question correctly, it appears you want to know the following:
How do I check if my String array contains usercode, the String that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
Instead of using array you can use the ArrayList directly and can use the contains method to check the value which u have passes with the ArrayList.
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner in = new Scanner (System.in);
/*Prints out the welcome message at the top of the screen */
System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf ("%55s", "=================================\n");
String[] codes =
{
"G22", "K13", "I30", "S20"};
System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
codes[3]);
System.out.printf ("Enter one of the above!\n");
String usercode = in.nextLine ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}
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.