w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » JAVA » Page 1
ClassNotFoundError ArrayList
Run the program by specifying fully classified name. It works! java arrayList.ArrayListStrings With out specifying package name, if you run it, it will throw NoClassDefFoundError.

Categories : Java

PrimeFaces 5.1 not being included properly
Turns out this was an issue in how Eclipse was deploying my project's EAR file to the app server. The WAR project wasn't set to include the Maven dependencies in the deployment assembly. Once I made that change it deployed as expected and Primefaces worked without issue.

Categories : Java

Reducing IF statement java
Since you are not going to have to modify this code later with more units, I would suggest you a ternary operator : String s = cbTwo.getValue(); showAnswer.setText(s.equals("Celsius") ? fahr.fahrenheitToCelsius() : s.equals("Farenheit") ? fahr.fahrenheitToFahrenheit() : kelvin.kelvinToKelvin()); Note that it is not exactly equivalent, in the case that s does not match any of thestrings you

Categories : Java

Designing a traffic light application
I wouldn't use timer at all. You would be better off looking at the ScheduledExecutorService for this sort of application.

Categories : Java

Recursion: Binary to Decimal
You don't have a base case; binary2Decimal (3-arg version) always calls itself. (Since the only thing changing from one call to the next is high, your base case should probably involve that somehow.)

Categories : Java

Java arraylist accessing an element to calculate average
The list numbers contains String objects, so casting the elements to double will throw an exception. You could have avoided this runtime exception if you had used the generic type ArrayList properly: ArrayList<String> numbers = new ArrayList<String>(); This would allow the compiler to detect ahead of time the type incompatibility. To read the double value of the string, you can use

Categories : Java

libGDX 3D rotate ModelInstance to the second one with a coefficient of rotation speed
Actually you should never rotate a ModelInstance to face another ModelInstance, but you should rotate it to an angle given by the gamelogic. That means, that you should sepperate the logic and the view. In this case the logic needs to store the currentAngle and the desiredAngle, as well as a rotationSpeed. The desiredAngle can be calculated out of the positions of the Tower and the Enemy. In the u

Categories : Java

HashMap initialization in java
Yes it is possible: public static <K,V> Map<K,V> mapFromArrays(K[] keys,V[]values){ HashMap<K, V> result=new HashMap<K, V>(); for(int i=0;i<keys.length;i++){ result.put(keys[i], values[i]); } return result; } Assuming that keys and values have the same length. You may also use this function in a static initializer like this: private static I

Categories : Java

What does @Proxy(lazy = false) do?
@Proxy(lazy=false) will disable the default lazy loading for a particular entity. This means you always get the initialized entity whenever this entity is being referenced from other entities. Using this annotation is usually a "code smell". If I were you I would remove it and simply load all entity associations using the join fetch directive or using @Subselect or @BatchSize eager loading.

Categories : Java

Lost, Trying to Program a Relatively Complex Hailstone Sequencer
public static void hailstone() { System.out.println("Welcome to the hailstone program! this program will take a number and generate the hailstone sequence, counting the number of steps until a 4, 2, or 1 is reached, and calculating the maximum value."); Scanner scanner = new Scanner(System.in); int n = Integer.MAX_VALUE; while(n < -1 || n > 100000){ System.out.print

Categories : Java

Java passing variable - downcasting
Change the definition of helloworld to public void helloworld(List<?> names) { //method implementation... } Take into account that your method won't be able to add or remove elements from the list parameter.

Categories : Java

How to collapse TitledPane programatically in JavaFX?
Since only one TitledPane in the same Accordion can be expanded at any time, the Accordion (to some extent) manages the expanded state of any TitledPanes it contains. You can do accordion.setExpandedPane(titledPane); to get the accordion to expand titledPane. Calling titledPane.setExpanded(true); also works, but only if you invoke this after the window has been shown (for reasons I don't full

Categories : Java

Adding a list of specific node on a custom JavaFX FXML control
Since you have a setButtons method defined, the FXMLLoader is going to attempt to pass in the value defined by the elements inside <buttons>...</buttons> to that method. (See Introduction to FXML, and note in particular "A read-only list property is a Bean property whose getter returns an instance of java.util.List and has no corresponding setter method." - my emphasis.) If you have a

Categories : Java

java Files.readAllBytes(image.png) doesn't work
Writers are for writing text, possibly in different formats (ie utf-8 / 16, etc). For writing raw bytes, don't use writers. Just use (File)OutputStreams. It is truly as simple as byte[] bytes = ...; FileOutputStream fos = ...; fos.write(bytes);

Categories : Java

Intellij Idea Tomcat and Spring MVC template
Without more detail about the error you got, I can't answer why you needed to change the Java version. As for the servlet-api dependency, that is because Tomcat has its own implementation of the servlet-api included. So there was a clash. What you will want to do is add the dependency back into your POM with a scope of provided. That way it is there for your IDE to use as well as at build time. (

Categories : Java

How to add 10 specific products (objects) with different data types in each one, in an ArrayList?
The products (objects) have to inherit from one superclass. Suppose you have class Foods, Drinks, and Snacks such that Drinks and Snacks inherit from Foods You can do this: ArrayList<Foods> menu = new ArrayList<Foods>(10); menu.add(new Drinks("Coke", 1.99, 10, 10)); menu.add(new Snacks("Candy", 0.99, 10, 10)); The above is called Polymorphism, great tutorial here https://www.you

Categories : Java

how to use Servicemix to make SOAP Web Services comunicate
Sure, this is essentially the pattern for ServiceMix. Much of what you are looking for in terms of mediation and routing is realized through Apache Camel. You would need to host the remote web services in a separate web container, such as Tomcat or Jetty. Next, you would implement service endpoints as OSGi bundles that are deployed to ServiceMix. These OSGi bundles expose your service interface. W

Categories : Java

Is the IN relation in Cassandra bad for queries?
I remembered seeing someone answer this question in the Cassandra user mailing list a short while back, but I cannot find the exact message right now. Ironically, Cassandra Evangelist Rebecca Mills just posted an article that addresses this issue (Things you should be doing when using Cassandra drivers...points #13 and #22). But the answer is "yes" that in some cases, multiple, parallel queries

Categories : Java

is IntStream class in JDK 1.6?
If all you want is to convert an int[] into an List<Integer> you can either: create your own ArrayList and add the elements manually List<Integer> list = new ArrayList<Integer>(intArray.length); for(int value : intArray){ list.add(value); } Or you can easily write your own class that implements List using an primitive array backing: public final class In

Categories : Java

the method to calculate prime number
First, if you put divisor <= number, you would get no prime numbers at all, because every number is divisible by itself. If the loop does not exit before divisor becomes number, you would get to number % divisor == 0 condition, and return false. Whoever wrote this code made an observation that you can stop as soon as you have reached half the number, because if you did not find divisors in

Categories : Java

How to avoid creating custom exception classes whilst still throwing exceptions at an appropriate level of abstraction?
It's quite philosophical question. But in general it means that you should create your own exception with considering of existing ones. Example : In case of usage some external service and this service is unavailable , in this case I wouldn't recommend you to throw your own exception, because "Connection Refused" or "Connection timed out" will understand on the spot every programmer a

Categories : Java

Need of page factory in page object model
You can, in fact, use the page object pattern without using the PageFactory class. The page object pattern simply abstracts your business logic away from the physical structure of your pages. What the PageFactory class gives you is the ability to use annotations to automatically find the elements on the page without resorting to explicit findElement calls. It lets you write code like this: public

Categories : Java

Eclipse ASTVisitor ImportDeclaration from Package or JAR?
Ok, the solution is resolving the node to IBinding and then ITypeBinding and calling isFromSource(): IBinding b = node.resolveBinding(); if (b instanceof ITypeBinding && !((ITypeBinding) b).isFromSource()) { //do stuff }

Categories : Java

Bitwise shift to get max unsigned value
One first thing: (1 << (bitsCount)) - 1 This is a mistake because you are only performing integer arithmetic. You needed: (1L << (bitsCount)) - 1 But anyway I assume bitsCount is 64. In Java you cannot shift by a number larger than 63 for a long and 31 for an int (JLS 15.19): If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-ha

Categories : Java

Difference between finish() and super.finish() in Java?
finish() will call the finish() method on your class. super.finish() will call the finish() method on your parent class. Unless your are overriding the finish() method in your Activities (which you shouldn't), the two will do the exact same thing.

Categories : Java

replace a string which already contains double quotes with blank
You have to escape double quotes " with a backslash " public static void main(String[] args) { String s = ""welcome "to" the world""; s = s.replace(""welcome "to" the world"", ""); System.out.println(s); } or you can use s = s.replaceAll(""welcome "to" the world"", ""); Output

Categories : Java

WELD-001408 Unsatisfied dependencies for type [LdapService] with qualifiers [@Named] at injection point
The solution for my first error was: -Removing the @Stateless and @Inject from LdapService and the default constructor public class LdapService { }... -Create an Interface for LdapService and @Inject this interface to UserService public class UserService { private static final Logger logger = LoggerFactory.getLogger(UserService.class.getCanonicalName()); @Inject private LdapServiceInterface

Categories : Java

How to copy a tree where each node has more that two leaves?
How about using this pattern: class Item { //.... } TreeItem<Item> deepcopy(TreeItem<Item> item) { TreeItem<Item> copy = new TreeItem<Item>(item.getValue()); for (TreeItem<Item> child : item.getChildren()) { copy.getChildren().add(deepcopy(child)); } return copy; }

Categories : Java

Fatal Exception: java.lang.IllegalStateException GoogleApiClient is not connected yet
There's an issue with your code here: @Override public void onDestroy() { Log.d(TAG, "onDestroy"); if (googleApiClient != null) { if (googleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, highAccuracyListener); googleApiClient.disconnect(); } Simply clean it up a bit: @Override public void onDestroy() { Log.d(TAG, "onDes

Categories : Java

Unable to click on the drop down link
This is not a dropdown, this is some fancy AJAX that looks like a dropdown. You need to use discrete clicks. Start with something like the following, but you will need to experiment (or post a link to your site) to get it to work the way you need. driver.findElement(By.className("dropdown")).click(); driver.findElement(By.className("dd_txt")).click();

Categories : Java

Java remove duplicates from array using loops
Try this: public static void duplicate(int numbers[], int size) { for (int i = 0; i < size; i++){ boolean duplicate = false; int b = 0; while (b < i){ if (numbers[i] == numbers[b]) duplicate = true; b++;} if (duplicate == false) System.out.print(numbers[i] + " ");} } You need to use == not = in your if statement.

Categories : Java

Java Struts call another action after executed action finsihed
You can use this <result type="redirectAction"></result> <action name="copyTestSuite" class="testSuiteAction" method="copyTestSuite"> <result type="redirectAction">/newAction.action</result> </action>

Categories : Java

Shared Preferences Null Pointer Exception
Try use 'apply' instead of 'commit' , the justification is here -> What's the difference between commit() and apply() in Shared Preference by Lukas Knuth. But basically, apply() will commits its changes to the in-memory SharedPreferences immediately. It's strong recommended use a class to manager your preferences, like 'MyPreferencesManager'.

Categories : Java

non build files of eclipse project in git repository
If there are files/directories that you do not want to push to the repository, you should use the .gitignore file. Create a .gitgnore file in the root directory of the git project. This is what a typical .gitignore file looks like in case of android. # Built application files *.apk *.ap_ # Files for the Dalvik VM *.dex # Java class files *.class # Generated files bin/ gen/ # Gradle files .grad

Categories : Java

How can I make fields in nested class real private?
If the class must not be moved to outside of Outer, you should define an interface for Inner and use only that. If you have only few instances and this is not a performance critical point of your application, you could just create anonymous implementations of that interface. The class isn't static anymore but at least it's a short and readable solution. private static interface Inner { void s

Categories : Java

Java: how to relaunch the class extended application from JButton?
I actually find this code from oracle which helped me a lot. I will share it here just in case if anyone needs https://docs.oracle.com/javafx/2/swing/SimpleSwingBrowser.java.htm explanation can be found here https://docs.oracle.com/javafx/2/swing/swing-fx-interoperability.htm#CHDIEEJE Thank you for trying to help me

Categories : Java

Is native platforms: junit-4.11.jar, junit-LICENSE.html normal in Play Store?
junit-4.11.jar and junit-License.html causes problem of supporting 0 devices on playstore. Please check which library or jar file in your is using this. Then you have to remove them and then upload your app. In my case, core.jar had these files, just open the jar file using winrar, go to lib folder and delete these 2 files. There will be no problem in functioning of jar file by doing this.

Categories : Java

How do you print the value of an int inside square brackets in Java?
If I am understanding the question. Say you have an int int number = 0; and you have a print statement. System.out.println("This is the number : [" + number + "]"); That is how you do it.

Categories : Java

Making a triangle with stars
public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("How many rows: "); int rows = input.nextInt(); for (int i = 0 ; i < rows ; i++) { for (int x = 0 ; x < rows - i ; x++) { System.out.print(" "); } for (int x = 0 ; x < i + 1 ; x++) { System.out.print("*"); } Syste

Categories : Java




© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.