I'm not sure why this won't print out anything
for (int number : humidity)
{
if (sum < 12)
{
System.out.printf("%6d",humidity[sum]);
sum++;
}
}
Humidity is taken in from a file
Scanner inFileHumid = new Scanner(fileNameHumid);
int [] humidity = new int[length];
Then is set to the array
while (inFileHumid.hasNextInt())
{
humidity[n] = inFileHumid.nextInt( );
n++;
}
and the numbers from the file are 69 67 66 64 66 69 67 67 70 69 69 70 which are the ones I'm trying to get to be printed in my for each loop
You are iterating each number in humidity, but then you ignore those values and test some unrelated sum. I think you want
for (int number : humidity)
{
System.out.printf("%6d", number);
}
Or equivalently,
for (int sum = 0; sum < humidity.length; sum++)
{
System.out.printf("%6d", humidity[sum]);
}
I think you just have a problem indexing into humidity. So this should work.
for (int number : humidity){
if (number < 12) // Look at the value
{
System.out.printf("%6d", number); // Print what is in the array
}
}
Assuming sum is zero before the loop is entered, that code works.
int[] humidity = {1,2,3,4,5,6,7,8,9,0,1,2};
int sum= 0;
for (int number : humidity) {
if (sum < 12) {
System.out.printf("%6d", humidity[sum]);
sum++;
}
}
producing:
1 2 3 4 5 6 7 8 9 0 1 2
So for the code to fail sum must be greater or equal to 12 before the loop is entered.
Related
I have this code, and it works fine, but I want to format it so that it prints 15 numbers on each line.
I have seen it done with % or for loops, but I don't know how to use them in my code. Thank you to everyone for helping! Thank you!
import java.util.*;
import java.io.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number that you want to find all the prime numbers up to it: ");
int num = sc.nextInt();
boolean[] bool = new boolean[num];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i * i); j < num; j = j + i) {
bool[j] = false;
}
}
}
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2; i < bool.length; i++) {
if(bool[i]==true)
{
System.out.print(i + " ");
}
}
}
}
You can make increment a count each time bool[i] is true, then move to the next line when the count is 15 and reset the count back to 0.
Here is what your print loop would now look like:
System.out.println("List of prime numbers upto given number are : ");
int count = 0;
for (int i = 2; i< bool.length; i++) {
if(bool[i])
{
if (count == 15) {
count = 0;
System.out.println();
}
System.out.print(i + " ");
count++;
}
}
Output:
Enter the number that you want to find all the prime numbers up to it: 120
List of prime numbers upto given number are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
In the context of what you're doing the best option would be something like this:
int count = 0;
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2; i< bool.length; i++) {
if(bool[i]==true) {
System.out.print(i + " ");
count++;
}
if(count == 15) {
System.out.println();
count = 0;
}
}
Do it as follows:
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2, j = 1; i < bool.length; i++) {
if (bool[i] == true) {
System.out.print(i + " ");
if (j % 15 == 0) {
System.out.println();
}
j++;
}
}
A sample run:
Enter the number that you want to find all the prime numbers up to it: 200
List of prime numbers upto given number are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173 179 181 191 193 197
199
Feel free to comment in case of doubt.
Im trying to get the maximum number in the array, using the function getMax(), but the output is always 0.
When input is: 12 87 3 10 55 69 40
Result should be: 69
Instead result is: 0
public int getMax()
{
int x=1;
int y=0;
for(int i=0; i<size; i++)
{
if(i!=size-1)
{
if(arr[i]>arr[x])
{
y=arr[i];
x++;
}
}
}
return y;
}
Simply set the default maximum value to the first value in the array. Then, iterate thru the array comparing that value to the next one in the array. If is is larger then assign it to max. Continue to the end of the array.
As 89 is larger, I think you want the local maximum of the longest non-decreasing subsequence in the array. The problem is not well formulated, so probably no homework.
array: 12 87 3 10 55 69 40
sequences: 12 87
3 10 55 *69* answer
40
int maxOfLongestSubsequence(int[] a) {
int maxSeqLength = 0;
int max = Integer.MIN_VALUE;
int seqStart = -1;
for (int i = 0; i <= a.length; ++i) {
if (i == 0 || i == a.length - 1 || a[i] < a[i - 1]) { // New subsequence
int seqLength = i - seqStart;
if (i - seqLength > maxSeqLength) {
maxSeqLength = seqLength;
max = a[i - 1];
}
seqStart = i;
}
}
return max;
}
Formulate the problem. Depict the data as I did. And program it out.
You can pick the max of an int array like this:
int [] numbers = new int[]{12,87,3,10,55,69,40};
int max = numbers[0];
for(int current : numbers) {
max = current >= max ? current : max;
}
System.out.println(max);
I am confused from the comment "sorting begins". Could anyone explain this to me.
class endsly {
public static void main(String[] args) {
int num[] = { 55, 40, 80, 65, 71 };
int n= num.length;
System.out.println("Given list: ");
for (int i = 0; i < n; i++) {
System.out.println(" " + num[i]);
}
System.out.println("\n");
//sorting begins
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (num[i] < num[j]) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.println("Sorted list:");
for (int i = 0; i < n; i++) {
System.out.println(" " + num[i]);
}
System.out.println(" ");
}
}
The two nested loops implement a variation of Selection Sort algorithm with a small "twist" at the end.
Sorted portion of the array is on the left of i, i.e. items from 0, inclusive, to i, exclusive
Nested loop walks the unsorted part, swapping in progressively smaller items into num[i]
By the end of the nested loop the smallest of the unsorted items is in num[i]
By the end of the outer loop the array is sorted
Note that this is different from the "classic" selection sort, which picks the next smallest item from the unsorted array without swapping anything, and performs a single swap at the end of the nested loop. Traditional implementation of selection sort would look like this:
for (int i = 0; i < n; i++) {
int minPos = i;
// Look for a position of the smallest element
for (int j = i + 1; j < n; j++) {
if (num[minPos] < num[j]) {
minPos = j;
}
}
// Perform the swap after the loop has ended
int temp = num[i];
num[i] = num[minPos];
num[minPos] = temp
}
The algorithm you have posted is selection sort where multiple swaps are permitted, but in reverse (so that the largest elements are placed at the head of the array, rather than the smallest). The general algorithm for selection sort (standard selection sort, where the smallest element is moved to the front of the array) with multiple swaps is:
for element i at 0 to n:
for element j at i to n:
if element at j is less than element at i:
swap element at i with element at j
Starting at element 0, the algorithm finds the smallest value from index 0 to index n and places it at index 0. The next iteration, the algorithm finds the smallest value from index 1 to n and places it at index 1. The next iteration, the algorithm finds the smallest value from index 2 to n and places it at index 2. This algorithm continues until the final iteration, which finds the smallest value from index n - 1 to n and places it at index n.
In particular case of your algorithm, it is not the smallest value that is found in each iteration, it is the largest. Thus, once the array is sorted, the array is ordered from largest to smallest value. For reference, the conditional in the sorting algorithm is num[i] < num[j], but it may be easier to read this as num[j] > num[i], which means that elements should be swapped if the element at j is greater than the element at i. You can see each step demonstrated by altering your code to print the value of the array at each step:
public static void main(String[] args) {
int num[] = { 55, 40, 80, 65, 71 };
int n= num.length;
System.out.println("Before sorting");
printArray(num);
System.out.println();
//sorting begins
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (num[i] < num[j]) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
System.out.print("Iteration i = " + i + ": ");
printArray(num);
}
System.out.println("\nAfter sorting");
printArray(num);
System.out.println();
}
private static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(" " + array[i]);
}
System.out.println();
}
Executing this code results in the following output:
Before sorting
55 40 80 65 71
Iteration i = 0: 80 40 55 65 71
Iteration i = 1: 80 71 40 55 65
Iteration i = 2: 80 71 65 40 55
Iteration i = 3: 80 71 65 55 40
Iteration i = 4: 80 71 65 55 40
After sorting
80 71 65 55 40
As can be seen in the output, each iteration successively finds the largest value and moves it down. During the first iteration, 80 is moved to index 0; during the second, 71 is moved to index 1; and so forth, until 5 iterations (matching the size of num) iterations are performed. Although it may appear that iteration i = 4 is wasted, this is only true for this particular case since the last two elements are already sorted (when 65 and 55 are swapped in iteration i = 2).
In general, it is a good idea to step through each iteration of a sorting algorithm to see what the algorithm is doing. This also aids in determining the complexity of the algorithm as well. In this case, a set of nested loops are used, where the outer loop runs from 0 to n and the inner loop runs from i (starting at 0) to n. This creates the following complexity: n(n-1)(n-2)..., or O(n2). For example, suppose there are 10 elements in the array; the first iteration inner loop will run 10 times; the second iteration inner loop will run 9; and so on. See the Wikipedia Selection Sort Complexity Analysis for more information.
The algorithm in the question differs from the standard selection sort in that the standard selection sort finds the minimal (or maximal in this case) element from i to n and performs at most one swap at the end of the iteration. In this case, instead of performing one swap at the end, any time a minimal (or maximal) value is found, the swap is immediately performed, which may result in more than one swap per iteration. This can be demonstrated by instrumenting the algorithm to print the array values each time a swap is performed:
public static void main(String[] args) {
int num[] = { 55, 40, 80, 65, 71 };
int n= num.length;
System.out.println("Before sorting");
printArray(num);
System.out.println();
//sorting begins
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (num[i] < num[j]) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
System.out.print(" Swap performed:");
printArray(num);
}
}
System.out.print("Iteration i = " + i + ": ");
printArray(num);
}
System.out.println("\nAfter sorting");
printArray(num);
System.out.println();
}
private static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(" " + array[i]);
}
System.out.println();
}
This results in the following output:
Before sorting
55 40 80 65 71
Swap performed: 80 40 55 65 71
Iteration i = 0: 80 40 55 65 71
Swap performed: 80 55 40 65 71
Swap performed: 80 65 40 55 71
Swap performed: 80 71 40 55 65
Iteration i = 1: 80 71 40 55 65
Swap performed: 80 71 55 40 65
Swap performed: 80 71 65 40 55
Iteration i = 2: 80 71 65 40 55
Swap performed: 80 71 65 55 40
Iteration i = 3: 80 71 65 55 40
Iteration i = 4: 80 71 65 55 40
After sorting
80 71 65 55 40
My problem is when I sort a list it will get the last element of the array wrong, ending up with it at the beginning of the array. In my example it fails to sort the last element which is 9, ending up printed first ahead of small numbers such as 0 and 1. Here is my code:
public class ty {
public static void main(String[]argus){
int []numbers={45,23,34,545,56,23,4,1,66,0,9};
int j;
for( int i=0;i<numbers.length;i+=1){
int first=0;
for(j=0;j<=i;j+=1){
if(numbers[j]>=first){
first=numbers[j];
numbers[j]=numbers[i];
numbers[i]=first;}
}//inner loop
}//first loop
for(int i=0;i<numbers.length;i+=1){
System.out.print(numbers[i]+" ");}
}
}
//the output is 9 0 1 4 23 23 34 45 56 66 545
As you see, they are in order except for the 9 at the start which is out of place.
You have the wrong output as a result of a logical error. You have mistakes in the Selection sort technique. Here's how to do it:
int []numbers={45,23,34,545,56,23,4,1,66,0,9};
for(int i=0; i<numbers.length-1; i+=1){
int m = i;
for(int j=i+1; j<numbers.length; j+=1){
if(numbers[m]>numbers[j])
m = j;
}
int temp = numbers[m];
numbers[m] = numbers[i];
numbers[i] = temp;
}
for(int i=0; i<numbers.length; i+=1)
System.out.print(numbers[i]+"\t");
This will work correctly and give the output:
0 1 4 9 23 23 34 45 56 66 545
Currently I'm only able to display odd numbers of 1 3 5 7 9. However, I would like to display all the odd numbers from 1 - 99 with 9 rows and 5 col. May I know how am I able to display from 11 onwards rather than just 9 rows of 1 3 5 7 9.
Below is the code I'm stuck with.
public static void main(String args[])
{
for (int i=1; i<=9; i++)
{
for (int j=1; j<=10; j++)
{
if (j%2 !=0)
System.out.print(j + " " );
}
System.out.println();
}
}
first you need to calculate your number, try
for (int i=0; i<=9; i++)
{
for (int j=1; j<=10; j++)
{
int number = j+i*10
if (number%2 !=0)
System.out.print(number + " " );
}
System.out.println();
}
but this problem you can solve with single loop
for (int i=1; i<=99; i++)
{
if (number%2 !=0)
System.out.print(number + " " );
if (number%10 ==0)
System.out.println();
}
for ( i = 1; i < 100; i+=2 ) {
System.out.print(i);
}
System.out.println();
public static void main(String args[])
{
for (int i=1; i<=99; i++)
{
if (i%2 !=0)
System.out.print(i + " " );
if(i%10 == 0)
System.out.println();
}
}
This code will allow you to do what you want with 1 loop which is more efficient than using nested loops.
This will loop through each number from 1-99 and print if it is odd. If the number is a multiple of 10 then it will print a new line.
Maybe this helps:
public static void main(String args[])
{
for (int j = 0; j < 10; j++)
{
for (int i = 1; i <= 9; i++)
{
int c = j * 10 + i;
if (c % 2 !=0)
System.out.print(c + " " );
}
System.out.println();
}
}
Other alternative with just one loop:
public static void main(String args[]) {
for (int j = 1; j <= 99; j += 2) {
System.out.print(j + " ");
if ((j + 1) % 10 == 0) {
System.out.println();
}
}
}
If you want to use a nested forloop you have to use both iterating variables to build your numbers. You dont use i at all in the inner for-loop. Therefore only 1 3 5 7 9 gets printed 9 times. For a hotfix try to use something like
System.out.print(i + j + " " );
instead of
System.out.print(j + " " );
note how i+j does not compute an addition here.
Anyway like pointed out in the comments you dont really need 2 loops here.
we cheat:
for (int i = 1; i <= 99; i += 2)
System.out.printf("%d%s", i, i % 10 == 9 ? "\n" : " ");
we check:
int c =0;
for (int i = 1; i <= 99; i++)
if ((i & 1) == 1) {
c++;
System.out.printf("%d%s", i, c % 5==0 ? "\n" : " ");
}
both output same, 5 odd numbers in a row, without trailing spaces.
With this one you can easily set the number of columns as you like it.
We use a single loop.
Code:
int columns = 5;
int start = 1;
int end = 99;
// iterate through every seconds i.
for (int i = start; i <= end; i += 2) {
System.out.printf("%-4d", i);
// if we have displayed enough words, start a new line
if (i % (2 * columns) == 0) {
System.out.println();
}
}
Output:
1 3 5 7 9
11 13 15 17 19
21 23 25 27 29
31 33 35 37 39
41 43 45 47 49
51 53 55 57 59
61 63 65 67 69
71 73 75 77 79
81 83 85 87 89
91 93 95 97 99
However, if I understood your question correctly, you wanted to show numbers with 5 columns and 9 rows? Well this is impossible if we print only the numbers from 1 to 99. With 5 columns and numbers 1 to 99, you will get 10 rows.
Your code now prints 9 rows of:
1 3 5 7 9
This is happening because your inner loop loops on values between 1 and 9, always.
You should try something like:
int counter = 0;
for(int i=1; i<=99; i++) {
if(i%2 != 0) {
System.out.print(i + " ");
counter++;
}
if(counter == 5) {
System.out.println();
counter = 0;
}
}
This will print:
1 3 5 7 9
11 13 15 17 19
21 23 25 27 29
31 33 35 37 39
41 43 45 47 49
51 53 55 57 59
61 63 65 67 69
71 73 75 77 79
81 83 85 87 89
91 93 95 97 99