I'm having a hard time getting this to print the way my professor wants. I have tried print, println, \t, and, \n however the results either come out vertically and side by side or each duplicated number next to each other horizontally. This is what my professor wants:
The results (printed twice) are:
14 81 94 91 47 57 98 89 82 15
14 81 94 91 47 57 98 89 82 15
my outputs have consisted of:
The results (printed twice) are:
14 14
81 81
94 94
91 91
47 47
57 57
98 98
89 89
82 82
15 15
The results (printed twice) are:
14 14 81 81 94 94 91 91 47 47 57 57 98 98 89 89 82 82 15 15
The results (printed twice) are:
14 14 81 81 94 94 91 91 47 47 57 57 98 98 89 89 82 82 15 15
This is my code thus far:
System.out.println("The results (printed twice) are:\t");
for (i = 0; i< arr.length; i++){
arr[i] = rand.nextInt(100) + 1;
int[] arrb = arr.clone();
System.out.print(arr[i] + " " + arrb[i] + " ");
Your current code attempts to do 2 things in a single loop:
Generate a new random number.
Print it (twice).
This is never going to work - you need to print the other numbers first, and then 'start over' and print the first number a second time. You can't ask java to 'hop between lines' - standard output is a rather abstract concept. Perhaps its a line printer; you can't ask it to swallow a page it just printed out back into itself and unprint something, for example.
Thus, the answer lies in separating out your tasks. This is usually a good idea for any programming task of any stripe:
Fill an int[] array by generating random numbers.
Print an int[] array - whatever may be inside it.
Do the previous thing twice in a row.
That involves at least 3 for loops, in other words.
int LEN = 100;
int[] numbers = new int[LEN];
for (int i = 0; i < LEN; i++) {
numbers[i] = rnd.nextInt(100) + 1;
}
That's one job done. Don't complicate matters by attempting to also print from there. You're just doing the one job.
Printing one line is easy:
for (int i = 0; i < LEN; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
And how do we do things more than once? With.. for loops:
for (int print = 0; print < 2; print++) {
for (int i = 0; i < LEN; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
}
Something like this could work:
int[] arr = new int[] { 14,81,94,91,47,57,98,89,82,15 };
System.out.println("The results (printed twice) are:\t");
int counter = 0;
while(counter <= 1) {
for (int i = 0; i< arr.length; i++) {
System.out.print(arr[i] + " ") ;
}
counter++;
System.out.println();
}
Or if you want a nested for loop could also do the work:
int[] arr = new int[] { 14,81,94,91,47,57,98,89,82,15 };
System.out.println("The results (printed twice) are:\t");
for (int i = 0; i <= 1 ; i++){
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + " ") ;
}
System.out.println();
}
And then the output should be:
The results (printed twice) are:
14 81 94 91 47 57 98 89 82 15
14 81 94 91 47 57 98 89 82 15
Basically the logic here is just repeat the printing of the list two times with another for loop or while loop, both works the same way in the examples above, if you have any question you can reply my answer.
Use something like this instead:
System.out.println("The results (printed twice) are:\t");
for (i = 0; i< arr.length; i++){
arr[i] = rand.nextInt(100) + 1;
int[] arrb = arr.clone();
System.out.print(Arrays.toString(arr));
System.out.println();
System.out.print(Arrays.toString(arrb));
Example output:
[1,2,3,4]
[1,2,3,4]
If you want the outout to be 1 2 3 4 instead, use a simple for-loop
for (int i = 0; i<arr.lenght; i++){
System.out.print(arr[i] + " ")
}
System.out.println();
for (int i = 0; i<arrb.lenght; i++){
System.out.print(arrb[i] + " ")
}
There is no need to clone your array.
int[] arr = new int[10];
Random rand = new Random();
System.out.println("The results (printed twice) are:\t");
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(100) + 1;
System.out.print(arr[i] + " " + arr[i] + " ");
System.out.println();
}
The result:
The results (printed twice) are:
58 58
31 31
22 22
81 81
36 36
38 38
40 40
9 9
10 10
11 11
Did u try to System.out.println ???
Something like that:
System.out.println("The results (printed twice) are: ");
for (i = 0; i< arr.length; i++){
arr[i] = rand.nextInt(100) + 1;
int[] arrb = arr.clone();
System.out.println(arr[i]);
System.out.println(arrb[i]);
}
Or u can try to make 2D array and fill row[0] with Your arr.
Then fill row [1] with Your arrb
Related
I have a Matrix with different line size , i read it from a text file
private int set_data[][];
I have created another copy
private int set_number=set_data.length;
private int[][] set_cluster = new int[set_number][];
What i want to do is to fill set_cluster from the third row of each line
For example we have :
line one 1 3 30 49 48
line two 2 3 22 36 11 40
line three 3 5 51 44 47 15 38 40
and my goal is to store in set_cluster these numbers
line one 30 49 48
line two 22 36 11 40
line three 51 44 47 15 38 40
I have tried this code
private void fill_id_cluster() {
for (int i = 0; i < set_data.length; i++) {
set_cluster[i] = new int[set_data[i].length - 2];
for (int j = 0; j < set_data[i].length - 2; j++) {
set_cluster[i][j] = set_data[i][j + 2] ;
System.out.print(set_cluster[i][j] + " ");
}
}
}
Thanks for your help!
I created an array with 50 elements.
The first 25 elements are equal to the square of the index and the last 25 elements are equal to the index times 3.
This is my current output: 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 75 78 81 84 87 90 93 96 99 102 105 108 111 114 117 120 123 126 129 132 135 138 141 144 147
My desired output is this:
0 1 4 9 16 25 36 49 64 81
100 121 144 169 196 225 256 289 324 361
400 441 484 529 576 75 78 81 84 87
90 93 96 99 102 105 108 111 114 117
120 123 126 129 132 135 138 141 144 147
I have tried using the formatting feature (printf), but I can't seem to get it to work. I've also tried using an if statement, but that gave me a "cannot convert int to boolean" error.
I've searched some similar questions but their solutions are either too complex for me to understand or they don't work for my specific code since I am already using for loops.
Does anybody have an easy way to achieve this? This is for a homework assignment. I have the logic part down, which ironically should be the hard part but this formatting part has me stumped lol
I appreciate any help!
This is my code right now:
int [] Number = new int [50];
for(int i = 0; i < Number.length/2; i++) {//first loop
System.out.print(i * i + " ");
}
for(int i = 25; i < Number.length; i++) {//second loop
System.out.print(i * 3 + " ");
}
You don't need an array. What you want to do is:
Loop 50 times
1st time, set i to 0
2nd, set i to 1
50th time, set i to 49
Each time:
if i < 25 print i * i
if i >= 25 print i * 3
Every 10th time, print a new line.
Here is how you can do it without an array:
int size = 50;
for (int i = 0; i < size; i++) {
// Print a newline after every 10 elements
if (i != 0 && i % 10 == 0) {
System.out.println();
}
// Print i * i for 0 up to but excluding 25
// Print i * 3 after that
if (i < size / 2) {
System.out.print(i * i + " ");
} else {
System.out.print(i * 3 + " ");
}
}
If you really wanted to loop over the elements of an array:
int[] myArr = new int[50];
for (int i = 0; i < myArr.length; i++) {
if (i != 0 && i % 10 == 0) {
System.out.println();
}
if (i < size / 2) {
System.out.print(i * i + " ");
} else {
System.out.print(i * 3 + " ");
}
}
Also it is not a good idea to name a variable as Number, because:
There is already a class in Java called Number and that can confuse readers.
Variables in Java by convention should be in camelCase. Class names in PascalCase (see here).
Try this:
int[] Number = new int[50];
for (int i = 0; i < Number.length / 2; i++) {//first loop
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(i * i + " ");
}
for (int i = 25; i < Number.length; i++) {//second loop
if (i % 10 == 0) {
System.out.println();
}
System.out.print(i * 3 + " ");
}
Does the array require to store the correct values?
int[] numbers = new int[50];
for (int i=0; i<numbers.length; ++i) { //calculating correct value into the array
numbers[i] = (i < 25) ? i * i : i * 3;
}
for (int i=0; i<numbers.length; ++i) { //displaying data
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
I hope this helps
int[] arrNum = new int[50];
for (int i = 0; i < numbers.length; ++i) { //First loop to enter the data
numbers[i] = ((i < 25) ? i * i : i * 3);
}
for (int i = 0; i < numbers.length; ++i) { //Second loop to output data
if (i % 10 == 0) System.out.println;
System.out.print(numbers[i] + " ");
}
int[] array = new int[50];
int count = 0; // To print 10 elements per line
for(int I = 0; I < array.length; I++) {
if (count == 10) {
System.out.println();
count = 0;
}
System.out.print(a1[i] + " ");
count++;
}
public class Average {
static Integer[][] myDouble = new Integer[10][12];
static int x = 0, y = 0;
static int strDouble;
public Average() {
try {
BufferedReader in = new BufferedReader(new FileReader("StudentIdAverage.txt"));
String line;
while ((line = in.readLine()) != null) {
String[] values = line.split("\\s+");
for (String str : values) {
strDouble = Integer.parseInt(str);
myDouble[x][y] = strDouble;
y = y + 1;
}
x = x + 1;
y = 0;
}
in.close();
} catch (IOException ioException) {
}
}
public static void main(String[] args) {
Average arr = new Average();
for (int i = 0; i < myDouble.length; ++i) {
IntSummaryStatistics statistics = Arrays.asList(myDouble[i]).stream().filter(intValue -> intValue != null).collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Average: " + statistics.getAverage() + ", min: " + statistics.getMin() + ", max: " + statistics.getMax());
}
for (int k = 0; k < myDouble.length; ++k) {
int count = 0; // count the values used to calculate sum
double sum = 0;
double average = 0;
for (int j = 0; j < myDouble[k].length; ++j) {
if (myDouble[k][j] == null) //skip the null values
{
continue;
}
//Arrays.sort(myDouble[i]);
sum += myDouble[k][j];
count++;
System.out.print(Average.myDouble[k][j] + " ");
}
average = (sum / count); //use count instead of lenght
System.out.println(" ");
System.out.println(average);
}
}
}
input txt file
45 72 90 50 67 63 81 71 55 56 80 74/n 55 54 79 72 75 68/n 51 88 79 72/n 98 52 52 53 50 92 67 99 92 50 61 91/n 94 48 53 92 97/n 97 69 77 74 68 54 87 74 54 83 58 69/n 75 49 87 61 66 53 79 48 96 60/n 58 71 51 73 53 75 93 81 45 69 78 65/n 50 88 78 81 99 61 97 70 87 80 69/n 91 89 97 80 93 82 92 49 52 69 96 61
Given an array, myDouble[k] of size myDouble[k].length (call it L), dropping the min and max really means ignore the min and max. Since the sum is calculated as average/size, ignore the min and max values.
The sum is in the form newsum + min + max. Obtain the new sum by subtracting min and max from sum: sum -= (min + max).
You can get the min and max manually so you really are using just one for loop. Start min and max at the first non-null entry, and update min and max if the next entry is strictly less or strictly greater than the (candidate) current value, respectively.
The new size will also decrease by two (Beware if size is two or less!). That means, the average excluding min and max is the new sum/(myDouble[k].length - 2).
Simply keep track of the min and max value then substract both value at the end. You don't need to change the rest. This will allow you to get the average value without the need to read the line twice (to remove those values).
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (int j = 0; j < myDouble[k].length; ++j) {
if (myDouble[k][j] == null) // skip the null values
{
continue;
}
min = Math.min(myDouble[k][j], min);
max = Math.max(myDouble[k][j], max);
...
}
sum = sum - min - max;
If you can find those value twice, you will need to use a way to count the occurrence of those value. But you get the idea here.
Note that another solution would be to sort the array then skip the first and last value :
double[] sortedArray = Arrays.sort(myDouble[k]);
for (int j = 1; j < sortedArray.length - 1; ++j) {
sum += sortedArray[j];
}
This solution is easier but required more memory, for big list I would not recommend it (but performance is not an issue)
public class Average {
static int[][] myDouble = new int[10][12];
static int x = 0, y = 0;
static int strDouble;
public Average() {
try {
BufferedReader in = new BufferedReader(new FileReader("StudentIdAverage.txt"));
String line;
while ((line = in.readLine()) != null) {
String[] values = line.split("\\s+");
for (String str : values) {
strDouble = Integer.parseInt(str);
myDouble[x][y] = strDouble;
y = y + 1;
}
x = x + 1;
y = 0;
}
in.close();
} catch (IOException ioException) {
}
}
public static void main(String[] args) {
Average arr = new Average();
//int[][] residuescores = arr.myDouble;
for (int i = 0; i < myDouble.length; ++i) {
int sum = 0;
int average = 0;
for (int j = 0; j < myDouble[i].length; ++j) {
Arrays.sort(myDouble[i]);
sum+=myDouble[i][j];
System.out.print(Average.myDouble[i][j] + " ");
}
average = (sum/myDouble[i].length);
System.out.println(" ");
System.out.println(average);
}
}
}
input File:-
45 72 90 50 67 63 81 71 55 56 80 74/n 55 54 79 72 75 68/n 51 88 79
72/n 98 52 52 53 50 92 67 99 92 50 61 91/n 94 48 53 92 97/n 97 69 77
74 68 54 87 74 54 83 58 69/n 75 49 87 61 66 53 79 48 96 60/n 58 71 51
73 53 75 93 81 45 69 78 65/n 50 88 78 81 99 61 97 70 87 80 69/n 91 89
97 80 93 82 92 49 52 69 96 61
If you are using java 8 you can utilize streams and SummaryStatistics to calculate average/min/max like below
static Integer[][] myDouble = new Integer[10][12];
for (int i = 0; i < myDouble.length; ++i) {
IntSummaryStatistics statistics = Arrays.asList(myDouble[i]).stream().filter(intValue -> intValue!=null).collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Average: "+statistics.getAverage()+", min: "+statistics.getMin()+", max: "+statistics.getMax());
}
If you can not use java 8 then note that the issue with your code is that you are using primitive int in your array which will initialize the values to 0 and thus you get 0 when the row has less values than 12. One way to solve it is to change your array to Integer class but remember to skip the entries which have null as now instead of 0 you will get null in the rows with less entries.
your code working with int array changed to Integer, skipping nulls and using count instead of array.length:
for (int i = 0; i < myDouble.length; ++i) {
int count = 0; // count the values used to calculate sum
int sum = 0;
int average = 0;
for (int j = 0; j < myDouble[i].length; ++j) {
if(myDouble[i][j] == null) //skip the null values
continue;
//Arrays.sort(myDouble[i]);
sum+=myDouble[i][j];
count++;
System.out.print(App.myDouble[i][j] + " ");
}
average = (sum/count); //use count instead of lenght
System.out.println(" ");
System.out.println(average);
}
I need a for loop that its limit could be exceeded after one ends(one of the limits), I like to declare the limit 9 and start traversing an array to index of 8 then start from 9 and take 9 more steps and so on,until I reach the end of the array, my tries reached to this point but I wonder if it works correctly:
int [] i={9,18,27,36,45,54,63,72,81};
for(int x:i){
for(int j=0;j<x;j++)
{}
}
does the nested for loop going to change the x value after each complete cycle of the inner for loop or not?
then start from 9 and take 9 more steps
Your code doesn't behave as you want, since the inner loop always starts at 0.
There's no need to declare the i array. You can do it like this :
int start = 0;
for (int i = 9; i <= 81; i+=9) {
for (int j = start; j < i; j++) {
}
start = i;
}
Or as phflack suggested :
for (int i = 9; i <= 81; i+=9) {
for (int j = i - 9; j < i; j++) {
}
}
you can use this code:
int start = 0;
for (int i = 9; i <= 81; i+=9) {
for (int j = start; j < i; j++) {
System.out.print(j+" ");
}
System.out.println();
start = i;
//System.out.print(start+" ");
}
}
and you see:
0 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17
18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62
63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80
Another training for you:
int start = 0;
for (int i = 1; i <= 10; i++) {
for (int j = 1; j < i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
and you can see:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
You can use two loop to print like matrix.