Need guidance with loops and multiples - java

This is my code so far. It prints the numbers 0 through 10. But I can’t figure out how to multiply each number by 2 and 10.
while(numberCounter <= 9){
System.out.println("Number: " + numberCounter);
numberCounter++;
}

Well, what you are doing is probably better suited for a for loop. Like this:
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + i); // This prints 0-9
}
Or for each number times 2:
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + (i*2)); // This prints 0-9 times 2
}
Or for each number times 10:
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + (i*10)); // Prints 0-9 times 10
}
Lastly, each number times 10 times 2:
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + (i*10*2)); // Prints 0-9 times 10 times 2
}
You should take a class on Java or read a thorough tutorial or book, because these are very basic Java topics. Try this one: http://www.learnjavaonline.org/

Related

How to get indices as well as array numbers printed out horizontally?

I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}

Fibonacci Sequence using Array in Java

I want to get the fibonacci sequence entered by the user in array. The task given to me was "Ask the user for 2 integer input which will be taken for first and second array elements of size 10 array."
Here is my code.
int limit = 10;
int[] fib = new int[limit];
fib[0] = 0;
fib[1] = 1;
for (int j = 1; j < 2; j++)
{
System.out.print("Enter number " + "[" + j + "]: ");
num[j] = reader.nextInt();
num[j] = fib[j+1] + fib[j+2];
System.out.println("");
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++ )
{
System.out.print(fib[j] + " ");
System.out.print("");
}
I badly need help for this one, been searching for solution for hours and still don't get it.
I'll just make some corrections to your code and explain them:
int limit = 10;
int[] fib = new int[limit];
// fib[0] = 0;
// fib[1] = 1;
// The two lines above are wrong. Even though the real fibonacci sequence starts
// with 0 and 1, the question asks for the first two terms to come from user
// inputs. Instead, you can initialize them below:
// In your old code, you had "j = 1; j < 2; j++". However, that only loops once.
// So, have your condition to be j <= 2 instead: (I'm assuming that you want 1
// and 2 and not zero-based because it should print out "Enter number [1]:" and
// "Enter number [2]:"
for (int j = 0; j < 2; j++) // Not "j < 2"
{
System.out.print("Enter number " + "[" + j + "]: ");
fib[j] = reader.nextInt(); // not num[j] = ..., it's fib[j] = ...
// num[j] = fib[j+1] + fib[j+2];
// You don't need this ^^^
System.out.println("");
}
// Now you need to fill in the array:
for (int j = 2; j < limit; j++)
{
fib[j] = fib[j - 1] + fib[j - 2];
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++)
{
System.out.print(fib[j] + " ");
System.out.print("");
}
You have a number of mistakes here. Try to answer the following things:
What is the purpose of num variable here? You are using it to take input (num[j] = reader.nextInt();), then you are using it to store the Fibonacci sequence as well (num[j] = fib[j+1] + fib[j+2];)!!!
The first loop is only running one time. Assuming that your calculations are correct (which is not in this case!), it will have values for the first fibonacci number only.
Finally when you are printing the Fibonacci numbers, you are not using the num variable! Why?
Anyway, here is a solution to your problem. But, it will not help you unless you understand the logic behind it and you know which line is doing what!!!
int limit = 10;
int[] fib = new int[limit];
for (int j = 0; j < 2; j++)
{
System.out.print("Enter number " + "[" + j + 1 + "]: ");
fib[j] = reader.nextInt(); // These are the first two fibonacci numbers provided by the user
System.out.println("");
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++ )
{
if( j > 1 ) // You only calculate from the third Fibonacci, as the first two were given by user
{
fib[j] = fib[j-1] + fib[j-2];
}
System.out.print(fib[j] + " ");
System.out.print("");
}

Program that takes user input and lists multiples of 7 according to that number (Java)

Here is my code to create a program that takes a user input and lists multiples of 7 that relate to that number.
For example: The user inputs 3, I need the output to be "7, 14, 21".
Currently if I enter a number less than 7, the program complies without printing an output, but as soon as I enter 7 or any number higher than 7 then the program compiles and prints exactly what I need it to.
So the problem I need to fix is to be able to enter a number lower than 7 and recieve the correct output.
Thanks in advance!
import java.util.Scanner;
public class MultiplesOfSeven {
public static void main(String[] args){
int j = 0;
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(j = 1; j <= n; j++){
if(j % 7 == 0){
System.out.print(j + " ");
for (int counter = 0 ; counter < n ; counter++) {
System.out.print(j*(2 + counter) + " ");
}
}
}
}
Don't overthink the loop here. As alternatives, both which mean you can delegate the % check, consider
for (j = 0; j < n; ++j){
// output (j + 1) * 7;
}
or, the less elegant due to your having to write 7 in three places
for (j = 7; j <= n * 7; j += 7){
// output j
}
This code is preventing your programm from printing anythingk, when you enter a number below 7:
if(j % 7 == 0){
% is the modulo operator.
It says: do what is in the brackets if the number I have counted to (j) has no reminder if I divide it by 7.
So what you have to do is count to the number entered (using a for loop) and print the mulitplication of the current number times 7.
It's not printing anything because when the number you inputted is less than seven and greater than zero, the code inside
if(j%7==0)
does not get executed. I think your code should be like this.
for (j = 1; j <= n; j++) {
if (j % 7 == 0) {
System.out.print(j + " ");
}
for (int counter = 0; counter < n; counter++) {
System.out.print(j * (2 + counter) + " ");
}
}
import java.util.Scanner;
public class MultiplesOfSeven {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(int j = 1; j <= n; j++) {
System.out.print(7*j + " ");
}
}
}
This is simple solution of your problem. This will work for all cases. Keep code simple good luck.

Java Dice game won't work. need some advice [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have a problem with my code, it's a simple dice game:
import java.util.Random;
class Zaruri {
public static void main(String args[]) {
Random roll = new Random();
int[] zar = new int[2];
for (int i = 0; i < 1; i++) {
for(int k = 0; k < 2; k++){
zar[i] = (int) (roll* 6) + 1;
}
if (zar[0] == zar[1]) {
System.out.println("Your numbers are : " + zar[0] + " and " + zar[1] + "\nYou won! \nYEEEY!!");
} else {
System.out.println("Your numbers are : " + zar[0] + " and " + zar[1] + "\nYou lost, better luck next time!");
}
}
}
}
I don't know how to make it work,first it won't let print out the second dice(it comes allways 0) and if i put more then 1 roll and (roll.nextDouble * 6) + 1; it will work,but i don't want more then 1 roll.
CAn you help me ? What am i doing wrong??
You don't need 2 for loops. Just 1 loop will do. Remove the outer i loop and let k loop do your random int generation.
for (int k = 0; k < 2; k++) {
zar[k] = roll.nextInt(6) + 1; // k loop populates your array.
}
if (zar[0] == zar[1]) {
System.out.println("Your numbers are : " + zar[0] + " and "
+ zar[1] + "\nYou won! \nYEEEY!!");
} else {
System.out.println("Your numbers are : " + zar[0] + " and "
+ zar[1] + "\nYou lost, better luck next time!");
}
There are a number of issues, i'll go through them 1 by 1
for (int i = 0; i < 1; i++) {
for(int k = 0; k < 2; k++){
zar[i] = (int) (roll* 6) + 1;
}
<snip rest of loop>
The loop with k in does nothing but repeat the line zar[i] = (int) (roll* 6) + 1; several times, it does nothing, this loop should be removed
for (int i = 0; i < 1; i++) {
for(int k = 0; k < 2; k++){
zar[i] = (int) (roll* 6) + 1;
}
if (zar[0] == zar[1]) {
System.out.println("Your numbers are : " + zar[0] + " and " + zar[1] + "\nYou won! \nYEEEY!!");
} else {
System.out.println("Your numbers are : " + zar[0] + " and " + zar[1] + "\nYou lost, better luck next time!");
}
}
The print statements are within the for loop, so it prints out every time through the loop, the first time through the loop only the first die will be set, the second time only the first two, etc etc.
zar[i] = (int) (roll* 6) + 1;
roll is of class random, it is not a number but generates random numbers, this should be
zar[i] = (int) (roll.nextDouble()* 6) + 1;
or more sensibly (as you want an int in the end anyway
zar[i] = roll.nextInt()+ 1;
for (int i = 0; i < 1; i++)
Numbers from i=0 to i<1 is just one number, 0, dice 1 is never set because its only goes through the loop once
Try to use Math.random() instead of Random()
I don't see why you have two loops, and especially the one with k as an index. You are not using that k anywhere. Try this:
for (int i = 0; i < 2; i++) {
zar[i] = roll.nextInt(6) + 1;
}
try this instead :
int Low = 10;
int High = 100;
int R = r.nextInt(High-Low) + Low;
SOURCE : How can I generate random number in specific range in Android?
or Java Generate Random Number Between Two Given Values
Delete the first loop with the i and let only the k loop.
Then it won't logically work and always print 0 because you don't generate a random number.
You must do zar[i]=roll.nextInt(6)+1; because the range is from 0 (included) and 6 (excluded). Logically you must add 1 whatever will be the result to obtain a 1-6 range.

Print an array elements with 10 elements on each line

I just created an array with 100 initialized values and I want to print out 10 elements on each line so it would be somthing like this
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
...26
this is the code I used and I managed to do it for the first 10 elements but I couldn't figure out how to do it for the rest
public static void main(String[] args) {
int[] numbers = { 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
int i, count = 0;
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 9)
for (i = 9; i < numbers.length; i++)
System.out.println(numbers[i] + " ");
}
}
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
This prints a newline before printing numbers[i] where i % 10 == 0 and i > 0. % is the mod operator; it returns the remainder if i / 10. So i % 10 == 0 when i = 0, 10, 20, ....
As for your original code, you can make it work with a little modification as follows:
int count = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
Basically, count is how many numbers you've printed in this line. Once it reaches 10, you print the newline, and then reset it back to 0, because you're starting a new line, and for that line, you haven't printed any numbers (yet).
Note that in above two solutions, an extra space is printed at the end of each line. Here's a more flexible implementation that only uses separators (horizontal and vertical) when necessary. It's only slightly more complicated.
static void print(int[] arr, int W, String hSep, String vSep) {
for (int i = 0; i < arr.length; i++) {
String sep =
(i % W != 0) ? hSep :
(i > 0) ? vSep :
"";
System.out.print(sep + arr[i]);
}
System.out.println(vSep);
}
If you call this say, as print(new int[25], 5, ",", ".\n");, then it will print 25 zeroes, 5 on each line. There's a period (.) at the end of each line, and a comma (,) between zeroes on a line.
Why do you use 2 nested loops where you only need to remember at which places you need to output a linebreak? Also using the same variable i for both loops will not do what you expect.
How about:
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10)
System.out.print("\n");
count = 0;
}
}
All you are going to have to do is to print out a newline after every ten numbers.
for (i = 0; i < numbers.length; ++i)
{
System.out.print(number[i]);
if (i % 10 == 9)
{
System.out.println();
}
else
{
System.out.print(" ");
}
}
I know this is an old question, but I just wanted to answer. In java 8 you can do this in one line. Arrays.stream(arr).forEach(s->System.out.print(s%10 > 0 ? s+" ":"\n"));

Categories

Resources