Java

98K

Solutions

32K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

Share tech news, updates, or what's on your mind.

Sign up to Post

I am learning recursion so trying to practise it by implementing BinarySearch algorithm.
public class BinarySearch {
	public int search(int[] items, int searchTerm, int startIndex, int endIndex) {
		int midIndex = (startIndex + endIndex)/2 ;
		System.out.println("Midpoint: "+midIndex);
		if(searchTerm == items[midIndex]) {
			return midIndex;
		} else if(searchTerm > items[midIndex]) {
			search(items, searchTerm, midIndex, endIndex);
		} else if(searchTerm < items[midIndex]) {
			search(items, searchTerm, startIndex, midIndex);
		} else {
			return -1;
		}
		return -1;
	}
	
	public static void main(String[] args) {
		BinarySearch bs = new BinarySearch();
		int[] items = { 1, 7, 9, 11, 22, 55, 67 };
		int index = bs.search(items, 7, 0, items.length-1);
		System.out.println(index);
	}

}

Open in new window


'search' is the method that is called recursively with array of items, the value that I want to search and start & end index of the array where item could potentially be there.

First, I get the midpoint and if the item at midpoint matches the searchTerm then I return it. If searchTerm is greater than value at midpoint then I call the search method again with  midpoint as startIndex and last item in the array as endIndex.
Similarly, if searchTerm is less than value at midpoint, then pass startIndex and midpoint as start and end value to search in.

Lets say, I want to search for 7. In the first iteration, 3 would be the midpoint so value at index 3 would be 11. Since, 7 < 11, search will be called again with startIndex as 0 and endIndex as 3. Now, midpoint would be 7, so the index of 7 (which is 1) should be returned. However, the value returned is -1 which is not correct.

When I tried troubleshooting it using Eclipse debugger, I found that even after the match is found at

if(searchTerm == items[midIndex]) {
			return midIndex;
}

Open in new window


instead of exiting the method, the below code gets executed

else if(searchTerm < items[midIndex]) {
			search(items, searchTerm, startIndex, midIndex);
		}

Open in new window

and then it returns -1. I feel it could be something to do with recursion as the previous invocation of search() would still be in the stack due to recursive nature of the code and it might be popping out of the stack. However, I can't really understand it. What would be the correct way to implement BinarySearch using recursion?
0
Free Tool: Port Scanner
LVL 9
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hello there,

I have a Zebra ZT410 and it is integrated with my Java application and for some reason sometimes the printer does not begin start printing. Is there a simple ZPL code or way to get an error message back from a Zebra printer to determine if the labels did not print successfully or that there was some kind of error?

cheers
Zolf
0
Hi, I'm not very familiar with oracle oraclient11g.

I just seem to have a very basic issue of needing to either uninstall it or figure out how to manually remove move it. And may need to locate the correct oraclient11g that can be easily installed and uninstalled if and when needed.

All of our machines have this installed on them as part of an image and when we have an issue with it, I have been told the best solution is to reimage the pc rather than a simple uninstall/reinstall.

When I go to the  Oracle Universal Installer - OUI from the start menu to uninstall as has been suggested by a few posts on the web, a CMD window opens, it checks swap space & screen resolution then just closes while "preparing to launch OUI from
users\username\local\temp\orainstall~ directory.

When I go to that path, I see it has created one for ever time I have ran it.

My basic issue is how to completely uninstall and confirm as well as how to locate the oraclient11g package so I maybe able to easily uninstall/ reinstall if and when needed.


Thank you very much
0
I have a Java HashSet such as

	Set<Character> allowedBraces = new HashSet<Character>('{', '[');

Open in new window


This HashSet contains some characters. Now, there is an input string, I need to iterate through it and find out if any of the characters in the input String match the characters in allowedBraces HashSet.

String input = "{abc}[xy]";
for (int i = 0; i < input.length(); i++) {
	Character c = input.charAt(i);
	System.out.println(allowedBraces.contains(c));
}

Open in new window


'{' and '[' match the values in HashSet, so should return true. However, all character comparisons return false.

What would be the correct way to compare a character with values in a Set?
0
Hello,
What other programming languages for web service development?  Which is better PHP or html?
0
How can I be very proficient in Java? I am an electrical electronics engineer but I have keen interest in programming though my age is not that encouraging- I am 35 years old.
0
hi experts,

 i'm wondering if there are any filemakerpro experts in here. I'm trying to open the admin console and i'm getting error message : Java (TM) Web Start 11.13.2.11-fcs   Cannot Determine a valid Java Home
0
please send me the link
0
What is depdencies and how do I know which version is avaible for selection in my current project ?

Pic2 : There is no library for com.android.support:appcompat-v7:25.3.1 but I can use it in my code
Pic1: Try to use cardview but it tells me that the version is not correct. Where can I check which version is currently avaialble ?

Thx
0
302 Moved Temporarily
Location: http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-linux-x64.tar.gz?AuthParam=1499150225_7c8888245a3ac92875923c1caa8b317c [following]
--2017-07-04 12:05:05--  http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-linux-x64.tar.gz?AuthParam=1499150225_7c8888245a3ac92875923c1caa8b317c
Connecting to download.oracle.com (download.oracle.com)|49.200.255.202|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2017-07-04 12:05:06 ERROR 404: Not Found.

download failed
Oracle JDK 7 is NOT installed.
0
Optimize your web performance
LVL 1
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Hi,

I want to create list of list of integers in java. I want to add elements in the integer list dynamically, one at a time. I dont want to create a temo list and then add it to list if list. For example -

List<List<Integer>> myList = new List<ArrayList<Integer>>();
myList.get(0).add(111);  ------> This should add 111 in 1st integer list in the myList
myList.get(1).add(222); --------> This should add 222 in 2nd integer list in the myList

This looked straighforward but while testing this gives me out of index error. How can i accomplish this? Let me know if you need more info. Thanks.
0
import java.util.*;
import java.util.stream.*;
public class X {
	public static void main(String[] args) {
		List<String> list = Arrays.asList("xxax", "xbxbx", "xxcx", "zzz");
		System.out.println(noX(list));
	}
	public static List<String> noX(List<String> strings) {
		return strings.stream().map(s -> s.replaceAll("x","")).collect(Collectors.toList());
    }	
}

Open in new window

in above program what are Collectors , stream, collect methods. And why map is used in this lamda functional examples
0
I have a string AAABBCCCDEEEFF. I want to find out if any character in this sting repeats only 2 times. For example, AA or BB or CC etc. Also how to replace that char sequence in one regex? What is regex to identify this in java?
0
Hello,
Within the last 3-4 months I had changed the environment variables, and today I can't.  I read the findings from the internet and that has not worked.  I am Administrator.  I read that since Windows 10 15011 the ability to change the environment variables has been disabled.
Might you know of a work around.  I need this solved very soon.  I hope one of you will know.
Thanks
0
Hi,

http://codingbat.com/prob/p105967

I wrote my code as below and failing some tests
public List<String> noX(List<String> strings) {
   strings.replaceAll(x -> "");
  return strings;
}

Open in new window



Expected	Run		
noX(["ax", "bb", "cx"]) → ["a", "bb", "c"]	["", "", ""]	X	
noX(["xxax", "xbxbx", "xxcx"]) → ["a", "bb", "c"]	["", "", ""]	X	
noX(["x"]) → [""]	[""]	OK	
noX([""]) → [""]	[""]	OK	
noX([]) → []	[]	OK	
noX(["the", "taxi"]) → ["the", "tai"]	["", ""]	X	
noX(["the", "xxtxaxixxx"]) → ["the", "tai"]	["", ""]	X	
noX(["this", "is", "the", "x"]) → ["this", "is", "the", ""]	["", "", "", ""]	X	
other tests
		X	

Open in new window


how to fix and improve my code, please advise
0
Hi,

I am trying to double list numbers using functionala lamda programming


http://codingbat.com/prob/p117665
Given a list of integers, return a list where each integer is multiplied by 2.

doubling([1, 2, 3]) → [2, 4, 6]
doubling([6, 8, 6, 8, -1]) → [12, 16, 12, 16, -2]
doubling([]) → []

Open in new window


Solution:

public List<Integer> doubling(List<Integer> nums) {
  nums.replaceAll(n -> n * 2);
  return nums;
  
  // OR the equivalent java streams solution:
  // return nums.stream()
  //  .map(n -> n * 2)
  //  .collect(Collectors.toList());
}

Open in new window

i am trying to write a java a program to execute it in exclipse to see result in eclipise consoel

import java.util.List;

public class FuncProgDouble {
	public static void main(String[] args) {
		List<Integer> li=[1, 2, 3];
		System.out.println(doubling(li));
	}

	
	public static List<Integer> doubling(List<Integer> nums) {
	  nums.replaceAll(n -> n * 2);
	  return nums;
}

	
}

Open in new window


i am getting below compilation error.

Multiple markers at this line
      - Syntax error on token "]", } expected
      - Type mismatch: cannot convert from int[] to
       List<Integer>
      - Syntax error on token "[", { expected

canont i add primitives as below to Integer list


import java.util.ArrayList;
import java.util.List;

public class FuncProgDouble {
      public static void main(String[] args) {
            
            
            ArrayList<Integer> al=new ArrayList<Integer>();  
            al.add("1");  
            al.addAll("3");  
            al.addAll("8");  
            //al.add(1,"Sachin");
            
            //List<Integer> li=[1, 2, 3];
            System.out.println(doubling(al));
      }

      
      public static List<Integer> doubling(List<Integer> nums) {
        nums.replaceAll(n -> n * 2);
        return nums;
}

      
}

please advise
0
Hi Experts,
Trying to build and deploy a war file using Gradle on Tomcat...for one of my POC.

could you give me some lead pls
0
We have Double.isInfinite(), float.isInfinite(), why dont we have that for Integers ?, I think they shud, irrespective of any reasons
0
In a book i'm reading, it shows below code and states: if 'data' isn't defined as a volatile var, other classes might access it before it's completely initialized.  Can someone explain this statement to me. There's nothing else written about it.
class StockData {}
class StockExchange {
      static volatile StockData data = null;
      static void loadStockData () {
            //load and initialize reference variable data. the variable data is written to only once
      }
}
class BuyStocks {
      public void buy () {
            if (StockExchange.data != null) {
                     //analyze data
                    //buy stock
            }
      }
}
0
On Demand Webinar: Networking for the Cloud Era
LVL 9
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Hello Experts,

I have a Java applications that uses FileVisitor to walk the directories and read each file looking for a pattern using Scanner’s findWithinHorizon method. Once a match is made, the program stops searching the current directory and moves on to the next one. The issue I’m having is that it takes up too much memory and the program can’t complete a search without throwing an OutOfMemoryExeption. Does anyone have a way around the out of memory exception?

Thank you!

Fox

here is the code::
private java.util.List<String> searchFiles2(String FilePath, final String pattern) throws FileNotFoundException, AccessDeniedException
    {
        File file = new File(FilePath);
        if (!file.isDirectory()) {
            throw new IllegalArgumentException("file has to be a directory");
        }

        final List<String> FoundDirectories = new ArrayList<String>();
        try {
            Path startPath = Paths.get(FilePath);
            Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path file, final BasicFileAttributes attrs)  throws IOException {
                    try {
                        final String name = file.getFileName().toString();
                        // skip hidden files:
                        if (name.startsWith(".") || new File(file.toString()).isHidden()) {
                            return FileVisitResult.SKIP_SUBTREE;
         

Open in new window

0
I have been using JDK 9 on Windows 10 x64 for a while but when I went to install the latest early release (b174), I first uninstalled the previous version (as usual) and then ran the new installer.

It fails with a message box saying "Another Java installation is in progress. You must complete that installation before you can run this installer".

It seems there are some artifacts around causing the problem but only for JDK 9 as I can uninstall & reinstall JDK 8 without any issues. Also, the same problem occurs if I try to run the installers for any prior JDK 9 releases as well (even though they worked before).

Searches have suggested various options like using a Microsoft MSI clean-up tool and registry hacks but nothing is helping.

Can anyone suggest a way to get JDK 9 installed (as now I cannot use any release of JDK 9 at all)?
0
Should I use Ecllispe or Android Studio to develop Android application ? Any good resource for starter to build an Android application ?

Thx
0
I have an expandable list view that is inside of an expandable list adapter. I would like to remove an item from an expandable list view when the delete option is selected in the context menu in Android. After I call the remove method on the object's position, when I try to call notifyDataSetChanged() on the expandable list adapter, it says the method does not exist.

However, it will work for a regular ArrayAdapter. Because of the way my data is structured (having to display multiple fields in each list view item), I need to use an expandable list view instead of just a simple list view. I have tried casting the expandable list adapter to an ExpandListAdapter object and calling the getAdapter() method on it, and then calling notifyDataSetChanged() but I get the following error: SimpleAdapter cannot be cast to com.test.myapp.ExpandListAdapter.

My application is using API 25. Please see the code below:
@Override
public boolean onContextItemSelected(MenuItem item) {

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
        case R.id.add:
            Intent intent = new Intent(MainActivity.this, AddUser.class);
            startActivity(intent);
            return true;
        case R.id.edit:
            Intent intent2 = new Intent(MainActivity.this, ViewUser.class);
            intent2.putExtra("data", userList.get(info.position).get("id"));
            startActivity(intent2);
 

Open in new window

0
padserver/padErr.txt

==> /usr/local/pad/padserver/padOut.txt <==

---- java.library.path   ../lib/dll;/usr/local/pad\lib\dll\sys32

---- java.ext.dirs   /usr/java/jdk1.7.0_79/jre/lib/ext:/usr/local/pad/lib/ext



 checkFileInPath jspWin.dll   exists false

 checkFileInPath x25lyra.dll   exists false




==> /usr/local/pad/padserver/padErr.txt <==

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space

java.lang.OutOfMemoryError: Java heap space


Hi Experts

we get above Java heap space error on our servers due to this we face other issues on server. kindly help.
0
I have below entity class which Im saving to DB based on LogType enum

@Entity
@Table(name = "AuditLog")
@Getter
@Setter
public class AuditLog implements Serializable
{
  
    private static final long serialVersionUID = 1L;
   
    @Id
    @Column(name = "AuditLogId", nullable = false)
    public Integer            importId;
	
    @Column(name = "AuditLogDescription", nullable = false, length = 1000)
    public String             logMessage;
 
 
    @Column(name = "EntryDateTimestampJoda", nullable = true)
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    @XmlJavaTypeAdapter(DateTimeAdapter.class)
    public DateTime           entryDateTimestampJoda;
   
       
    @Column(name = "ExitDateTimestampJoda", nullable = true)
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    @XmlJavaTypeAdapter(DateTimeAdapter.class)
    public DateTime           exitDateTimestampJoda;

}

Open in new window


And im calling it like based on Enum Value as below however Its the same repeatative code that gets called in below if condition,

private void processLoggingData(LogData logObj, LogType type)
{
	if (type.toString().equalsIgnoreCase(LogType.LOG1_PROCESSING.toString()))
	{	
			AuditLog audObj = new AuditLog();
			audObj.setImportId(logObj.id);
			audObj.setLogMessage(logObj.description);
			audObj.setEntryDateTimestampJoda(logObj.getStartDateTime());
			audObj.setExitDateTimestampJoda(logObj.getExitDateTime());
			

Open in new window

0

Java

98K

Solutions

32K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.