I have this problem that I have observed when generating numbers as a condition in a for loop.
I use this in my android program.
When I do this:
String temp = "";
for (int i = 0; i < new Random().nextInt(1000); i++) {
temp += i + " ";
}
I always get no more than 100
But when I do this:
for (int i = 0; i < 10; i++) {
temp += new Random().nextInt(1000) + " ";
}
I got real random numbers ranging from 0 to 999.
What is actually happening?
I know I could do this:
int x = new Random().nextInt(1000);
for (int i = 0; i < x; i++) {
temp += i + " ";
}
And this does return random numbers from 0-999. But I just want to understand why the first code only returns numbers not more than 100.
for (int i = 0; i < new Random().nextInt(1000); i++) { // here upper limit of i will change time to time.
temp += i + " ";
}
.
for (int i = 0; i < 10; i++) { // here i increase up to 10
temp += new Random().nextInt(1000) + " ";
}
.
int x = new Random().nextInt(1000); // here x is random but this will never change while for loop is running
for (int i = 0; i < x; i++) {
temp += i + " ";
}
In this code
for (int i = 0; i < new Random().nextInt(1000); i++) {
temp += i + " ";
}
the variable i is incremented by one for each iteration of loop, but at a given point of time where i<100, there is a chance of a number smaller than 'i' get generated randomly and thus the loop exits.
you should initialize random variable before cycle
int max = new Random().nextInt(1000);
String temp = "";
for (int i = 0; i < max; i++)
{ temp += i + " "; }
Java Doc says:
Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive)
So it is possible that value of i can be larger than the random generated by nextInt() and the loop exits.
As you are creating a new Random is generated using nextInt(1000) on each iteration of for loop, you will not get a fixed value for the loop and it will keep changing and so will your output.
String temp = "";
for (int i = 0; i < new Random().nextInt(1000); i++) { //new random nextInt() called on each iteration
temp += i + " ";
}
Note: My program ran till 64
Your first implementation ...
for (int i = 0; i < new Random().nextInt(1000); i++) {
temp += i + " ";
}
is calling new Random().nextInt(1000) at the end of every iteration to determine if it's time to end the loop. The same code could be rewritten as follows:
int i = 0;
while (i < new Random().nextInt(1000)) {
temp += i + " ";
i++;
}
which may be better illustrated as ...
int i = 0;
while (true) {
if (i < new Random().nextInt(1000)) {
break;
}
temp += i + " ";
i++;
}
so although the value of i is constantly increasing, the number against which it is being compared new Random().nextInt(1000) is constantly changing. Your comparisons might look like this ...
if (0 < 981) break;
if (1 < 27) break;
if (2 < 523) break;
if (3 < 225) break;
if (4 < 198) break;
if (5 < 4) break;
In the above example, even though the first call to new Random().nextInt(1000) is returning a whopping 981, the loop only happens 5 times, because at the beginning of the 6th iteration, new Random().nextInt(1000) returned 4, which is less than 5 the current value of i.
Hope this helps!
Here
String temp = "";
for (int i = 0; i < new Random().nextInt(1000); i++) {
temp += i + " ";
}
i may be bigger than 100 but probabilistically is practically impossible. yeah!
The "first for loop" may give output numbers less than 100 but not always, it will give a series of numbers from 0 to the random number which is returned by the Random.nextInt(1000) method....
1st and 3rd looping methods works same...
but the second one will pick 9 random numbers from 0 to 999 and the answer is like, (373 472 7 56 344 423 764 722 554 800)
Related
I am having trouble trying to figure this out. I need to create an application that displays the index numbers 0-101, and also stores the sum of each individual index numbers digits. for example:
INDEX---------GENERATED NUMBER
0--------------------0
1--------------------2
2--------------------4
3--------------------6
And so on. Index 17 would store 25, because 17 + 1 + 7 = 25.
I've got the list of index numbers down pact..
public class ArrayPractice {
public static void main(String[] args)
{
int sum = 0;
int[] arrayNumber = new int[102];
for(int i = 0; i < arrayNumber.length; i++){
arrayNumber[i] = i;
int add = i % 10;
sum += add;
i /= 10;
System.out.println(i);
}
}
}
I also understand that to get the sum of the digits, you have to modulus 10 and then divide by 10, 17 % 10 = 7, 17 / 10 = 1 7 + 1 = 8 + 17(index) = 25.
I just keep failing to get this to work within a loop. Any help would be greatly appreciated.
Will also explain, since you have 3 digit numbers it's not enough to divide by 10 once. You have to do it until it's bigger than 0, so for 100, you get 0, 0, 1. Which is why a while loop is best, since you don't know when it will end. This works for any integer.
Just remember, for loops are meant to be used when you know when your loop has to end.
While loop is used when you don't know when you will end, well you know when but not when it will happen.
EDIT: Just saw you have to add the index itself, 17 = 1 + 7 + 17. Fixed that.
int current;
int[] array = new int[102];
int sum;
for(int i = 0; i < array.length; i++){
current = i;
sum = 0;
while(current != 0){
sum += current % 10;
current = current/10;
}
array[i] = sum+i;
}
for(int i = 0; i < array.length; i++){
System.out.println("Index " + i + " :" + array[i]);
}
The problem with your code is it just sums up the last digit of the number, it won't work for numbers having digits greater than 2, you have to loop through all the digits and keep adding them to the number.
for(int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = i;
int tmp = arrayNumber[i];
// summing up digits
while(tmp > 0) {
arrayNumber[i] += tmp%10; //extracting right-most digit
tmp /= 10; // removing the right-most digit
}
System.out.println(i , arrayNumber[i]);
}
I think you're pretty close, but you'll most likely want to use another variable (other than i your iterator) to modify -- otherwise your iterator will continuously get messed with. You'll also want to continue doing the mod/divide operation until your initial number is 0 (i.e. you've processed all the digits). You'll also want to reset your sum for each pass through the for loop.
Here's my example code:
int[] arrayNumber = new int[102];
for (int i = 0; i < arrayNumber.length; i++) {
int sum = i;
int startingNumber = i;
while (startingNumber > 0) {
sum += startingNumber%10;
startingNumber /= 10;
}
arrayNumber[i] = sum;
System.out.println(i + " " + sum);
}
The variable "num" is a 2D array. I'm trying to check in that array, if there are any duplicates. "num" is a user-input.
I have extensively looked through Java documentation and asked my lectures and I can't get a working answer. I understand the concept, what I'm meant to do, but just can't get the coding right.
Here is my code:
for(int i = 0; i < 3; i++){ //3 rows with 5 numbers each
for(int j = 0; j < 5; j++){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for line: " + i + " and position: "+ j ));
if((num[i][j] == num[i][0]) || (num[i][j] == num[i][1]) ||(num[i][j] == num[i][2]) || (num[i][j] == num[i][3]) || (num[i][j] == num[i][4])){
if(num[i][j] != 0){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "ERROR. Enter value for line: " + i + " and position: "+ j ));
}
}
}
}
I have also tried using HashSet, but I think that only works with 1D arrays.
I would like to use something like this, as I feel this I understand the most:
secret = new Random().ints(1, 40).distinct().limit(5).toArray();
But obviously not with Random.
I've tried this:
Set<Integer> check = new HashSet<>();
Random gen = new Random();
for(int i = 0; i < 3; i++){ // 3 rows, 5 numbers
for(int j = 0; j < 5; j++){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for row " + i + " and position " + j));
check.add(gen.nextInt(num[i][j]));
}
}
This last section of coding (directly above this) compiles and runs, but doesn't check for duplicates.
There are alternative ways to checking for duplicates (e.g. you could loop back through the data you've entered previously into the 2D array in order to check for duplicate values) however here's how I'd go about using a Set to check for duplicates in order to, Are you trying to populate the 2d array with all unique values, where each value is from the user?? (also - knowing this explicitly in the original post would be very helpful, thanks to Michael Markidis for specifying that)
With a little UX knowledge here, separating the ERROR is def helpful to the end-user, as ERROR + re-input at the same time is confusing.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;
public class App {
public static void main(String[] args) {
int[][] num = new int[3][5];
System.out.println("Before:");
for (int i = 0; i < 3; ++i)
System.out.println(Arrays.toString(num[i]));
Set<Integer> data = new HashSet<Integer>();
for (int i = 0; i < 3; i++) { // 3 rows with 5 numbers each
for (int j = 0; j < 5; j++) {
boolean isGoodInput = false;
while (!isGoodInput) {
String input = JOptionPane.showInputDialog(null, "Enter value for line: " + i + " and position: " + j);
Integer n = Integer.parseInt(input);
if (data.contains(n)) {
JOptionPane.showMessageDialog(null, "ERROR: Try again");
} else {
num[i][j] = n;
isGoodInput = data.add(n);
}
}
}
}
System.out.println("After:");
for (int i = 0; i < 3; ++i)
System.out.println(Arrays.toString(num[i]));
}
}
Note: the 2D array is limited to your specification in the original post as a 3x5, so you'd have to change these values in multiple places to make different sized arrays - perhaps making these more dynamic could speed up further development of this application in the future.
Here's one way to accomplish this where you use the hashset to track what has already been inserted into the 2D array:
int[][] num = new int[3][5];
Set<Integer> check = new HashSet<>();
for (int i = 0; i < 3; i++)
{ // 3 rows, 5 numbers
for (int j = 0; j < 5; j++)
{
int n = 0;
do
{
n = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for row " + i + " and position " + j));
} while (!check.add(n)); // keep looping if it was in the hashset
// add it to the array since we know n is not a duplicate at this point
num[i][j] = n;
}
}
I am learning to code Java, and in a tutorial I learned to make the percentage of the percentage of wins I got. I am really confused what the integer "a" does exactly. Can someone please explain it in simple terms? (because I'm a complete newb)
double numOfGames = 10000;
double arrayNum = 1;
Random r = new Random();
int[] num = new int[(int) arrayNum]; // same as "= {0,0,0,0,0}
boolean gameResult = true;
boolean[] odds = new boolean[(int) numOfGames];
double numOfWins = 0;
for (int a = 0; a < numOfGames; a++) {
for (int i = 0; i < num.length; i++) {
num[i] = r.nextInt(100) + 1;
if (num[i] % 2 == 0) {
} else {
gameResult = false;
}
}
if (gameResult) {
odds[a] = true;
}
gameResult = true;
}
for (int i = 0; i < odds.length; i++) {
if (odds[i]) {
numOfWins++;
}
}
double perWin = (numOfWins / numOfGames) * 100;
System.out.println(perWin + " % of an array with " + arrayNum
+ " positions.");
}
}
It's a counter.
Basically it goes up by one every time that code block is run, in plain English this:
for (int a = 0; a < numOfGames; a++) {
// Do things.
}
Is like saying "Start counting at 0; Do things repeatedly until the counter reaches numOfGames".
a++ is just shorthand for a = a + 1 or "add 1 to a".
int = a is a local variable (an integer number) that increases by one in each iteration of your for loop. it simply goes from 0 to the total number of games, in this case: 10000. when it reaches the number of total games, it is discarded.
I'm very close to completing this, all I need is help on finding the five lowest values from a text file by using arrays. I figured out how to find the five highest values, but my min array to find the lowest values always outputs five 0's.
Output: //obviously dependent on individual text file
Total amount of numbers in text file is 10
Sum is: 1832
1775 14 9 9 7 //max
0 0 0 0 0 //min
Any help is much appreciated!
import java.util.Scanner;
import java.io.*;
public class HW3
{
public static void main(String[] args) throws IOException
{
File f = new File("integers.txt");
Scanner fr = new Scanner(f);
int sum = 0;
int count = 0;
int[] max = new int[5];
int[] min = new int[5];
int temp;
while(fr.hasNextInt())
{
count++;
fr.nextInt();
}
Scanner fr2 = new Scanner(new File("integers.txt"));
int numbers[] = new int[count];
for(int i=0;i<count;i++)
{
numbers[i]=fr2.nextInt(); //fills array with the integers
}
for(int j:numbers)//get sum
{
sum+=j;
}
for (int j=0; j < 5; j++) //finds five highest
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] > max[j])
{
temp = numbers[i];
numbers[i] = max[j];
max[j] = temp;
}
}
}
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] < min[j])
{
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
}
}
System.out.println("Total amount of numbers in text file is " + count);
System.out.println("Sum is: " + sum);
System.out.println(max[0] + " " + max[1] + " " + max[2] + " " + max[3] + " " + max[4]);
System.out.println(min[0] + " " + min[1] + " " + min[2] + " " + min[3] + " " + min[4]);
}
}
Your min array will be initialized with zero values. So the values in numbers will always be higher (assuming there are no negatives).
I'd suggest that you initialize min[j] with numbers[0] before the inner loop.
for (int j=0; j < 5; j++) //finds five highest
{
min[j] = numbers[0]; // Add this line
for (int i=0; i < numbers.length; i++)
{
Try debugging your code by entering inside your nested min loop the following line:
System.out.println("the value of numbers[i] is: " + numbers[i]);
so it looks like this:
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] < min[j])
{
System.out.println("the value of numbers[i] is: " + numbers[i]);
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
}
}
You'll notice something interesting. The innermost nested part doesn't even start.
Try putting that line into the nested max loop in its respective location instead... and it will run fine and show the max array values. You are getting zero values for the min array because (other than initial assigning) the innermost part of the nested min loop isn't being started somehow, so it fails to run and searched values do not get assigned to the min array.
The outer nested parts of the min loop run fine if you try debugging them with a similar line. It's this part that won't start and something's wrong with:
if (numbers[i] < min[j])
{
System.out.println("the value of numbers[i] is: " + numbers[i]);
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
(Update)
In the min loop, numbers[i] from i=0 to i=4 have a value of 0 after completing the max loop.
You only need to add one line and use int i=5 instead of int i=0 inside your min loop:
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
min[j] = max[4]; // added line
for (int i=5; i < numbers.length; i++) // change to int i=5
{
if (numbers[i] < min[j])
{...
As the other answer states, your problem is that you did not take into account the arrays beginning at 0. In Java, it sets default values for that data structure. For primitives, this will normally be 0 or false. However, when you move into data structures, you will have problems with null pointer exceptions if you fail to initialize your objects. For this reason, I would urge you to get into the habit of setting the values in your data structures before you ever use them. This will save you A LOT of debugging time in the future.
If you know the values in advance, you can set them manually with {0,0,0,0,0} notation, or your can initialize using a for loop:
for(int i = 0; i < array.length; i++)
array[i] = init_value;
I would recommend that you also look into trying to consolidate as much as possible. For example, in your code you go through the same data 4 times:
1) read the integers from the file into an integer array
2) sum all of the numbers in the integer array
3) look for max
4) look for min
I'm not sure if you've covered functions yet, but one example of consolidating this might look like:
while(fr2.hasNextInt()){
int i = fr2.nextInt();
sum += i;
checkHighest(i);
checkLowest(i);
}
You then define these functions and put the meat elsewhere. This lets you only worry about the loops in one place.
You have 2 problems.
First was explained by Tom Elliott.
The second problem is that also the max[] array is initialized with 0, and when you search for max values you change the value from max array (which is 0) with the value from the numbers array, so the numbers array becomes filled with 0s.
A quick solve (though not the best) would be to copy the numbers array in a temp array and use that temp when searching for min values.
In case you didn't exactly understood what I said, try to make a print of the numbers array after you found the 5 max values.
Just curious , Cant you just sort it(using quick sort) select top five and bottom five ?
- if you can use sorting I think this should work then
int sum = 0;
int count = 0;
int[] max = {Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE};
int[] min = {Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE};
int temp;
int visited[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int j : numbers)// get sum
{
sum += j;
}
int tempindex;
for (int j = 0; j < 5; j++) // finds five highest
{
for (int i = 0; i < numbers.length; i++) {
if (visited[i] != 1) {
if (numbers[i] > max[j]) {
max[j] = numbers[i];
tempindex = i;
}
}
}
visited[tempindex] = 1;
}
for (int j = 0; j < 5; j++) // finds five lowest...array not assigned
// values
{
for (int i = 0; i < numbers.length; i++) {
if (visited[i] != 1) {
if (numbers[i] < min[j]) {
min[j] = numbers[i];
tempindex = i;
}
}
}
visited[tempindex] = 1;
}
As the title states, I have trouble understanding loops and have come up with a way to do a simple 1 through 100 sum, but like I said, the loops are causing me some confusion. I think I have the FOR Loop figured.
Here's what I've come up with.
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
- First to me Iterating and Looping are 2 different things.
Eg: Increment a variable till 5 is Looping.
int count = 0;
for (int i=0 ; i<5 ; i++){
count = count + 1;
}
Eg: Iterate over the Array to print out its values, is about Iteration
int[] arr = {5,10,15,20,25};
for (int i=0 ; i<arr.length ; i++){
System.out.println(arr[i]);
}
Now about all the Loops:
- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...
For Loop :
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("The sum is " + sum);
The Difference between While and Do-While is as Follows :
- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.
- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.
While Loop :
int sum = 0;
int i = 0; // i is 0 Here
while (i<100) {
sum += i;
i++;
}
System.out.println("The sum is " + sum);
do-While :
int sum = 0;
int i = 0; // i is 0 Here
do{
sum += i;
i++
}while(i < 100; );
System.out.println("The sum is " + sum);
From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.
ArrayList<String> arr = new ArrayList<String>();
arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");
for (String str : arr){ // str represents the value in each index of arr
System.out.println(str);
}
Your for loop looks good.
A possible while loop to accomplish the same thing:
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
System.out.println("The sum is " + sum);
A possible do while loop to accomplish the same thing:
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 100);
System.out.println("The sum is " + sum);
The difference between the while and the do while is that, with the do while, at least one iteration is sure to occur.
Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.
The for loop you specified is absolutely correct.
Although i will do all the loops for you once again.
int sum = 0;
// for loop
for (int i = 1; i<= 100; i++){
sum = sum + i;
}
System.out.println(sum);
// while loop
sum = 0;
int j = 1;
while(j<=100){
sum = sum + j;
j++;
}
System.out.println(sum);
// do while loop
sum = 0;
j = 1;
do{
sum = sum + j;
j++;
}
while(j<=100);
System.out.println(sum);
In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.