C to Java Conversion - java

I know someone will give me a hard time for this, but here goes. I am trying to convert some C code to Java and am still learning java as I go. I am having a very difficult time figuring out how to do this conversion and learning java for that matter. Any help or pointers on where to go would be greatly appreciated.
for(d=alldevs; d; d=d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if(i==0)
{
printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);

A conversion offering:
public class Item {
private String name;
private String description;
public Item(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
}
(defined elsewhere)
List<Item> items;
And now the code
int index = 1;
for (Item item: items) {
System.out.print(index + ". " + item.getName());
if (item.getDescription() != null) {
System.out.println(" (" + item.getDescription() + ")");
} else {
System.out.println"( (No Description Available)");
}
index++;
}
List<NetworkInterface> nets = Collections.list(NetworkInterface.getNetworkInterfaces());
if (nets.size() == 0) {
System.out.println();
System.out.println("No interfaces found! Make sure WinPcap is installed.");
return;
}
System.out.print("Enter the interface number(1-" + nets.size() + "):");
Byte[] input = new byte[100];
System.in.read(input);
String inString = new String(input);
int interfaceIndex = Integer.getInteger(inString);
if (interfaceIndex < 1 || interfaceindex > nets.size()) {
System.out.println();
System.out.println("Interface number out of range.");
// freeing items is done by dereferencing
nets = null;
return;
}
// jump to the selected adapter
NetworkInterface selectedInterface = nets.get(interfaceIndex);
Note that you will have to do the "real" conversion of the rest of the program; that is writing a PCap solution in Java, or writing a JNI (Java) interface to call the PCap library routines.

WinPcap will always require native coding. You could use JNI to get some of that code (e.g. the select interface part) to java, but you'll never be able to fully convert it. (You can't directly call native dll's from java)
I can't really give you examples on JNI, but there is enough out there to find when searching JNI and Tutorial or the like :).

Java does not have pointers, so a construct like "d->next" won't map 1:1 in Java.
You'll have to figure out how to create a Java object that corresponds to whatever your "d" is. The rest looks like simple iteration and calls to System.out.

What do you mean by conversion?Are you trying to write an equivalent C program to Java?Is it an existing project or you wrote a program in C first and now you want to write the same program in Java?In any case you should get a good grip with both languages because they differ in the way you write programs that is C is a imperative/procedural language whereas Java is an object-oriented one. This alone means programming 'style' varies differently due to language semantics (and programming patterns, while language-agnostic, are applied differently too).
P.S.: I assume you are a beginner which, if I am correct, does not justify your votes down.

Related

Metadata Item bug

I'm creating a mod for minecraft and created a metadata item, it has three variants (default, 1 and 2).
when im trying to give it to my player with item:0 or nothing i get this item, and its id is just item without :number, but when i give item:1, the given item adds to stack to item:0. When i throw item:0 from inventory, item:1 successfully gives with it custom texture, but its id is item, not item:1
Here's my item with variants code:
public Trowel(String name, CreativeTabs tab) {
super(name, tab);
this.tab = tab;
}
public void getSubItems(Item item, CreativeTabs tabs, List<ItemStack> list) {
for(int i = 0; i < EnumTrowel.count(); i++) {
list.add(new ItemStack(item, 1, i));
}
}
#Override
public String getUnlocalizedName(ItemStack stack) {
for(int i = 0; i < EnumTrowel.count(); i++) {
if(stack.getItemDamage() == i) {
return this.getUnlocalizedName() + "_" + EnumTrowel.values()[i].getName();
} else {
continue;
}
}
return this.getUnlocalizedName() + "_" + EnumTrowel.CLEAR.getName();
}
This is my Main class preInit()
public static void preInit(FMLPreInitializationEvent event) {
proxy.registerModelBakeryStuff();
RegistryHandler.registerCustomMeshesAndStates();
RegistryHandler.registerFluid(concrete);
for(int i = 0; i < EnumTrowel.count(); i++) {
ModItems.registerRender(ModItems.TROWEL, i, "trowel_" + EnumTrowel.values()[i].getName());
}
}
And here's my ClientProxy register method
#Override
public void registerModelBakeryStuff() {
ModelBakery.registerItemVariants(ModItems.TROWEL, new ResourceLocation(Reference.MOD_ID, "trowel_clear"), new ResourceLocation(Reference.MOD_ID, "trowel_plaster"), new ResourceLocation(Reference.MOD_ID, "trowel_gypsum"));
}
item:0 = trowel_clear (default variant)
item:1 = trowel_plaster (1 variant)
item:2 = trowel_gypsum (2 variant)
There's no any errors in console.
I'm not actually sure what's going wrong, as you've hidden a few things behind other mehods that aren't really in places where they should be (why does ModItems have a registerRender method?)
Anyway, if I dissect my own code1 regarding items with variants I notice two things:
I don't see anything equivalent to variantName + "=" + variant.getByOrdinal(stack.getMetadata())); in your code. This string is what actually maps the metadata to a different model. My variants were all enum specified and hard mapped metadata <-> enum ordinal.
I don't see a call to ModelLoader.setCustomModelResourceLocation() which is what tells the game how to go find a resource for that string.
Its possible that your code does contain those things, but you haven't included it in the question, making it very difficult to figure out where things are going wrong.
Note that the class I've linked here is one half of a system that I custom built to handle the RegistryEvent systems in a way that was more friendly to having transitioned from 1.7.10's GameRegistry system. There's some odd redirections involved shoving data into arrays only to read them back out again later that's not actually necessary if you just construct items in the relevant event (which is the more widely accepted standard). I do all the same things, just at a different point.

Search for book using multiple criteria in java

I have this method which takes n number of arguments and search for a book in an arrayList using couple of arguments. .
How can i make it smaller?
How to sort books by category or author?
thank you in advance.
Here is my method
// search for a book using multiple criteria
static void bookSearch(String... varg) { // take varg as parameter
String title = ""; // place holders
String author = "";
if (varg.length > 1) { // check varg length
title = varg[0]; // if it is greater than 1 initialize needed arguments
author = varg[1];
} else {
title = varg[0]; // else initialize the first argument
}
for (Book book : bookList) {
/*
* if the title is the same and there is a second argument that
* match author's name print found it
*/
if (book.getTitle().equals(title)) {
if (author.isEmpty() ^ (book.getAuthor().getfName() == author)) {
System.out.println(" \"" +
title +
"\" founded at: " +
bookList.indexOf(book));
break;
}// end of if
} else if (bookList.indexOf(book) == bookList.size() - 1) {// if not found
System.out.println("cant find \"" + title);
}// end of else
} // end of for loop
} //end of search method
In Java8 you can use lambdas and functions to get flexible filter book function.
E.g. you have following Book class:
class Book {
private String author;
private String title;
}
The book filter function could look like this:
BiFunction<List<Book>, Predicate<Book>, List<Book>> BOOK_FILTER =
(books, fields) -> books.stream().filter(fields).collect(Collectors.toList());
Then, all you need is just build required Predicate and use this function.
public static List<Book> findBookByPredicate(List<Book> books, String author, String title) {
Predicate<Book> byAuthor = book -> book.getAuthor().equals(author);
Predicate<Book> byTitle = book -> book.getTitle().equals(title);
return BOOK_FILTER.apply(books, byAuthor.and(byTitle));
}
As you can see, you're not limited only certain number of Book fields. You can combine it as you like; BOOK_FILTER function stays the same.
You can default title to varg[0] and set author if varg.length is greater than one with a ternary. I would prefer a standard loop with a index counter (since otherwise you must search again to determine the index). Next, you need to complete the loop before declaring the title isn't found (I would use a boolean to maintain that state). Next, you logically need an or (not a xor) to check that the author argument is present and not empty before checking the book author. I would prefer formatted io. Like,
static void bookSearch(String... varg) {
String title = varg[0], author = varg.length > 1 ? varg[1] : "";
boolean found = false;
for (int i = 0; i < bookList.size(); i++) {
Book book = bookList.get(i);
if (book.getTitle().equals(title)
&& (author.isEmpty() || book.getAuthor().getName().equals(author))) {
System.out.printf("\"%s\" found at: %d%n", title, i);
found = true;
break;
}
}
if (!found) {
System.out.printf("cant find \"%s\"%n", title);
}
}
You can use java 8 lamda expression for this.
Ex.
List<String> lines = Arrays.asList("spring", "node", "mkyong");
//Here pass your collection and filter as per your requirement
List<String> result = lines.stream()
.filter(line -> !"mkyong".equals(line))
.collect(Collectors.toList());
Aside from using lambda expression, other way to make your code a little shorter would be to implement equals method for your Book class where you can compare two Book objects for equality by their title and author. Then instead of:
if (book.getTitle().equals(title)) {
if (author.isEmpty() ^ (book.getAuthor().getfName() == author)) {
System.out.println(" \"" + title + "\" founded at: "
+ bookList.indexOf(book));
break;
}// end of if
you can just use:
Book searchForBook = new Book();
searchForBook.setAuthor(author); //ins
searchForBook.setTitle(title);
for (Book book : bookList) {
if (book.equals(searchForBook)){
System.out.println(" \"" + title + "\" found at: "
+ bookList.indexOf(book));
break;
}
You can also make the creation of object searchForBook one line only, if you add proper constructors in your Book class.
On sorting the ArrayList - you can either make Book implement Comparable and use Collections.sort(bookList) or use a Comparator instead and use Comparator and again use Collections.sort before you use the collection, to have it sorted the way you want.
Your code can be shortened like this:
static void bookSearch (String... varg) {
String author = "";
String title = varg[0];
if (varg.length > 1) {
author = varg[1];
}
for (Book book : bookList) {
if (book.getTitle().equals (title)) && (author.isEmpty() || (book.getAuthor().getfName() == author)) {
System.out.println(" \"" + title + "\" founded at: " + bookList.indexOf(book));
return;
}
}
System.out.println("cant find \"" + title);
}
Title doesn't need to be in if and else branch. Just initialize on declaration.
Take the ternary operator from Elliot if you like
Your outer if only has the inner if (title/author). This can be replaced by &&.
Just return instead of breaking.
With the premature return, you don't need else anymore.
A boolean predicate 'matches' which does the same thing in the Book class might be preferred. Sorting can be a good idea, if you don't have to resort by different criteria often and if you search for multiple books - then it can pay off.
A boolean return or a return of the index, where the book was found, might be more flexible. But for reporting the index, I would use a classical for loop, where you get it by the same iteration.
Returning the index would allow to remove the System.outs, so that the caller can decide, how to handle the event: Order a book via net, print to stdout, output with Swing oder JavaFX or whatever.
A pure compareTo would allow efficient search algorithms to find many book in big lists fast and smooth integration in the new Stream collections.
Using varg seems to be a bad idea to me, since it opens the door wide for getting the parameter order wrong.
int bookSearch (String title, Optional[String] author) {
expresses more clearly what you want - many IDEs support parameter names.

Linking java functions/subroutines

I am developing a slots machine game as part of an assignment.
I have two functions that I need to link together, shown below:
public static void DisplayOnScreen(){
int LeftVal = GenerateNumber();
int MidVal = GenerateNumber();
int RightVal = GenerateNumber();
FruitVal1 = showFruit[LeftVal];
FruitVal2 = showFruit[MidVal];
FruitVal3 = showFruit[RightVal];
System.out.println(" |",FruitVal1, "|", FruitVal2, "|", FruitVal3, "| ");
--
public String showFruit(int inVal) {
String[] strFruitArr = new String[6];
strFruitArr[0] = "Orange";
strFruitArr[1] = "Pear";
strFruitArr[2] = "Banana";
strFruitArr[3] = "Cherry";
strFruitArr[4] = "Lemon";
strFruitArr[5] = "Apple";
strFruitArr[6] = "Bar";
while(inVal > 0){
if(inVal == 0){
return strFruitArr[0];
}
else if (inVal == 7){
return strFruitArr[6];
}
else{
return strFruitArr[inVal];
}
}
}
As you can see, each "FruitVal" is assigned by taking for example "LeftVal" which is a randomly generated number, and applying that to one of the fruits from the "showFruit" function. I'm aware this is done completely wrong however i do not understand the different java functions to do so.
Could someone explain the basic java functions e.g. 'public static void' and try and help implement them in to this code correctly.
If anyone wants to see the full program code then please do ask, I wasn't sure if the full code was necessary, however it is only short.
Learn Java coding standards. Your code will be more readable.
You link them by having one method return the data that the other needs to have passed to it.
public void displayFruitOnScreen(String [] fruit) {
// display here
}
public String [] getFruit() {
// populate the fruit array here
}
Neither of these is static; they are associated with some instance of a Java class.

I am making a safe, compile-time String.format(...) equivalent. An issue still persist

Most people understand the innate benefits that enum brings into a program verses the use of int or String. See here and here if you don't know. Anyway, I came across a problem that I wanted to solve that kind of is on the same playing field as using int or String to represent a constant instead of using an enum. This deals specifically with String.format(...).
With String.format, there seems to be a large opening for programmatic error that isn't found at compile-time. This can make fixing errors more complex and / or take longer.
This was the issue for me that I set out to fix (or hack a solution). I came close, but I am not close enough. For this problem, this is more certainly over-engineered. I understand that, but I just want to find a good compile-time solution to this, that provides the least amount of boiler-plate code.
I was writing some non-production code just to write code with the following rules.
Abstraction was key.
Readability was very important
Yet the simplest way to the above was preferred.
I am running on...
Java 7 / JDK 1.7
Android Studio 0.8.2
These are unsatisfactory
Is there a typesafe alternative to String.format(...)
How to get string.format to complain at compile time
My Solution
My solution uses the same idea that enums do. You should use enum types any time you need to represent a fixed set of constants...data sets where you know all possible values at compile time(docs.oracle.com). The first argument in String.format seems to fit that bill. You know the whole string beforehand, and you can split it up into several parts (or just one), so it can be represented as a fixed set of "constants".
By the way, my project is a simple calculator that you probably seen online already - 2 input numbers, 1 result, and 4 buttons (+, -, ×, and ÷). I also have a second duplicate calculator that has only 1 input number, but everything else is the same
Enum - Expression.java & DogeExpression.java
public enum Expression implements IExpression {
Number1 ("%s"),
Operator (" %s "),
Number2 ("%s"),
Result (" = %s");
protected String defaultFormat;
protected String updatedString = "";
private Expression(String format) { this.defaultFormat = format; }
// I think implementing this in ever enum is a necessary evil. Could use a switch statement instead. But it would be nice to have a default update method that you could overload if needed. Just wish the variables could be hidden.
public <T> boolean update(T value) {
String replaceValue
= this.equals(Expression.Operator)
? value.toString()
: Number.parse(value.toString()).toString();
this.updatedString = this.defaultFormat.replace("%s", replaceValue);
return true;
}
}
...and...
public enum DogeExpression implements IExpression {
Total ("Wow. Such Calculation. %s");
// Same general code as public enum Expression
}
Current Issue
IExpression.java - This is a HUGE issue. Without this fixed, my solution cannot work!!
public interface IExpression {
public <T> boolean update(T Value);
class Update { // I cannot have static methods in interfaces in Java 7. Workaround
public static String print() {
String replacedString = "";
// for (Expression expression : Expression.values()) { // ISSUE!! Switch to this for Expression
for (DogeExpression expression : DogeExpression.values()) {
replacedString += expression.updatedString;
}
return replacedString;
}
}
}
So Why Is This An Issues
With IExpression.java, this had to hacked to work with Java 7. I feel that Java 8 would have played a lot nicer with me. However, the issue I am having is paramount to getting my current implementation working The issue is that IExpression does not know which enum to iterate through. So I have to comment / uncomment code to get it to work now.
How can I fix the above issue??
How about something like this:
public enum Operator {
addition("+"),
subtraction("-"),
multiplication("x"),
division("÷");
private final String expressed;
private Operator(String expressed) { this.expressed = expressed; }
public String expressedAs() { return this.expressed; }
}
public class ExpressionBuilder {
private Number n1;
private Number n2;
private Operator o1;
private Number r;
public void setN1(Number n1) { this.n1 = n1; }
public void setN2(Number n2) { this.n2 = n2; }
public void setO1(Operator o1) { this.o1 = o1; }
public void setR(Number r) { this.r = r; }
public String build() {
final StringBuilder sb = new StringBuilder();
sb.append(format(n1));
sb.append(o1.expressedAs());
sb.append(format(n2));
sb.append(" = ");
sb.append(format(r));
return sb.toString();
}
private String format(Number n) {
return n.toString(); // Could use java.text.NumberFormat
}
}

Utilizing Comparable for 2 Sort Criteria when Sorting an Array of Objects

I've been working at this for a couple hours now and I feel (I hope) I'm right on the verge of figuring it out. This program reads in a bunch of values from an external file and places them in an array of objects which seems to be working just fine.
The Objects properties are:
Bank Account #
Customer Name
Bank Account Balance
1. I can output them in order of Account # (That's how their read in from the file, no sorting is necessary)
2. I've setup a method from implementing Comparable to sort by Bank Account Balance and it's working fine.
3. I need a second sort method, to sort by Customer Name.
- The problem I'm having with this is based on the research I've done and what I've tried I've come to the conclusion that the only way to make this work will be to build my own Comparable Objects (sorry if my terminology is skewed.) I've attempted this as well multiple times with both Java Doc and some similar questions on SE.
When all is said and done I'm going to throw some Listeners into my checkbox group to allow the user to toggle the different sort methods.
Here's the chunks i'm working on:
public class bankAccounts implements Comparable<bankAccounts> {
/* PRIVATE FIELDS HERE, FOLLOWED BY TYPICAL GET AND SET METHODS */
/*SORTS BY ACCOUNT BALANCE WORKING GREAT*/
public int compareTo(bankAccounts b) {
if (accountBalance < b.accountBalance)
{
return -1;
}
if (accountBalance > b.accountBalance) {
return 1;
}
return 0;
}
/* BEGIN SNIPPET OF MAIN CLASS */
/*METHOD I CALL FROM MAIN CLASS, SORTS BY BALANCE ^^ AS SEEN ABOVE */
Arrays.sort(retrievedAccounts);
for (int i=0; i<retrievedAccounts.length; i++) {
String resultFull = Integer.toString(retrievedAccounts[i].getAccountNumber()) + retrievedAccounts[i].getAccountLastName() + Double.toString(retrievedAccounts[i].getAccountBalance());
box.append(resultFull + "\n");
}
/* NORMAL METHOD WHICH OUTPUTS IN ORDER OF ACCOUNT NUMBER, NO SORTING HAPPENING HERE */
for(int x = 0; x < retrievedAccounts.length; ++x)
{
String resultFull=Integer.toString(retrievedAccounts[x].getAccountNumber()) + retrievedAccounts[x].getAccountLastName() + Double.toString(retrievedAccounts[x].getAccountBalance());
box.append("\n\n\n" + resultFull + "\n\n");
}
I'm hoping someone will have some insight towards a next step which might allow me to finish this up. If you have suggestions to take this a completely different direction I'm open to that as well.
This is an idea haven't tested.
Create a another private method to store compareType
public class bankAccounts implements Comparable<bankAccounts> {
private int compareType = 0; // 0 - compare by balance 1-compare by name
In your compare method
public int compareTo(bankAccounts b) {
if(this.compareType == 0){
if (accountBalance < b.accountBalance)
{
return -1;
}
if (accountBalance > b.accountBalance) {
return 1;
}
return 0;
}else{
return customerName.compareTo(b.customerName)
}
Use an implementation of Comparator<bankAccounts> that compares the names of your objects and pass that into the Arrays.sort() method.
Use an anonymous class like this:
Arrays.sort(retrievedAccounts, new Comparator<bankAccounts>() {
public int compare(bankAccounts a, bankAccounts b) {
return a.getName().compareTo(b.getName());
}
});
This code assumes you have a getter method on bankAccounts for customer name called getName()
You would do well to follow java naming conventions:
class names start with a capital letter
class names are singular, not plurals

Categories