I'm new to Java and this is a simple question but i'm having trouble printing small numbers between 1 and 100. Small numbers are those less than 20 and I want my program to print out "small x" for each small number.
When I run this I'm not getting what I'm suppose to I just get "small x" printed 100 times.
Here's my code:
class ExerciseA {
public static void main(String[] args) {
int x = 1;
while ( x < 100 ) {
x = x + 1;
if( x > 20) {
System.out.println("small x");
}
}
}
}
> means greater, but you want lesser. So use <. Another thing in your code, 1 would not be printed as it's being incremented before printing. This should be:
int x = 0;
while ( x < 100 ) {
x++; // shorter than x = x + 1;
if (x < 20) {
System.out.println("small x");
//System.out.println("small " + x); //if want to print like small 1, small 2 etc.
}
}
Your System.out.println is printing small x since it is using the whole string instead of using the value of variable x.
Also, if you want to print small x for numbers less than 20, you should use x<20.
int x = 0;
while ( x < 100 ) {
x = x + 1;
if( x < 20) {
System.out.println("small " + x);
}
}
You can write down such kind of loops in the more matching for-loop style:
for (int i = 1; i <= 100; i++) {
if (isSmall(i)) {
System.out.println("small i");
}
using a bit of "re-factoring" by putting the check "is this a small number" into its own method:
private boolean isSmall(int i) {
return i < 20;
}
Using such small methods is something that you should get used to as soon as possible - as it helps to "isolate" certain functionality. Another change I made: in computer science, variables for whole numbers are typically called "i,j,k" ... and so on; whereas x, y, ... would be for floating point numbers!
And of course: you got the comparison wrong - if you want numbers smaller than 20, well, than you have to say so ( i < 20 ).
Related
I am trying to make a scoreboard with images in processing, with images from 0 to 9, but any number greater than 9 does not make changes
It should be something like this: 10, 11, 12, ..., 99
but it only changes the number on the left, try using a counter, converting it to a String and then to a Char[] to get the first digit of two numbers; for example: 25, it would have to be 2
when passing that number to the array, it sends "ArrayIndexOutOfBoundsException"
char[] digits;
PImage [] prueba = new PImage[10];
int contadorPrueba2 = 0;
int aa = 0;
void setup () {
size (781, 470);
tablero = loadImage("tablero.png");
flechaRight = loadImage("flechaRight.png");
flechaLeft = loadImage("flechaLeft.png");
for (int i = 0; i < prueba.length; i++) {
prueba[i] = loadImage("numero_" + i + ".jpg");
}
}
void draw () {
//flechas
image(flechaRight, x, y);
image(flechaLeft, x2, y);
image(prueba[0], x3, 50);
//cambiar de numeros
image(prueba[contadorPrueba2], x4, 50);
image(prueba[aa], x3, 50);
}
boolean isMouseOver (int x, int y, int w, int h) {
if (mouseX>x && mouseX <x+w && mouseY>y && mouseY <y+h) {
return true;
}
return false;
}
void mousePressed () {
if (isMouseOver (x, y, w, h) == true) {
contadorPrueba2++;
//image(uno, x3, 50);
} else if (isMouseOver (x2, y, w, h) == true) {
contadorPrueba2--;
}
if (contadorPrueba2 >= prueba.length)
contadorPrueba2 = 0;
count = String.valueOf(contadorPrueba2);
digits = count.toCharArray();
for (int i = 0; i < digits.length; i++) {
if (contadorPrueba2 >= 10) {
//aa = digits[0];
println(digits[i]);
aa = digits[i];
//aa = digits[i];
//print("pp" + aa);
if (i == 0) {
print("ksk" + digits[i]);
}
}
}
}
Chars aren't exactly the best way to keep track of a score, which can make for some headache at times. I strongly suggest that you keep track of the score with an integer number unless you really have no choice on the matter.
Now, to translate an integer into a bunch of index numbers associated with images of said numbers, things can also become complicated, but I got your back! In fact, you can use MATH and solve this quite easily. Are you familiar with the modulo operator? If you're not, read about it because it's a programmer's best friend. Long story short, it's a division that returns only the leftover numbers after the division. As an example, if I write:
10 / 3 == 3.333333 // as a division this makes sense
10 % 3 == 1 // modulo only keeps what's left when the division stops being an integer
because: 10 == [3+3+3] + 1
Ok, you probably already knew this, but if you didn't, now you do. Here's how I use this knowledge to simplify your issue with a commented example:
PImage[] digits = new PImage[10];
int score = 4780; // you can change this number for whatever integer number
void setup () {
size(200, 200);
for (int i = 0; i < digits.length; i++) {
digits[i] = loadImage(i + ".png"); // these 10 images are 10x10 pixels for easier handling
}
}
void draw () {
int i=1;
int j = 160; // arbitrary number: this is where i start drawing the score (the rightest number)
// oooh! This is a good opportunity to use a do...while(); loop! I don't have that many of those.
// This is because we have to show at least ONE digit even if the score is zero, but I coded this so you can have a score higher than 99 without issue
do {
i*=10; // using multiples of 10 with the modulo operator
// as we use base 10 in real life, multiples of 10 help isolate digits of interests
image(digits[(score%i)/(i/10)], j, 90); // j is the x coordinate of the current digit, 90 is an arbitrary y coordinate
// 'digits[(score%i)/(i/10)]' deserves an explanation:
// 'score%i' removes every unit besides the current digit of interests, as an example if we're looking for the hundreds digit of 3456 it'll be 400
// '/(i/10)' removes the unwanted zero (in the 3456 example it would leave only the number 4 instead of 400)
j-=10; // updating j for the next digit
} while(i<score);
}
I know I didn't tell you why you get ArrayIndexOutOfBoundsException and it's kinda on purpose: this is a very common error and although I have no trouble guessing why you get it, it's just more efficient to fix by improving the method than by meddling with the code. There are many articles on SO about why this error happens and I encourage you to read at least one, as it'll be something that you'll see again in the future. Yet, for now, you can just avoid it by switching to this method.
I hope this helps. Have fun!
I have this java code in eclipse. When I run it, I assume I should get something back in the console at the bottom of eclipse. This is not the case. The console at the bottom of eclipse is blank.
package com.veggiedogtreats.javacode;
public class doobeedoobeedo {
/**
* #param args
*/
public static void main(String[] args) {
int x = 1;
while (x < 0) {
System.out.println("Doo");
System.out.println("Bee");
x = x + 1;
}
if (x == 2 ) {
System.out.print("Do");
}
}
}
you have the while loop set to x < 0, it should be x > 0. The way you have it, it will never enter the while loop
Your while condition is wrong. it should read while ( x > 0 ) instead of while ( x < 0 )
Your program only prints to the console when x is less than zero and when x is 2.
x always has a value of 1.
int x = 1; // x is 1
while (x < 0) { // 1 is not less than zero, doesn't enter the loop
System.out.println("Doo");
System.out.println("Bee");
x = x + 1;
}
if (x == 2 ) { // 1 is not two, doesn't enter the if
System.out.print("Do");
}
Maybe you wanted something like this:
while (x < 0) { .... }
your conditions are not satisfied and hence the sysout statements are not executed. Either change the initial value of x or the conditions so that the sysout statements are executed atleast once.
Neither of the conditional statements are true. 1 is not less than zero or equal to 2.
Here's how it's written in the book:
"The value e^x can be approximated by the following sum:
1+x+x^2/2!+x^3/3!+...+x^n/n!
Write a program that takes a value x as input and outputs this sum for n taken to be each of the values 1 to 10, 50, and 100. Your program should repeat the calculation for new values of x until the user says she or he is through. The expression n! is called the factorial of n and is defined as
n! = 1*2*3*...*n
Use variables of type double to store the factorials (or arrange your calculation to avoid any direct calculation of factorials); otherwise, you are likely to produce integer overflow, that is, integers larger than Java allows."
I don't have any coding problems (not yet at least), my problem is I don't know what it's asking me to do. I get the factorial part (ex. 3i = 1*2*3) but I am just not sure what else it is asking. I have the user input a value for "x" but where does the "n" come from?
"The value e^x can be approximated by the following sum:
1+x+x^2/2!+x^3/3!+...+x^n/n!
" I don't know what this is saying or asking for.
I put together this for loop for the 1-10, 50, 100 part and I don't know if that even makes sense without understanding the rest, but here it is:
for (counter = 1 ; counter <= 100 ;counter++)
{
//System.out.print("Enter value for x: ");
//x = keyIn.nextDouble();
if (counter >= 1 && counter <= 10)
{
if (counter == 1)
System.out.println("Iterations 1-10: ");
System.out.println("test to see if 10 show up");
}
else if (counter == 50)
{
System.out.println("Iteration 50: ");
}
else if (counter == 100)
{
System.out.println("Iteration 100: ");
}
}
I haven't been in algebra in about two years so some of this stuff is throwing me off a bit. Please help with whatever you can, thanks.
It's saying that e^x can be approximated through a Taylor Series: Sum(i:0:n)(xi/fact(i))
So, we have:
double ex_taylor_series(double x, int n)
{
double value;
for(int i = 0; i < n; i++)
{
value += Math.pow(x, i)/(factorial(i));
}
return value;
}
private int factorial (int num)
{
int value = 1;
for(int i = num; i > 1; i--)
{
value *= i;
}
return value;
}
In your case, you would simply feed different values of n, 10, 50 and 100, to ex_taylor_series.
Hi I am a beginner so please don't use any complicated stuff.
Here is a SS of what i mean. http://prntscr.com/1ffec0
as of now don't worry about having numbers vertically and horizontally that display what columns and row number it is.
I have my code but am totally confused on how to go about it and how to make them multiply.
import java.util.Scanner;
public class test
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
int x=0, y=0;
System.out.print("Enter rows ");
x = keyboard.nextInt();
System.out.print("Enter columns ");
y = keyboard.nextInt();
for (int i=1; i<=x; i++)
{
for (int j=1; j<=y; j++)
{
System.out.print(" "+i+j);
}
System.out.println();
}
}
}
I'm not going to give you the answer straight out, but I'm going to help you understand the problem better with some pseudocode. Assume that your x-range goes from 1 to 3, and your y-range also goes from 1 to 3.
You did correctly set up 2 loops
Loop x = 1 to 3
Loop y = 1 to 3
//Do stuff
End innerloop
End outerloop
Now consider the values that will be printed at //do stuff, in pairs like (x, y):
(1, 1) , (1, 2), (1, 3), (2, 1), (2, 2), and so on until (3, 3);
Obviously you want the product to be displayed, so create some variable z = x * y inside the loops
//Do stuff:
z = x * y
Print z + " "
Print z out and leave a space, because you want to print the next value without it being adjacent to the first value.
This will print all your solutions in a straight, single line. But you want it to be in a matrix obviously. The answer is to simple a simple change, taking only one line of code. After each full cycle of your inner loop, you essentially finish one row of multiplication (think about why). So the solution is that after your inner loop finishes running, right before going to the next outer loop value for x, you want to print a new line. All in all we have something like:
Loop x = 1 to 3
Loop y = 1 to 3
z = x * y
Print z + " "
End innerloop
Print NewLine // "\n" is the way to do that
End outerloop
And you're done. You just need to put it into code, as well as accept user input instead of hard coding the range as from 1 to 3, or whatever. This is trivial and I'm sure you'll be able to put it together.
change the i+j by i*j
btw you are printing only half of the matrix
You need to use "*" instead of "+" ?
Like this:
public static void print(int x, int y) {
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
System.out.print(" " + i * j);
}
System.out.println();
}
}
And after that you might want to think about the formatting!? My advice: think about the length of the longest value (is always x*y) and "reservice" enought space for it!
Change:
System.out.print(" "+i+j);
To:
if ((i + j) <= 9) {
System.out.print(i + j + " ");
} else if ((i + j) <= 99) {
System.out.print(i + j + " ");
} else
System.out.print(i + j + " ");
This is the question I've been assigned:
A so-called “star number”, s, is a number defined by the formula:
s = 6n(n-1) + 1
where n is the index of the star number.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) star numbers are: 1, 13, 37,
73, 121, 181
In contrast a so-called “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) triangle numbers are: 1, 3, 6, 10, 15, 21
Write a Java application that produces a list of all the values of type int that are both star number and triangle numbers.
When solving this problem you MUST write and use at least one function (such as isTriangeNumber() or isStarNumber()
or determineTriangeNumber() or determineStarNumber()). Also you MUST only use the formulas provided here to solve the problem.
tl;dr: Need to output values that are both Star Numbers and Triangle Numbers.
Unfortunately, I can only get the result to output the value '1' in an endless loop, even though I am incrementing by 1 in the while loop.
public class TriangularStars {
public static void main(String[] args) {
int n=1;
int starNumber = starNumber(n);
int triangleNumber = triangleNumber(n);
while ((starNumber<Integer.MAX_VALUE)&&(n<=Integer.MAX_VALUE))
{
if ((starNumber==triangleNumber)&& (starNumber<Integer.MAX_VALUE))
{
System.out.println(starNumber);
}
n++;
}
}
public static int starNumber( int n)
{
int starNumber;
starNumber= (((6*n)*(n-1))+1);
return starNumber;
}
public static int triangleNumber( int n)
{
int triangleNumber;
triangleNumber =+ n;
return triangleNumber;
}
}
Here's a skeleton. Finish the rest yourself:
Questions to ask yourself:
How do I make a Triangle number?
How do I know if something is a Star number?
Why do I only need to proceed until triangle is negative? How can triangle ever be negative?
Good luck!
public class TriangularStars {
private static final double ERROR = 1e-7;
public static void main(String args[]) {
int triangle = 0;
for (int i = 0; triangle >= 0; i++) {
triangle = determineTriangleNumber(i, triangle);
if (isStarNumber(triangle)) {
System.out.println(triangle);
}
}
}
public static boolean isStarNumber(int possibleStar) {
double test = (possibleStar - 1) / 6.;
int reduce = (int) (test + ERROR);
if (Math.abs(test - reduce) > ERROR)
return false;
int sqrt = (int) (Math.sqrt(reduce) + ERROR);
return reduce == sqrt * (sqrt + 1);
}
public static int determineTriangleNumber(int i, int previous) {
return previous + i;
}
}
Output:
1
253
49141
9533161
1849384153
You need to add new calls to starNumber() and triangleNumber() inside the loop. You get the initial values but never re-call them with the updated n values.
As a first cut, I would put those calls immediatly following the n++, so
n++;
starNumber = starNumber(n);
triangleNumber = triangleNumber(n);
}
}
The question here is that "N" neednt be the same for both star and triangle numbers. So you can increase "n" when computing both star and triangle numbers, rather keep on increasing the triangle number as long as its less the current star number. Essentially you need to maintain two variable "n" and "m".
The first problem is that you only call the starNumber() method once, outside the loop. (And the same with triangleNumber().)
A secondary problem is that unless Integer.MAX_VALUE is a star number, your loop will run forever. The reason being that Java numerical operations overflow silently, so if your next star number would be bigger than Integer.MAX_VALUE, the result would just wrap around. You need to use longs to detect if a number is bigger than Integer.MAX_VALUE.
The third problem is that even if you put all the calls into the loop, it would only display star number/triangle number pairs that share the same n value. You need to have two indices in parallel, one for star number and another for triangle numbers and increment one or the other depending on which function returns the smaller number. So something along these lines:
while( starNumber and triangleNumber are both less than or equal to Integer.MAX_VALUE) {
while( starNumber < triangleNumber ) {
generate next starnumber;
}
while( triangleNumber < starNumber ) {
generate next triangle number;
}
if( starNumber == triangleNumber ) {
we've found a matching pair
}
}
And the fourth problem is that your triangleNumber() method is wrong, I wonder how it even compiles.
I think your methodology is flawed. You won't be able to directly make a method of isStarNumber(n) without, inside that method, testing every possible star number. I would take a slightly different approach: pre-computation.
first, find all the triangle numbers:
List<Integer> tris = new ArrayList<Integer>();
for(int i = 2, t = 1; t > 0; i++) { // loop ends after integer overflow
tris.add(t);
t += i; // compute the next triangle value
}
we can do the same for star numbers:
consider the following -
star(n) = 6*n*(n-1) + 1 = 6n^2 - 6n + 1
therefore, by extension
star(n + 1) = 6*(n+1)*n + 1 = 6n^2 + 6n +1
and, star(n + 1) - star(n - 1), with some algebra, is 12n
star(n+1) = star(n) + 12* n
This leads us to the following formula
List<Integer> stars = new ArrayList<Integer>();
for(int i = 1, s = 1; s > 0; i++) {
stars.add(s);
s += (12 * i);
}
The real question is... do we really need to search every number? The answer is no! We only need to search numbers that are actually one or the other. So we could easily use the numbers in the stars (18k of them) and find the ones of those that are also tris!
for(Integer star : stars) {
if(tris.contains(star))
System.out.println("Awesome! " + star + " is both star and tri!");
}
I hope this makes sense to you. For your own sake, don't blindly move these snippets into your code. Instead, learn why it does what it does, ask questions where you're not sure. (Hopefully this isn't due in two hours!)
And good luck with this assignment.
Here's something awesome that will return the first 4 but not the last one. I don't know why the last won't come out. Have fun with this :
class StarAndTri2 {
public static void main(String...args) {
final double q2 = Math.sqrt(2);
out(1);
int a = 1;
for(int i = 1; a > 0; i++) {
a += (12 * i);
if(x((int)(Math.sqrt(a)*q2))==a)out(a);
}
}
static int x(int q) { return (q*(q+1))/2; }
static void out(int i) {System.out.println("found: " + i);}
}