Python Program converted into Java - java

Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time.
Could someone please help with what I've done and umm give me some advice? Maybe a good site for a beginner.... Someone that kinda knows Python (only from a first CS course perspective).
1) In python
def winCraps():
roll = rollDice()
if roll == 7 or roll == 11:
return True
elif roll == 2 or roll == 3 or roll == 12:
return False
else:
return rollForPoint(roll)
This is my attempt at the conversion of it over to java
public int winCraps{
roll = rollDice();
if (roll = 7 && 11){
return (true);
}
else (roll =2 && 3 && 12){
return(false);
}
else{
return rollforPoint(roll);
}
}
2) Python
def rollDice():
raw_input("Press <Enter> to roll...")
die1 = randrange(1,7)
die2 = randrange(1,7)
sum = die1 + die2
print "You rolled", die1, "+", die2, "=", sum
return sum
This one confused the hell out of me. What would randrange be in Java??
Java
static int rollDice(){
System.out.print("Press <Enter> to roll...");
double die1 = Math.random();
double die2 = Math.random();
die1 = (int) die1*6+1;
die2 = (int) die2*6+1;
int sum = (int)die1 + (int)die2;
System.out.println("You rolled "+die1+ " + "+die2+ " = "+sum+".");
return sum;
}
*please bear in mind that I'm just learning this stuff lol

You need to fix your if statements the "==" operator checks for equality, and you must put the variable you are checking against in each section of the statement.
public int winCraps{
roll = rollDice();
if (roll == 7 || roll == 11) {
return true;
}
else if(roll == 2 || roll == 3 || roll == 12) {
return false;
}
else{
return rollforPoint(roll);
}
}
In you rollDice() method, the way you assign values to each die is incorrect. I recommend reading up on random numbers (since this is homework, I'll leave that to you).
Also, remember in java you must always end each statement with a semicolon

What would randrange be in Java?
You can get a random integer in a specific range from Java's Random class by calling the nextInt(int n) method. For example,
Random rand = new Random();
int a = rand.nextInt(7);
will give you a random integer >= 0 and < 7. This isn't exactly the same as randrange in Python, but you could use it as the index to an array of objects, or as the value of a roll of a single die.

Randrange can be replaced by methods in java.util.Random. Like Python, Java has an extensive standard library which you should reference.

1) In Java "OR" operator is "||" not "&&" and comparison operator is "==" as in Python
So
if roll == 7 or roll == 11:
Should be
if( roll == 7 || roll == 11 ) {
and not
if( roll = 7 && 11 ){
2) randrange is : random generator from there you can search: Random in Java
Which will lead you to something like: Random.nextInt()
Use this algorithm ( a) search Internet for Python function, b) understand what it does c) search it in java ) for the next assignment you have and you're done.
You can always ask here again, that's what this site is all about after all

I'd recommend that you look up the docs on randrange(). Once you know exactly what it does, google for the those keywords, plus the word Java.
One thing you'll quickly discover in working with languages is that the APIs can be very different. There might not be an equivalent of randrange in Java, but you might be able to find two or three functions that you can combine to do the same thing.

System.out.print isn't going to cause the system to wait for someone to hit the enter key. For that, you need to do something with System.in, most likely System.in.read(), as it blocks while waiting for input.
Also, in Java, a program starts executing with the main method. To be exact, an executable class starts something like this:
// You'll need the Random class, as per other answers
import java.util.Random;
// assuming WinCraps is the class name
public class WinCraps {
// args in this example is a string array of command-line arguments
public static void main(String[] args) {
// This is where your main method (that calls winCraps?) would be
}
// Other methods
}
Also, any method in this class called directly from main must also be static.

Write out in English what the Python program does. Go through it line by line and explain to yourself what computations are evoked, in other words...what is happening?
Afterwards, write the Java program from that description.
Never ever try to convert the text of a program from one language to another. You'll run into a LOT of problems that way because every language is different, no matter how similar they look.

One major error in your first program that you have in the Java conversion is the conditionals.
Something like (roll =2 && 3 && 12) assigns 2 to roll and then applies AND operators. You also forgot the if. You have elseif in Python.
You want something like:
else if(roll==2 || roll==3 || roll==12)
As for random numbers, there is a function for that in Java.

Related

Beginner Boolean compiling error

I am very new to Java (doing a beginners university module) so sorry for the probably silly question. I am trying to verify whether a ragged array is a 'tridiagonal matrix'.
It is valid if it is of length 3 at the first level and of length n − 1, n, and n − 1 at the second level. I intended to come up with a code to firstly verify the length is 3, then find the longest length array within it for n, then finally verify each length.
For whatever reason my code won't compile but I'm not seeing an error message, just a red exclamation mark on the class. I assume this means there are multiple errors. If anyone could point them out it would be a massive help.
static boolean isValidTridiagonal ( double [][] m)
{
if (double [][]=new double [3][])
{
int n = 0;
for(int i = 0; i < m.length; i++)
{
if(m[i].length > n)
{
n = m[i].length;
if( (m[0].length = n-1) && (m[1].length = n) &&(m[2].length=n-1))
{
return true
}
else
{
return false
}
}
else
{
return false
}
}
Thanks very much!
I agree with Foolish in the comments that it's helpful to use an IDE that can highlight syntax errors and other problems with the code, it really makes a huge difference. Apart from that, another general strategy is to always code in "baby steps": do only the minimal thing to test if the code works, compile and test often. And if you still have troubles, you can always comment out chunks of your code when searching for the offending bits.
Having said that, the errors that I see in your code are:
if (double [][]=new double[3][])
If you want to test the length of the input, you can do if (m.length == 3)
In
if( (m[0].length = n-1) && (m[1].length = n) &&(m[2].length=n-1))
you're not testing for equality, but rather trying to put the values n-1 etc into m[0].length, which is not going to work. What you probably meant was
if( (m[0].length == n-1) && (m[1].length == n) &&(m[2].length==n-1))
In
return true
you're missing a semicolon. The compiler is whiny about things like that and unless you use an IDE or learn to interpret the compiler error messages, it can be really painful to find such errors.
Finally, of course, the answer by vasste provides a much simpler solution to your actual task, so it's worth looking into that :).
Why do you need all that loops? If all arrays cannot be null, than
static boolean isValidTridiagonal(double[][] m) {
return m.length == 3 && m[0].length == m[1].length - 1 && m[2].length == m[0].length;
}
You're missing a few braces at the end but, judging from your indentation, you just forgot to copy them.
You're missing semicolons from the end of the return lines.
The condition within this if statement if (double [][] = new double [3][]) is not a valid expression. You simply want to evaluate the length, which you can do like if (m.length == 3). You did the same thing later on.
The line including (m[0].length = n-1) && (m[1].length = n) && (m[2].length=n-1) is not valid because you are performing assignment (=) in all three cases. An equality check is the double equals operator ==.
You do not return a value in every case. You can fix this by adding return false; after the closing brace of your first if statement, i.e. the last line of the function.
This is enough to get your code to compile. As mentioned in another answer though, your logic is confusing and without actually tracing it through I would speculate that it will not work as you would expect.
If I have understood your requirements correctly, you can rewrite the entire function as:
static boolean isValidTridiagonal ( double [][] m)
{
return m.length == 3 &&
m[0].length + 1 == m[1].length &&
m[2].length + 1 == m[1].length;
}
A proper IDE - Netbeans, Eclipse, etc. - will give you fairly descriptive error messages to show you where you've gone wrong.
This is basically completely stylistic but I wish someone had pointed this out to me earlier. If you ever find yourself writing code in this form:
if( (m[0].length == n-1) && (m[1].length == n) && (m[2].length == n-1))
{
return true;
}
else
{
return false;
}
know that you can save yourself so many lines without losing any readability by instead writing:
return (m[0].length == n-1) && (m[1].length == n) && (m[2].length == n-1);

Recursion and Recursive Methods

I'm studying for my computer science final and am going back over some of the things that I never quite grasped when we went over them in class. The main thing being recursion. I think I've got the hang of the simple recursion example but am trying to work through one that was on a previous exam and am having trouble figuring out how it should be done.
Here is the question:
Texas numbers (Tx(n)) are defined as follows for non-negative numbers (assume true):
Tx(n) = 10 if n is 0
Tx(n) = 5 if n is 1
Tx(n) = 2*(Tx(n-1) + Tx(n-2) if n >= 2
We are then to write the recursion function for Texas numbers, after making some corrections after the test, here's what I've come up with, I think it's right, but not 100% sure.
public int Tx(int n) {
if(n == 0)
return 10;
else if (n == 1)
return 5;
else
return 2*(Tx(n-1) + Tx(n-2));
}
Then we are asked to computer the value of Tx(5). This is where I'm stuck. If the return statement for the else was simply n-1, I think I'd be able to figure it out, but the n-1 + n-2 is completely throwing me off.
Can anyone explain how this would work, or share some links that have similar examples. I have tried looking this up online and in my textbook but the examples I've found are either so advanced that I have no clue what's going on, or they only deal with something like return n-1, which I already know how to do.
Let's start with Tx(2). n > 1, so we have 2*(Tx(n-1) + Tx(n-2)) which is 2*(Tx(1) + Tx(0)).
But we already know Tx(1) and Tx(0)! So just substitute them in and you get 2*(5 + 10) -> 30. Great, so now we know T(2).
What about T(3)? 2*(Tx(2) + Tx(1)). Nice, we already know these too :) Again, just fill them in to get 2*(30 + 5) -> 70.
You can work forwards to get to Tx(5).
Your code is logically correct, you should just be using == to test equality, a single = is for assignment.
When you run your method, it will work backwards and solve smaller and smaller subproblems until it gets to a point where the answer is known, these are your base cases.
Tx(3)
2* Tx(2) + Tx(1)
2*Tx(1) + Tx(0) (5)
(5) (10)
In order for recursion to work, whatever you are doing each time to break the problem down into smaller problems needs to make some progress towards the base case. If it doesn't, you will just infinitely recurse until your computer runs out of space to store all of the repeated calls to the same function.
public int Tx(int n) {
if(n == 0)
return 10;
else
return Tx(n+1); // n will never reach 0!
}
Tx(1) becomes Tx(2) -> Tx(3) -> Tx(4) -> Tx(5) etc.
Your implementation is good, only one minor mistake - in the conditions you should replace = with == - it's not an assignment - it's a comparison.
By the way, what would you expect your method to return for Tx(-1) ?
You have implemented it right just change = with ==.
If you want to further reduce the time complexity you can store the result in an array global to the function so that your function doesnot compute results again and again for a same number this will only save you some time for large computations.
You can use something like this.
public int tx(int n , int []arr) {
if (arr[n] == 0) {
if (n == 1) {
arr[n] = 10;
}
else if (n == 2) {
arr[n] = 5;
}
else {
arr[n] = 2 * (tx((n - 1), arr) + tx((n - 2), arr));
}
}
return arr[n];
}
See whenever you ask the computer for the value Tx(5) it will call the recursive function and so the program will execute the else part because value of n=5.
Now in the else part 2*(Tx(n-1)+Tx(n-2)) will be executed.
In first iteration it will become 2*((2*(Tx(3)+Tx(2)))+(2*(Tx(2)+Tx(1)))) . The iteration will be continued until the value of n become 0 or 1.

Java Palindrome, methods, and abstract classes?

I'm stuck on an assignment, largely due to an extreme lack of examples or even relevant diagrams from my textbook and class material.
The reason I structured the program the way I did is because I'm required to use 4 methods: a main method that executes all the other methods, a retrieve input method, a check method, and a display method. I love to hear about best practices, but I'm forced to code like this.
My main problem is the abstract classes I have. Any variables I write in one method won't be resolvable in another, I don't know how to make the variables global.
secondly, the code does not compile, the example I've found doesn't have a classic main, i don't really know how to make main implement methods, or make the compiler happy with abstraction.
also no clue on how to take my boolean result and use that to display the results in the display method. yes its asinine, I'd rather just do it in the check method.
all i know for sue is that my "logic" so far works. i think. any help to point me in the right direction would be very much appreciated. if thee is a way to do this without abstract classes i'd love to hear it, i think the abstraction is unnecessary.
well here's my monster so far:
import javax.swing.JOptionPane;
interface Palindrome {
void retrieveInput(String[] args);
boolean Check(String s);
void display();
}
abstract class Sub_Palindrome implements Palindrome {
public void retrieveInput(String[] args)
{
String Uinput;
int number1;
int digit1; // first digit
int digit2; // second digit
int digit3;
int digit4; // fourth digit
int digit5; // fifth digit
Uinput = JOptionPane.showInputDialog("Enter A 5 Digit Integer");
try { //Sanitize user input, make sure input entered is a number
number1 = Integer.parseInt(Uinput);
} catch (NumberFormatException String) {
JOptionPane.showMessageDialog(null, "Input invalid, please enter an integer",
"///-D-A-T-A---E-R-R-O-R-\\\\\\", JOptionPane.ERROR_MESSAGE);
return;
}
if (number1 < 10000 || number1 > 99999) { //Sanitize user input, make sure the given number is between 10000 and 99999
JOptionPane.showMessageDialog(null,
"The number entered must be between 10000 and 99999",
"///-D-A-T-A---E-R-R-O-R-\\\\\\", JOptionPane.ERROR_MESSAGE);
return;
}
}
public boolean Check(String s)
{
digit1 = number / 10000;
digit2 = number / 1000 % 10;
digit3 = number % 1000 / 100 % 10; // is the third digit even necessary?
digit4 = number % 10000 % 1000 % 100 / 10;
digit5 = number % 10000 % 1000 % 100 % 10;
if (digit1 == digit5 && digit2 == digit4)
return true;
else
return false;
}
public void display()
{
//display output text based upon result from IsPalinDrome
//after displaying result, start from the beginning and ask user to input data again
}
}
Move the variables outside methods and put directly in class scope
Writing main method is the first thing you learn in java. Look into your tutorial again
You can use a boolean variable boolean displayCheck = false; and set the same
And one question from my side: If your code doesn't compile what makes you feel that the logic is correct?

HOW to port "compact" Python to "compact" Java?

A friend is doing an online Scala course and shared this.
# Write a recursive function that counts how many different ways you can make
# change for an amount, given a list of coin denominations. For example, there
# are 3 ways to give change for 4 if you have coins with denomiation 1 and 2:
# 1+1+1+1, 1+1+2, 2+2.
If you are attending and still working on a solution, don't read this!
(disclaimer: even if my Python solution may be wrong, I don't want to influence your thinking if you are on the course, one way or the other! I guess it is the thinking that goes into it that yields learning, not just the "solving"...)
That aside...
I thought I'd have a go at it in Python as I don't have the Scala chops for it (I am not on the course myself, just interested in learning Python and Java and welcome "drills" to practice on).
Here's my solution, which I'd like to port to Java using as compact a notation as possible:
def show_change(money, coins, total, combo):
if total == money:
print combo, '=', money
return 1
if total > money or len(coins) == 0:
return 0
c = coins[0]
return (show_change(money, coins, total + c, combo + [c]) +
show_change(money, coins[1:], total, combo))
def make_change(money, coins):
if money == 0 or len(coins) == 0:
return 0
return show_change(money, list(set(coins)), 0, [])
def main():
print make_change(4, [2, 1])
if __name__ == '__main__':
main()
Question
How compact can I make the above in Java, allowing the use of libraries external to the JDK if they help?
I tried doing the porting myself but it was getting very verbose and I thought the usual "there must be a better way of doing this"!
Here my attempt:
import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
public class MakeChange {
static int makeChange(int money, int[] coins) {
if (money == 0 || coins.length == 0) {
return 0;
}
return showChange(money, Ints.asList(coins), 0, new ArrayList<Integer>());
}
static int showChange(int money, List<Integer> coins, int total,
List<Integer> combo) {
if (total == money) {
System.out.printf("%s = %d%n", combo, total);
return 1;
}
if (total > money || coins.isEmpty()) {
return 0;
}
int c = coins.get(0);
List<Integer> comboWithC = Lists.newArrayList(combo);
comboWithC.add(c);
return (showChange(money, coins, total + c, comboWithC) + showChange(money,
coins.subList(1, coins.size()), total, combo));
}
public static void main(String[] args) {
System.out.println(makeChange(4, new int[] { 1, 2 }));
}
}
Specifically, what I dislike a lot is having to do the stuff below just to pass a copy of the list with an element appended to it:
List<Integer> comboWithC = Lists.newArrayList(combo);
comboWithC.add(c);
Please show me how compact and readable Java can be. I am still a beginner in both languages...
Really, almost everything you're doing here is directly convertible to Java, without much extra verbosity.
For example:
def make_change(money, coins):
if money == 0 or len(coins) == 0: return 0
return calculate_change(money, list(set(coins)), 0)
The obvious Java equivalent is:
public static int make_change(int money, int coins[]) {
if (money == 0 || coins.length == 0) return 0;
return calculate_change(money, coins, 0);
}
A few extra words here and there, an extra line because of the closing brace, and of course the explicit types… but beyond that, there's no big change.
Of course a more Python and Javariffic (what is the equivalent word?) version would be:
def make_change(money, coins):
if money == 0 or len(coins) == 0:
return 0
return calculate_change(money, list(set(coins)), 0)
The obvious Java equivalent is:
public static int make_change(int money, int coins[]) {
if (money == 0 || coins.length == 0) {
return 0;
}
return calculate_change(money, coins, 0);
}
So, Java gets one extra closing brace plus a few chars of whitespace; still not a big deal.
Putting the whole thing inside a class, and turning main into a method, adds about 3 more lines. Initializing an explicit array variable instead of using [2, 1] as a literal is 1 more. And System.out.println is a few characters longer than print, and length is 3 characters longer than len, and each comment takes two characters // instead of one #. But I doubt any of that is what you're worried about.
Ultimately, there's a total of one line that's tricky:
return (calculate_change(money, coins, total + c, combo + [c]) +
calculate_change(money, coins[1:], total, combo))
A Java int coins[] doesn't have any way to say "give me a new array with the tail of the current one". The easiest solution is to pass an extra start parameter, so:
public static int calculate_change(int money, int coins[], int start, int total) {
if (total == money) {
return 1;
}
if (total > money || coins.length == start) {
return 0;
}
return calculate_change(money, coins, 0, total + coins[start]) +
calculate_change(money, coins, start + 1 total);
}
In fact, nearly everything can be trivially converted to C; you just need to pass yet another param for the length of the array, because you can't calculate it at runtime as in Java or Python.
The one line you're complaining about is an interesting point that's worth putting a bit more thought into. In Python, you've got (in effect):
comboWithC = combo + [c]
With Java's List, this is:
List<Integer> comboWithC = Lists.newArrayList(combo);
comboWithC.add(c);
This is more verbose. But that's intentional. Java List<> is not meant to be used this way. For small lists, copying everything around is no big deal, but for big lists, it can be a huge performance penalty. Python's list was designed around the assumption that most of the time, you're dealing with small lists, and copying them around is perfectly fine, so it should be trivial to write. Java's List was designed around the assumption that sometimes, you're dealing with huge lists, and copying them around is a very bad idea, so your code should make it clear that you really want to do that.
The ideal solution would be to either use an algorithm that didn't need to copy lists around, or to find a data structure that was designed to be copied that way. For example, in Lisp or Haskell, the default list type is perfect for this kind of algorithm, and there are about 69105 recipes for "Lisp-style lists in Java" or "Java cons" that you should be able to find online. (Of course you could also just write your a trivial wrapper around List that added an "addToCopy" method like Python's __add__, but that's probably not the right answer; you want to write idiomatic Java, or why use Java instead of one of the many other JVM languages?)

Java boolean if question

I am making a lottery program where I am asking if basically they would like a quick pick ticket. The numbers for their ticket of course would be random since it is a quick pick but the first four numbers range from 0-9 while the fifth number only goes up to 0-4. I am trying to ask them to input a button such as either "1" for no or "2" for yes if they don't want one then it would skip this step. But I am doing the boolean part incorrectly though. Could someone help me out?
Here is an example
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
I still haven't gotten around to making the line of code for the final number of 0-4, just the first four numbers, so I haven't forgotten that.
Your code for case 2 immediately does a return true; which ends the method (I assume this is in a method) right then and there. Your other lines don't get execute at all.
Consider using a switch() statement here, it'll make it easier to read:
switch(QuickPick)
{
case 1:
return false;
case 2:
int n = (int)(Math.random()*9+0); // Why is n here? You don't do anything with it?
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
default:
// Uh oh - someone did something bad maybe just return false?
return false;
}
Also your code for case 2 is definitely wrong, you need to generate a total of five numbers, using bounds 0-9 for the first 4 and 0-4 for the last one. You'll want to use Java's Random to do this (not Math.Random) something like:
Random rand = new Random();
int somethingRandom = rand.nextInt(10);
// Will give you an integer value where 0 < val < 10
// You can call rand.nextInt as many times as you want
To avoid doing your homework for you -- I'll follow the typical CS textbook line and say "Implementation left as an exercise."
The code after return true will not be executed - you need to put that prior to the return statement
Like Marvo said, you dropped a brace in your if.
But you also have faulty logic. I'm not quite sure what the purpose of the method you're in is (that returns a boolean value). But your last few lines will never be reached unless the user types in something like 3 or 42.
Assuming the method is supposed to a) Ask if the user wants a Quick Pick b) Calculate the Quick Pick, if desired c) Return true/false depending on whether the Quick Pick happened or not, you should have:
public boolean doQuickPick()
{
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
}
}
As a separate issue, it'd be much better style to break that into several methods. boolean yesNoPrompt(String message), generateQuickPick(), etc.
Your question is kind of unclear, so I'm afraid I can't be much more help than that. Do post any clarifications / further questions if you have them.
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
In the above copied code from your question, I see that you will be getting compilation errors in your IDE. Your IDE will complain about "Unreachable Code" for the line that is just below the return statement. So, you need to put the return statement at the end of the if block.

Categories