It's intuitive once you understand two key components of Python: magic methods and scope. Magic methods are Python's way of homogenizing and abstracting out some top-level object orientation/handling (e.g. __init__ and __del__ for classes). All magic methods have the __<name>__ syntax so they're easy to recognize, making it easier to read code you didn't write. Scoping dealing with what variables are accessible in a current context/namespace and are a consequence of how bindings work in the Python interpreter works- this article explains it pretty well. Once I got a handle on both of these, working with Python became simple for me.
I just think of __init__ as the constructor. Technically it isn't, it's the initializer, but that's splitting hairs.
Passing self makes sense when you realize other languages (or at least C++ for sure) do the same thing implicitly. When a C++ class method is compiled, the function signature is actually altered to include a constant this parameter. And any calls to it are altered to pass in the address of the object. So Python is doing the same thing, just explicitly.
You have an Object* and want to make an array out of it. So you just make a pointer to the pointer: (Object*)*, or Object**. That's where you are. Now you just need to perform that step an additional time. You want to make an array out of those Object**, so you just make a pointer to it: (Object**)*, or Object***.
Code:
Object*** array = new Object**[size]
will create a dynamic array containing a dynamic arrays containing Object-pointers.
Though just like when you create an array of pointers to Object, the objects won't have actually been created. You have to loop through the array and create the objects that you're pointing to. Similarly, you'll have to loop through that array to create the arrays containing the pointers.
Code:
for (int i=0; i<size; i++) {
array[i] = new Object*[size];
}
This creates the 2D array, that can store SIZE number of arrays?
Then
Code:
for (int i=0; i<size; i++) {
array[i] = new Object*[size];
}
[/QUOTE]
This actually creates SIZE number of dynamic arrays? Isn't the syntax incorrect then? You say new Object*[size]. But wouldn't a 1D array of pointers to Objects be Object**[size]?
Then how do I finally populate these arrays with the pointers?
Code:
for (int i = 0; i < numberofrows; i++) {
for (int j = 0; j < numofCols; j++) {
array[i][j] = *Object}
}
This creates the 2D array, that can store SIZE number of arrays?
Then
Code:
for (int i=0; i<size; i++) {
array[i] = new Object*[size];
}
This actually creates SIZE number of dynamic arrays? Isn't the syntax incorrect then? You say new Object*[size]. But wouldn't a 1D array of pointers to Objects be Object**[size]?
Then how do I finally populate these arrays with the pointers?
Code:
for (int i = 0; i < numberofrows; i++) {
for (int j = 0; j < numofCols; j++) {
array[i][j] = *Object}
}
I have been running into trouble with using MinGW. I have not been able to get external libraries (specifically BLAS and LAPACK) to link with my programs - most external libraries assume you use MVS or perhaps I'm just being dumb
Anyways, instead of spending hours trying to figure out how to get each library to work, I am thinking about just dual-booting Ubuntu. Will this negatively impact performance and how compatible is Ubuntu with dedicated Nvidia GPUs (GTX 970 in my case)?
I have been running into trouble with using MinGW. I have not been able to get external libraries (specifically BLAS and LAPACK) to link with my programs - most external libraries assume you use MVS or perhaps I'm just being dumb
Anyways, instead of spending hours trying to figure out how to get each library to work, I am thinking about just dual-booting Ubuntu. Will this negatively impact performance and how compatible is Ubuntu with dedicated Nvidia GPUs (GTX 970 in my case)?
No, it's more likely an issue of you doing something wrong. Running your program from the command line and it launching visual studio tells me that we're probably having a communication breakdown. Because that really makes no sense whatsoever. I think I'm saying one thing, and you're interpreting it as something else.
Try following these steps.
1. Open Visual Studio
2. Click File -> New -> Project
3. Choose Templates -> Visual C++ -> Win32 Console Application
4. Press Ok
5. Click Finish. You will be looking at a file like this:
Code:
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int main()
{
return 0;
}
6. Delete everything and paste this in:
Code:
#include "stdafx.h"
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
scanf_s("%d", &n);
return 0;
}
7. Press Ctrl+Shift+B
8. Press F5
This should work. And if it does, it means you are doing something wrong / differently in your steps.
I can't see your screen or your code, or tell what buttons you're pressing to build, compile, and run, so all I can tell is that something is happening that is impossible.
Man, I got nothing. I've never seen that before. I do find it a bit strange that you're running as Administrator, but I don't think that would make a difference. Only thing I can think of is to try running your program from the command line. (Which is what you tried to do earlier but did the wrong thing and somehow ended up runnign visual studio). To do that you would need to find the location of the executable on your disk (probably called ConsoleApplication14.exe) and run that from windows explorer or from the command line.
You can try reinstalling as haly suggested earlier. I'm not convinced it will fix it and it takes a couple hours so attempt at your own peril.
I don't want to have to pay for MSV C and Intel compilers.
Ok, I have found Visual Studio Community is for free, and I may be able to get free Intel Fortran as a student, but while I am a full time Ph D student I am getting paid for my research soo..?
I am having trouble understanding this C code for my UNIX class. I was given this code and I have to explain how it works. The single line "//'' comments are what I wrote. The "/*...*/ quotes are from the professor. I understand that it is recursively printing each directory and the files within the directory, but there are a lot of functions used that I don't understand. For example, I don't get how a DIR pointer can be assigned to adirent structure pointer. I've tried to read up on a lot of these functions, but I feel like I don't understand what a lot of these functions do or the data structures they operate on. I'm not sure if there is a concise way to explain what is happening that doesn't require me to understand fully what is happening behind the scene, which our professor does not expect us to know.
Code:
/* printdir1.c
* Documentation intentionally left out as part of the assignment
*/
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir(char *dir, int depth)
{
DIR *dp; // A pointer to a directory stream
struct dirent *entry; // A struct, directory entries
struct stat statbuf; //A struct of stats on a file
// Open a directory, and if it is NULL, the directory cannot be opened and return
if((dp = opendir(dir)) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
chdir(dir); // Change the current working directory to dir
//
while((entry = (dp)) != NULL) {
lstat(entry->d_nareaddirme,&statbuf);
if(S_ISDIR(statbuf.st_mode)) {
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0) {
continue;
}
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else {
printf("%*s%s\n",depth,"",entry->d_name);
}
}
chdir("..");
closedir(dp);
}
/* Now we move onto the main function. */
int main()
{
printf("Directory scan of /home:\n");
printdir("./",0); // print current directory entries
printf("done.\n");
exit(0);
}
Man, I got nothing. I've never seen that before. I do find it a bit strange that you're running as Administrator, but I don't think that would make a difference. Only thing I can think of is to try running your program from the command line. (Which is what you tried to do earlier but did the wrong thing and somehow ended up runnign visual studio). To do that you would need to find the location of the executable on your disk (probably called ConsoleApplication14.exe) and run that from windows explorer or from the command line.
You can try reinstalling as haly suggested earlier. I'm not convinced it will fix it and it takes a couple hours so attempt at your own peril.
I've tried just about everything at this point, and nothing seems to work. What I find interesting is that this same exact code works on another computer, which led me to believe that this could be an issue with the OS. Should I attempt using another IDE?
I don't want to have to pay for MSV C and Intel compilers.
Ok, I have found Visual Studio Community is for free, and I may be able to get free Intel Fortran as a student, but while I am a full time Ph D student I am getting paid for my research soo..?
I've tried just about everything at this point, and nothing seems to work. What I find interesting is that this same exact code works on another computer, which led me to believe that this could be an issue with the OS. Should I attempt using another IDE?
According to my research this means that the pointer I'm deferencing hasn't been initialized. But I thought for sure that I initialized it.
here is the relevant code...
Code:
Object*** arr2d= new Object**[row];
for (int i = 0; i < row; i++)
{
arr2d[i] = new Object*[col];
}
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
arr2d[i][j] = NULL;
}
}
and now the code that is trying to access this
Code:
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (arr2dt[i][j] == NULL)
{
cout << "1 " << endl;
}
else
{
cout << "0 " << endl;
}
}
cout << endl;
}
Weird. That's why i told you to do Ctrl+Shift+F5 instead of F5 earlier, I thought that would defeat that. Guess I should have just asked the real question, lol
Weird. That's why i told you to do Ctrl+Shift+F5 instead of F5 earlier, I thought that would defeat that. Guess I should have just asked the real question, lol
Weird. That's why i told you to do Ctrl+Shift+F5 instead of F5 earlier, I thought that would defeat that. Guess I should have just asked the real question, lol
The simple fact it isn't free for anyone and any use will make me choose MinGW or anything equivalent... even if it's harder.
Especially if I develop code for others, since I want others to be able to compile it and use it even if they don't qualify for free MSVC. If it works for them, then it's great, but I want to offer an alternative.
I have been running into trouble with using MinGW. I have not been able to get external libraries (specifically BLAS and LAPACK) to link with my programs - most external libraries assume you use MVS or perhaps I'm just being dumb
Anyways, instead of spending hours trying to figure out how to get each library to work, I am thinking about just dual-booting Ubuntu. Will this negatively impact performance and how compatible is Ubuntu with dedicated Nvidia GPUs (GTX 970 in my case)?
I used BLAS and LAPACK with both Cygwin (and its infamous 2.96 gcc) and MinGW a bit more than ten years ago, so it can be done, but I remember having troubles too... I don't remember how I solved it, but I had to recompile some libraries IIRC.
I'm not sure I understand the performance question. I'm convinced Ubuntu support the GTX 970, althiugh you may lack some acceleration. Is it a graphic heavy software you're writing?
You can also use a virtual box to run Linux inside Windows, if you're doing computations, it won't be much slower. I've already crossed compiled windows executables in a linux vurtual machine running in windows, that's crude, but sometimes practicality wins when you're in a hurry.
Well, this is my first time posting here, but hopefully a fellow gaffer can help.
Basically, I created a javascript array,... (a dynamic one)
which populates "elements" based on user clicks (if you click a certain area, it checks if is been clicked, so it creates a "push" value) but if the area is clicked again, it looks for that value, and if found, it uses "split" to remove said value.
Now the problem im having is that I need to calculate "onclick" what a user has clicked on, based off what the javascript array contains, then sum the areas "value" and post to next page.
If this makes sense, i will post the code, as i've been going at this for the past week, and i've run out of hair to pull on my head.
I already asked a friend who's very good a C/C++ arrays, but had no idea how to solve this for javascript.
Well, this is my first time posting here, but hopefully a fellow gaffer can help.
Basically, I created a javascript array,... (a dynamic one)
which populates "elements" based on user clicks (if you click a certain area, it checks if is been clicked, so it creates a "push" value) but if the area is clicked again, it looks for that value, and if found, it uses "split" to remove said value.
Now the problem im having is that I need to calculate "onclick" what a user has clicked on, based off what the javascript array contains, then sum the areas "value" and post to next page.
If this makes sense, i will post the code, as i've been going at this for the past week, and i've run out of hair to pull on my head.
I already asked a friend who's very good a C/C++ arrays, but had no idea how to solve this for javascript.
So the user can click on, let's say countries in a world map, and your app then calculates the sum of the population? I'd probably abuse a multicheckbox element.
But to get back to your question, if you have an array of DOM elements you can iterate over them and add up the values.
Code:
var sum = 0;
for (var i=0; i<array.length; ++i) {
sum += array[i].data.value;
}
The simple fact it isn't free for anyone and any use will make me choose MinGW or anything equivalent... even if it's harder.
Especially if I develop code for others, since I want others to be able to compile it and use it even if they don't qualify for free MSVC. If it works for them, then it's great, but I want to offer an alternative.
I just learned about underhanded programming challenges. Just digging through some examples and it's really giving me ideas to how code can be used. These are fun.
Well, this is my first time posting here, but hopefully a fellow gaffer can help.
Basically, I created a javascript array,... (a dynamic one)
which populates "elements" based on user clicks (if you click a certain area, it checks if is been clicked, so it creates a "push" value) but if the area is clicked again, it looks for that value, and if found, it uses "split" to remove said value.
Now the problem im having is that I need to calculate "onclick" what a user has clicked on, based off what the javascript array contains, then sum the areas "value" and post to next page.
If this makes sense, i will post the code, as i've been going at this for the past week, and i've run out of hair to pull on my head.
I already asked a friend who's very good a C/C++ arrays, but had no idea how to solve this for javascript.
The licenses requirements say it's free for "non enterprise users". Looking at the finer print says "Enterprise organizations are defined as >250 PCs or > $1 Million US Dollars in annual revenue"
The licenses requirements say it's free for "non enterprise users". Looking at the finer print says "Enterprise organizations are defined as >250 PCs or > $1 Million US Dollars in annual revenue"
Ok so... I'm working sort of on a game/school thing. I have that 2D dynamic array filled with Objects that you guys helped me with.
For this project, I have to have Objects move on the simulated grid. They can move up, down, left, or right.
When I move Objects I accomplish this by doing something like:
array[j+1] = new Object(stuff for constructor);
array[j] = NULL
So the new position gets a new Object. Is this potentially a huge problem because I keep creating new dynamically allocated objects, and may run out of memory on the heap. Is this an actual concern, or is there enough memory on the heap that I don't have to worry?
Should I instead be creating static Objects? For example:
array[j+1] = &Object(stuff);
array[j] = NULL
Is there a way to deallocate the old new object at array[j] without deallocating the whole array?
I don't see why you need to create a new object at all. Just move it.
array[j+1] = array[j];
array[j] = nullptr;
Also, yes, when you create an array of dynamically allocated objects, the array doesn't store any objects itself. It just stores pointers to the object. So you can delete the object without it affecting the array (and likewise, deleting the array won't delete the objects). You can simply do: delete array[j];
Does the code you have compile? The code you have posted does not compile, and I cannot be sure whether the problem that is preventing it from compiling is a deliberate part of the exercise(that you must work out) or a result of a bit of slightly careless copy-pasting.
Before I give away any anwsers (and therefore rob you of a useful learning exercise) I need to know what the actual assignment is. I can explain the problem preventing compilation and explain what the exercise is trying to show you, but before I do I would like to know what exactly you are trying to do/have been assigned to do. If the error in the code posted is in fact one of copy-pasting and not part of the exercise I will gladly help. The professors note at the top of your code explains that documentation has been left out but I am not sure if code itself has been left out and whether discovering this is part of the assignment, hence this somewhat strange line of inquiry.
Apologies if it seems as though I am rambling, but I do want to help you here (there are some interesting things about this program and the exercise). DM me if what I am asking is unclear.
Note
The remainder operator is sometimes incorrectly referred to as the "modulus" operator. It is very similar to modulus, but does not work properly with negative numbers.
What? Everytime I've seen % pop-up in lessons, people say it's a "modulo" operator. What is the difference? Apparently most everything besides Javascript (and even then Javascript) treats it as a modulo over remainder.
And I don't eve know what modulo is given I'm math dumb. Ugh.
What? Everytime I've seen % pop-up in lessons, people say it's a "modulo" operator. What is the difference? Apparently most everything besides Javascript (and even then Javascript) treats it as a modulo over remainder.
And I don't eve know what modulo is given I'm math dumb. Ugh.
That's exactly the problem: people call it modulo, and it's actually rather nearly always a remainder of an integer division. With different definitions depending on the language.
About modulo :
--------------------
In maths, there's several situations where we talk about modulo.
You can do computations, especially with integers, in modular arithmetics. Think about a 12h clock. If it's 9h and you add 5h, you'll get 2h instead of 14h.
For integers, for examples, two integers a and b are said congruent modulo p if and only if (b-a) is an integer multiple of p (or (b-a)=k.p where p is an integer).
Usually, you write it a = b (mod p) using a special "equal" sign with triple _
This equivalence is especially interesting because it's consistent with usual operations. Like when you use "proof by nine" by summing the digits of both operands of a multiplications till you get only a single digit, and do the same for the result, and check they're consistents. You're checking the operation "modulo 9".
There's rings (a mathematical structure) called Z/pZ where you consider only the p classes of congruent integers. In Z/7Z for example, 3, 10 and 17 are congruent (modulo 7) and thus represents the same object.
So, 4+6=10 and 4+6=3 are both correct in Z/7Z.
Since it's not really practical to have several ways to write the same number (here, 3, 10, 17, 24...), the lowest one is usually used to represent all the integers that are in the same "class". Here, you would use 3, and write 4+6 = 3... Sometimes with a line over the numbers.
Remainder of integer division :
----------------------------------------
The (least positive) remainder r of the integer division of two positive integers a and b is the integer r that satisfy
0 <= r < |b|
and
a = k.b + r where k is an integer
It can be extended to real numbers as long as 0 is non-zero and k remains an integer (with numerous rounding issues on IEEE floats).
On computers :
--------------------
With positive integers, both operations (getting the lowest integer that represent the class of congruent numbers in Z/pZ and computing the remainder of a division by p) are technically the same, that's the reason why you see both "remainder of integer division" and "modulo" used for the same operator.
But when you take into account negative operands, the problem is harder since you can make different choices for the remainder of the integer division (and I'm not sure I've seen negative values for congruence relations). Different languages have actually made different choices, in fact. The remainder can be positive or negative, it's not always the lowest positive remainder that is used.
In Python, 7 % -3 equals -2 and -7 % 3 equals 2 (but math.fmod use the other way around, the sign of the result is the same as the dividend)
In Java, % and floorMod work *exactly the opposite* :/
In C90, % behavior is implementation dependant (but there's mod whose results has the sign of dividend).
In C99, 7 % -3 equals 1 and -7 % 3 equals -1, like mod.
Etc.
All the possible results are actually congruent modulo p (1 and -2 for 7 modulo 3 or -3, and -1 and 2 for -7 modulo 3 or -3), so it's not a huge deal, but if you use the remainder of the integer division by p to get a unique value representing the class of all values that are congruent by p, you'll have nasty surprises.
Hello guys, i have assignment for converting binary numbers to decimal in java and i did write the code but want any feedback from you guys if i can make the code more efficient or if i did something that would reduce points from the assignment.
Code:
import java.util.Scanner;
public class ConvertBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a four, or more, digit binary number: ");
String Binary = input.nextLine();
int decimal = convertToDecimal(Binary);
System.out.println("The binary number you have chose equals this in decimal: "+ decimal);
}
private static int convertToDecimal(String binary) {
final int base = 2;
int decimal = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '0') {
decimal += 0 * Math.pow(base, binary.length() - i - 1);
} else if (binary.charAt(i) == '1') {
decimal += 1 * Math.pow(base, binary.length() - i - 1);
} else {
System.out.println("Use the number one and/or zero please");
}
}
return decimal;
}
}
the example we were given was this:
Enter a four digit binary number (e.g. "0111")
> 0101
0101 converted to decimal is 5
That's exactly the problem: people call it modulo, and it's actually rather nearly always a remainder of an integer division. With different definitions depending on the language.
It is very frustrating as I come from a math background. I wrote a modulo function for a PHP application because the built-in operator did not work as I had expected.
Need help if anyone is willing. Week 4 of intro to programming (Java). I finally got this working except it won't loop.
Code:
import java.util.Scanner;
public class BeersCharlesUnit4
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String entry; //string for (y/n) exit
boolean x = true; //you are sick
boolean z = false; //you are not sick
int d;
System.out.println("Enter the day of the week (1=Mon, 2=Tue, 3=Wed, etc.): ");
d = stdIn.nextInt(); //variable for day of the week
System.out.println("Are you sick? (True or False): ");
x = stdIn.nextBoolean(); //input true or false
do
{
if ((x) || (d > 5))//
{
System.out.println("Stay in bed!: ");
}
else if (d <= 5)
{
switch(d)
{
case 1:
System.out.println("Work Hours for today are 8-5");
break;
case 2:
System.out.println("Work Hours for today are 7-4");
break;
case 3:
System.out.println("Work Hours for today are 8-5");
break;
case 4:
System.out.println("Take the day off");
break;
case 5:
System.out.println("Work Hours for today are 8-12");
break;
} //end switch
} //end if
System.out.println("Would you like to run again? (y/n)");
entry = stdIn.nextLine();
} while (entry.equals('n'));//end do
} //end main
} //end class
Hello guys, i have assignment for converting binary numbers to decimal in java and i did write the code but want any feedback from you guys if i can make the code more efficient or if i did something that would reduce points from the assignment.
Code:
import java.util.Scanner;
public class ConvertBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a four, or more, digit binary number: ");
String Binary = input.nextLine();
int decimal = convertToDecimal(Binary);
System.out.println("The binary number you have chose equals this in decimal: "+ decimal);
}
private static int convertToDecimal(String binary) {
final int base = 2;
int decimal = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '0') {
decimal += 0 * Math.pow(base, binary.length() - i - 1);
} else if (binary.charAt(i) == '1') {
decimal += 1 * Math.pow(base, binary.length() - i - 1);
} else {
System.out.println("Use the number one and/or zero please");
}
}
return decimal;
}
}
the example we were given was this:
Enter a four digit binary number (e.g. "0111")
> 0101
0101 converted to decimal is 5
Need help if anyone is willing. Week 4 of intro to programming (Java). I finally got this working except it won't loop.
Code:
import java.util.Scanner;
public class BeersCharlesUnit4
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String entry; //string for (y/n) exit
boolean x = true; //you are sick
boolean z = false; //you are not sick
int d;
System.out.println("Enter the day of the week (1=Mon, 2=Tue, 3=Wed, etc.): ");
d = stdIn.nextInt(); //variable for day of the week
System.out.println("Are you sick? (True or False): ");
x = stdIn.nextBoolean(); //input true or false
do
{
if ((x) || (d > 5))//
{
System.out.println("Stay in bed!: ");
}
else if (d <= 5)
{
switch(d)
{
case 1:
System.out.println("Work Hours for today are 8-5");
break;
case 2:
System.out.println("Work Hours for today are 7-4");
break;
case 3:
System.out.println("Work Hours for today are 8-5");
break;
case 4:
System.out.println("Take the day off");
break;
case 5:
System.out.println("Work Hours for today are 8-12");
break;
} //end switch
} //end if
System.out.println("Would you like to run again? (y/n)");
entry = stdIn.nextLine();
} while (entry.equals('n'));//end do
} //end main
} //end class
When you call nextLine(), it reads the line break after the true/false input, and it will be an empty string, which is different from 'n' (BTW, you should keep the loop if it is 'y', not 'n').
One easy (but not very elegant) way, is calling
Code:
entry = stdIn.nextLine();
twice.
The elegant way is reading the Int and the Boolean with the nextLine() method and then parsing it.
Need help if anyone is willing. Week 4 of intro to programming (Java). I finally got this working except it won't loop.
Code:
import java.util.Scanner;
public class BeersCharlesUnit4
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String entry; //string for (y/n) exit
boolean x = true; //you are sick
boolean z = false; //you are not sick
int d;
System.out.println("Enter the day of the week (1=Mon, 2=Tue, 3=Wed, etc.): ");
d = stdIn.nextInt(); //variable for day of the week
System.out.println("Are you sick? (True or False): ");
x = stdIn.nextBoolean(); //input true or false
do
{
if ((x) || (d > 5))//
{
System.out.println("Stay in bed!: ");
}
else if (d <= 5)
{
switch(d)
{
case 1:
System.out.println("Work Hours for today are 8-5");
break;
case 2:
System.out.println("Work Hours for today are 7-4");
break;
case 3:
System.out.println("Work Hours for today are 8-5");
break;
case 4:
System.out.println("Take the day off");
break;
case 5:
System.out.println("Work Hours for today are 8-12");
break;
} //end switch
} //end if
System.out.println("Would you like to run again? (y/n)");
entry = stdIn.nextLine();
} while (entry.equals('n'));//end do
} //end main
} //end class
When you call nextLine(), it reads the line break after the true/false input, and it will be an empty string, which is different from 'n' (BTW, you should keep the loop if it is 'y', not 'n').
One easy (but not very elegant) way, is calling
Code:
entry = stdIn.nextLine();
twice.
The elegant way is reading the Int and the Boolean with the nextLine() method and then parsing it.
} //end if
System.out.println("Would you like to run again? (y/n)");
entry = stdIn.next();
} while (entry.equals("y"));//end do
} //end main
I use stdIn.next rather than nextLine, nextLine reads to the end of the current line, next reads the next token. Also the entry.equals() needs " rather than '. I don't know about java, but in c++ 'y' is a single character, while "y" is a string.
But the loop just loops over the output, the input questions are outside the loop. Don't know if that's what you intended, otherwise just move the 4 lines above the loop into the loop.
That's exactly the problem: people call it modulo, and it's actually rather nearly always a remainder of an integer division. With different definitions depending on the language.
About modulo :
--------------------
In maths, there's several situations where we talk about modulo.
You can do computations, especially with integers, in modular arithmetics. Think about a 12h clock. If it's 9h and you add 5h, you'll get 2h instead of 14h.
For integers, for examples, two integers a and b are said congruent modulo p if and only if (b-a) is an integer multiple of p (or (b-a)=k.p where p is an integer).
Usually, you write it a = b (mod p) using a special "equal" sign with triple _
This equivalence is especially interesting because it's consistent with usual operations. Like when you use "proof by nine" by summing the digits of both operands of a multiplications till you get only a single digit, and do the same for the result, and check they're consistents. You're checking the operation "modulo 9".
There's rings (a mathematical structure) called Z/pZ where you consider only the p classes of congruent integers. In Z/7Z for example, 3, 10 and 17 are congruent (modulo 7) and thus represents the same object.
So, 4+6=10 and 4+6=3 are both correct in Z/7Z.
Since it's not really practical to have several ways to write the same number (here, 3, 10, 17, 24...), the lowest one is usually used to represent all the integers that are in the same "class". Here, you would use 3, and write 4+6 = 3... Sometimes with a line over the numbers.
Remainder of integer division :
----------------------------------------
The (least positive) remainder r of the integer division of two positive integers a and b is the integer r that satisfy
0 <= r < |b|
and
a = k.b + r where k is an integer
It can be extended to real numbers as long as 0 is non-zero and k remains an integer (with numerous rounding issues on IEEE floats).
On computers :
--------------------
With positive integers, both operations (getting the lowest integer that represent the class of congruent numbers in Z/pZ and computing the remainder of a division by p) are technically the same, that's the reason why you see both "remainder of integer division" and "modulo" used for the same operator.
But when you take into account negative operands, the problem is harder since you can make different choices for the remainder of the integer division (and I'm not sure I've seen negative values for congruence relations). Different languages have actually made different choices, in fact. The remainder can be positive or negative, it's not always the lowest positive remainder that is used.
In Python, 7 % -3 equals -2 and -7 % 3 equals 2 (but math.fmod use the other way around, the sign of the result is the same as the dividend)
In Java, % and floorMod work *exactly the opposite* :/
In C90, % behavior is implementation dependant (but there's mod whose results has the sign of dividend).
In C99, 7 % -3 equals 1 and -7 % 3 equals -1, like mod.
Etc.
All the possible results are actually congruent modulo p (1 and -2 for 7 modulo 3 or -3, and -1 and 2 for -7 modulo 3 or -3), so it's not a huge deal, but if you use the remainder of the integer division by p to get a unique value representing the class of all values that are congruent by p, you'll have nasty surprises.
Uh... explain that like I'm ten? I got your clock example, but I'm not sure I'm following the rest of it. The graph on free code camp did similar to the clock example and mentions the negative problem you're mentioning.
What's tripping me up is if it's doing the same thing with the problem being negatives for whatever modulo is, why do people still call it modulo when Free Code Camp doesn't. FCC is like the only place that doesn't say it's modulo. Even CS50 seems to call it modulo.
} //end if
System.out.println("Would you like to run again? (y/n)");
entry = stdIn.next();
} while (entry.equals("y"));//end do
} //end main
I use stdIn.next rather than nextLine, nextLine reads to the end of the current line, next reads the next token. Also the entry.equals() needs " rather than '. I don't know about java, but in c++ 'y' is a single character, while "y" is a string.
But the loop just loops over the output, the input questions are outside the loop. Don't know if that's what you intended, otherwise just move the 4 lines above the loop into the loop.
Uh... explain that like I'm ten? I got your clock example, but I'm not sure I'm following the rest of it. The graph on free code camp did similar to the clock example and mentions the negative problem you're mentioning.
What's tripping me up is if it's doing the same thing with the problem being negatives for whatever modulo is, why do people still call it modulo when Free Code Camp doesn't. FCC is like the only place that doesn't say it's modulo. Even CS50 seems to call it modulo.
Modulo put the numbers into a cycle. When you get past the highest number, you goes back to the beginning.
For positive operands, % behaves exactly like modulo, I think this is why it is called this way. But since there's no consistency on how it behaves with negatives, it shouldn't have this name.
Also, modulo is easier to say than remainder of division - I believe this is also a factor