Struggling with my ArrayList code.
I needed to generate 20 random numbers between 1 and 200.
It works but when I show all in array list it, it all comes out horizontal
(ie: [190.9873874849,3.45694033,67.900034...] and SUPER long. It needs to have each number print out in a list format, with the only four digits after the decimal. (%10.4)
I tried this:
System.out.printf("%10.4", num[0]);
which works for the formatting but I can't seem to get the whole arraylist to work.
My array is this:
ArrayList<Number> num = new ArrayList<Number>();
for (int i = 0; i<20; i++) {
num.add(Math.random() *200 +1);
}
It works like I said for getting and listing the numbers -- but not in the "correct" way.
I also have to save the numbers to a file, and be able to let the user choose an index for them and tell them their number they chose from the file, which I am also struggling with.
Any help would be amazing!!!
[EDIT]
This worked (from Ole V.V.):
for (int i = 0; i<20; i++) {
num.add(Math.random() *200 +1);
System.out.printf("%10.4f%n", num.get(i));
[ADDITIONAL]
**I have to post here and can't make a new question because some jerk downvoted me? **
I have all of the numbers in my array read in and saved to a text file (with the right formatting!) but now I have to be able to ask the user for an index, and be able to find the object according to that index... but it isn't working!
I don't know how to assign indexes to variables when the numbers are no longer in array format (they're in a column similar to what is in the column).
Here are a couple of options. First, you may use a for loop like the one you already have:
for (int i = 0; i < 20; i++) {
System.out.printf("%10.4f%n", num.get(i));
}
A terser option is:
num.forEach(n -> System.out.printf("%10.4f%n", n));
In both case the output goes like
186.8143
129.4201
169.7405
...
Your format string, %10.4, was almost correct. You need to add f for formatting a floating-point number. I also added %n for a line break after the number. In Java num[i] works only for arrays, not for ArrayList, you need num.get(i).
You need to trim the extra digits by this simple trick.
double number = Math.random()*200 + 1;
number = (long)( number * 10000 );
number = number / 10000;
Related
This question already has answers here:
Elegantly Insert Spaces During Loop Between Values Without Trailing Space
(3 answers)
Java: join array of primitives with separator
(9 answers)
Closed 6 months ago.
I'm trying to get the console to output 100 random numbers between 0 and 50, all on the same line with a space between each. I have everything but the formatting for the space. I know I need to use the printf function, but am completely lost on how to properly impliment it. This is what I have so far, but the output formatting is incorrect.
public static void main(String[] args) {
Random rand = new Random();
for (int count = 0; count <=100; count++)
{
int randomNum = rand.nextInt(51);
System.out.printf("%1d %1d", randomNum, randomNum);
}
}
Here's a version neither using a condition or a separate first print but avoiding any leading or trailing space.
public static void main(String[] args) {
Random rand = new Random();
String delim="";
for (int count = 0; count <100; count++)//fixed as per comments elsewhere.
{
int randomNum = rand.nextInt(51);
System.out.printf("%s%1d", delim,randomNum);
delim=" ";// Change this to delim="," to see the action!
}
}
It's a classic faff to print out n items with n-1 internal separators.
PS: printf feels like overkill on this. System.out.print(delim+randomNum); works just fine.
[1] Your code actually prints 101 numbers. Embrace the logic computers (and java) applies to loops and 'the fences' (the start and end): The first number is inclusive, the second is exclusive. By doing it that way, you just subtract the two to know how many items there are. so, for (int count = 0; count < 100; count++) - that loops 100 times. Using <= would loop 101 times.
[2] You're making this way too complicated by focusing on the notion of 'there must be a space in between 2', as if the 2 is important. What you really want is just 'after every random number, print a space'. The only downside is that this prints an extra space at the end, which probably doesn't matter:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum + " ");
}
is all you actually needed. No need to involve printf:
I know I need to use the printf function
No, you don't. No idea why you concluded this. It's overkill here.
If you don't want the extra space.. simply don't print it for the last number:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum);
if (count < 99) System.out.print(" ");
}
[3] You mention that the code shuold print it all 'on one line', which perhaps suggests the line also needs to actually be a line. Add, at the very end, after the loop, System.out.println() to also go to a newline before you end.
Summary: I need a function based on the output. The problem is
connecting Eclipse or a Java code with another software.
I'm studying Physics. I needed a code that works the following way:
first, it declares a random number n;
then it outputs a "winner" number (based on some rules; the code
itself is irrelevant now I think), 20 times (but should be more,
first I need something to record the values, though).
I have n and 20 other numbers which are each between 1 and n (including 1 and n). I want, after compiling the code once, to see the 20 values, how they are distributed (for example, are they around one particular number, or in a region, is there a pattern (this is based on the rules, of course)).
The problem is, I'm only familiar with basic Java (I used eclipse), and have no clue on how I should register for example 2000 instead of the 20 numbers (so for an n number the code should print 2000 or more numbers, which should appear on a function: domain of the function is 1, 2, ..., n, and range is 0, 1, ..., 2000, as it might happen that all 2000 numbers are the same). I thought of Excel, but how could I connect a Java code with it? Visual interpretation is not necessary, although it would make my work easier (I hope, at least).
The code:
import java.util.Random;
public class korbeadosjo {
public static void main(String Args[]){
Random rand = new Random();
int n = (rand.nextInt(300)+2);
System.out.println("n= " + n);
int narrayban = n-1;
int jatekmester = n/2;
int jatekmesterarrayban = jatekmester-1;
System.out.println("n/2: " + jatekmester);
for(int i=0; i<400; i++){
int hanyembernelvoltmar = 1;
int voltmar[] = new int[n];
voltmar[jatekmesterarrayban]=1;
int holvan=jatekmester;
int holvanarrayban = holvan-1;
fori: for(;;){
int jobbravagybalra = rand.nextInt(2);
switch(jobbravagybalra){
case 0: //balra
if(holvanarrayban ==0){
holvanarrayban = narrayban;
}else {
--holvanarrayban;
};
if(voltmar[holvanarrayban]==0){
voltmar[holvanarrayban] =1;
++hanyembernelvoltmar;
}
break;
case 1: //jobbra
if(holvanarrayban == narrayban){
holvanarrayban = 0;
} else {++holvanarrayban;};
if(voltmar[holvanarrayban]==0){
voltmar[holvanarrayban]=1;
++hanyembernelvoltmar;
}
break;
}if(hanyembernelvoltmar==n){
System.out.println(holvanarrayban+1);
break fori;
}}}}}
basic Java (I used eclipse)
Unrelated.
I could only find two prompts in your question:
How to create statistics from output of Java code?
You are likely not wanting to get the output alone. Use those numbers in your Java program to find what you want and output it.
How did you store 2000 values? An array, list, queue...? So also iterate on that data structure and generate the statistics you need.
I thought of Excel, but how could I connect a Java code with it?
There is this site.
Hello I am trying to create a method in Java that Accepts an integer from the user. Calculate and display how many occurences of the integer are in the array(i'm Creating a random array) as well as what percentage of the array values is the entered integer.
This is how i create my Array:
public void fillVector ( )
{
int myarray[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
myarray [i] = (int) (Math.random () * 10);
}
}
Any sugestions how can i do to accomplish this ?
This seems like a homework to you so I am not gonna give you the full solution but I will break down the steps of what you need to do in order to solve your problem. You have to find out how to code those steps yourself, or at least provide some code and your specific problem because your question is too vague right now.
Ask the user to input the number.
Store that number somewhere.
Check each cell of the array for that number. If you find one appearance
increase the counter and continue until the end of your index.
Print out the appearances of the given number.
Print out the percentage of the cells containing the given value to the total amount of cells.
As I can see from your code (if it's yours) you are capable to pull this off on your own. It shouldn't be too hard.
I got this string[] I use in a grid of these images. The grid is generated randomly using a random. now I use the way of just adding the one object more times. but my algorithm to regenerate one if two pictures are the same(eg. egg-tree-blackcar-blackcar-pinkcar) won't work because I check the array indexes of the images.
String bingoObject[] = {
"black_car",
"gray_car",
"white_car",
"red_car",
"yellow_car",
"blue_car",
"pink_car",
"green_car",
"boat",
"tree",
//ADDED MORE FOR CHANCES
"black_car",
"black_car",
"gray_car",
"white_car",
"red_car",
"blue_car",
"green_car"
};
Is there another way to get randoms and assigning probability to each object without having to add them more times into the array? This would clean and help me through a lot of messy coding.
I don't personally know of any ways to assign probability, but we can kind of create our own way. It's not the most efficient way of doing so, but it does create a pseudo-probability.
int [] numbers = {1,2,3,4,5,6,7,8,9,10};
int index = 0;
Random rnd = new Random();
for (int i = 0; i < 3; i ++)
{
index = index + rnd.nextInt(numbers.length);
}
index=index/3;
System.out.println(numbers[index]);
This will skew the array index to be somewhere near the middle, most of the time. So the most common values, in theory, will be near the middle of the array, while the borders will be very uncommon.
You can change the "3" value to be whatever you want, the higher this number is, the more middle-biased the numbers should be.
Upon running this 10 times, my values were:
2,6,7,2,6,5,6,6,4,5
I'm trying to get a program so that it loops and adds up the sum of an array. My code appears to be working, with the exception that it states that the text[j] in adding = adding + text[j] is an incompatible type (I'm assuming data type). Earlier in the code, I have int adding = 0;. This is the erroneous code:
for (int j=0;j<=total;j++){
adding = adding + text[j];
System.out.println(text[j]);
}
where total is the limiting factor. If I put:
for (int j=0;j<= total;j++){
adding = adding + j;
System.out.println(text[j]);
}
the program compiles but gives 45, which is incorrect.
Why is this happening? Thanks!
The answer actually turned out to be outside the code given. I had set my array to be a String, not an int as it should have been.
If your text[] is String[] or char[] as the name suggests then I believe you are trying to update text[] elements with suffix j or adding, which you can write as:
If it is char[] then write
text[j] = (char)(adding + (int)text[j]);
If it is String[] then write
text[j]= text[j]+adding;
as required. It all depends on what is the data type of text[] and what are you trying to achieve?
Also as suggested in one of the answers, if total is length of the array, then change the comparison to < to avoind ArrayIndexOutOfBoundsException
Your second example, adds j into adding but prints text[j] value, which is nothing to do with the addition of adding and j.