I am inputting a array of numbers using the scanner class. I need to print these numbers, 5 per line.
Example:
How big is the Array: 20
Enter 20 whole numbers:
92 71 20 13 18 65 21 72 97 100 73 22 87 19 99 100 64 29 45 88
**The array contains:
92 71 20 13 18
65 21 72 97 100
73 22 87 19 99
100 64 29 45 88
**
Im having trouble getting the loop and variables correct.
This is my method for reading the input:
Scanner keyboard = new Scanner(System.in);
//prompt to enter size of Array
System.out.print("How big is the Array: ");
n = keyboard.nextInt();
numbers = new int[n];
//prompt to enter numbers in Array
System.out.println("\nEnter " +n + " whole numbers: ");
for (int i = 0; i < n; i++)
{
numbers [i]= keyboard.nextInt();
}
This is my code that Im having trouble with
for (int i= 0 ; i < 5; i++)
{
for (int l = 0 ; l < 5; l++)
System.out.print (numbers [l]+ " ");
System.out.println();
}
this is not giving me the inputted numbers, it is just giving me 1-5 line after line.
I need help getting the inputted array into a variable and then forming a loop to manipulate it.
for (int i = 0; i < numbers.length; i++) {
if(i % 5 == 0) System.out.println();
System.out.print(numbers[i] + " ");
}
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.
I'm newbie and I don't know how to merge my parts of knowledge.
I have to make Algorithm looking for the longest rising sequence of numbers.
My file has 50 columns, every column has some random numbers separated with space.
I'm still trying to put them in Matrix or other multi dimension arrays but I don't know how.
This is my code:
import java.io.File;
import java.util.Scanner;
import java.util.StringTokenizer;
public class reading {
public static void main(String[] args) {
double[][] numbers = new double[101][101];
int column = 0, row = 0;
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
for (int columns = 0; columns < 101; columns++) {
String input2 = input.nextLine();
StringTokenizer strToken = new StringTokenizer(input2);
int count = strToken.countTokens();
for (int rows = 0; rows < count; rows++) {
numbers[columns][rows] = Integer.parseInt((String) strToken.nextElement());// writing values to arrays
System.out.println(numbers[columns][rows]);// test
}
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// here someday will be algorithm
}
}
**Sorry guys for my poor english i'm trying to tell what i want but it's a little bit hard for me. :( I got file whit a lot of numbers and i have to found longest series of numbers from smaller to most bigger without replacing numbers **
little example from file "
45 -31 -21 -34 30 -2 12 21 -39 -46 -48 8 15 30 8 -48 29 12 11 -28 40 27 28 -45 2 50 8 28 14 47 -22 -20 27 16 43 -7 35 13 7 15 40 -42 23 -7 7 18
22 13 28 -33 -15 -46 12 -22 31 -33 39 34 -11 45 -25 -25 -50 48 31 -20 -25 -5 5
18 -36 -24 -17 10 24 21 -35 6 19 38 6 44 20 30 -49 -33 -44 9
37 -36 -18 2 -2 35 -2 45 -36 40 26 -42 -17 45 40 -31 -21 33 -4 -50 40 13 -50 11 12 37 -26 38 -31 7 30 4 32 -50 -7 -40 -12 27
17 -5 -11 41 -1 46 16 16 48 38 -49 10 1 25 39 26 -14 -50"
If you're trying to read whitespace-separated values, the easiest solution is probably just to use Scanner.next or one of the other next... functions (other than nextLine, like Scanner.nextInt, or Scanner.nextDouble in your case).
These functions use whitespace as a delimiter, so each subsequent call will return the next piece of text that's between some whitespace, and also convert it to the appropriate type, if applicable.
input = new Scanner(file);
for (int rows = 0; rows < numbers.length; rows++){
for (int columns = 0; columns < numbers[rows].length; columns++){
numbers[rows][columns] = input.nextDouble();
}
}
If you want each line in the file to be a row, the rows loop should be on the outside (consider that you want to start with row 0 and go through each column in the same way you'd start from line 0 and go through each value in that line).
This is not particularly robust (if there's something wrong with your data, it might still work or it might be hard to find where the problem is).
If you're looking for something more robust, I might recommend something more like:
for (int rows = 0; rows < numbers.length; rows++){
String[] split = input.nextLine().split("\\s+"); // \\s+ is 1 or more whitespace characters
if (split.length != numbers.length) {
throw new IllegalArgumentException("Line " + rows + " has " + split.length + " columns, but needs " + numbers.length);
}
for (int columns = 0; columns < numbers[rows].length; columns++){
numbers[rows][columns] = Double.parseDouble(split[columns]);
}
}
In Java 8 we can achieve the same result like this:
final int DESIRED_ROW_LENGTH = 101;
for (int rows = 0; rows < numbers.length; rows++){
numbers[rows] = Arrays.stream(input.nextLine().split("\\s+"))
.mapToDouble(Double::parseDouble).toArray();
if (numbers[rows].length != DESIRED_ROW_LENGTH) {
throw new IllegalArgumentException("Line " + rows + " has " + numbers[rows].length + " columns, but needs " + DESIRED_ROW_LENGTH);
}
}
I'll provide an alternative* to #Dukeling answer on the premise that you are actually looking for some sort of algorithm for the longest rising sequence of numbers:
Basically, do it directly while reading the file, and just check each position of ((column + 1) - (column) == 1) and update a field if so.
File file = new File("\\\\share\\file\\path\\file.txt");
Scanner sc = new Scanner(file);
int totalCount = 0;
int tempCount = 0;
int tempLineNumber = 1;
int totalLineNumber = 0;
while (sc.hasNextLine()) {
String[] array = sc.nextLine().split("\\s+");
for (int i = 0; i < array.length - 1; i++) {
if (Integer.parseInt(array[i + 1]) - Integer.parseInt(array[i]) == 1) {
tempCount++;
}
}
if (totalCount < tempCount) {
totalCount = tempCount;
totalLineNumber = tempLineNumber;
}
tempCount = 0;
tempLineNumber++;
}
System.out.println("The max longest rising sequence of numbers is: "
+ totalCount + " at line " + totalLineNumber);
* I just threw this example together quickly, and most likely has an issue or two, such as missing edge cases etc
The actual algorithm happens on a one-dimensional array of integers.
So this could be done per line read from the file.
Path path = Paths.get(input.nextLine());
for (String line : Files.readAllLines(path, Charset.defaultCharset())) {
// Convert line into numbers:
String[] words = line.split(" ");
int[] numbers = new int[words.length];
for (int i = 0; i < numbers.length; ++i) {
numbers[i] = Integer.parseInt(words[i]);
}
// Find longest sequence in numbers array:
...
}
As other code here uses File and Scanner, I have given Path (newer alternative for File), and Files a utility class that has such nice methods like readAllLines.
Though you need no matrix, in general one does not use the typical math ordering, but line-by-line (by rows):
for (int row = 0; row < count; rows++) {
... read a line
for (int column = 0; column < 101; column++) {
numbers[row][column] = ...
System.out.print(numbers[row][column] + " ");
}
System.println();
}
I have got this program working where a number is entered and if it is to big (over 100) it ask them to re enter a number. My problem is when they enter a correct number it says number to big enter a new number. Please help:
import java.util.Scanner;
public class roomNumbers {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
System.out.print("Input a number between 1 - 75 please");
num = scnr.nextInt();
while (num < 100){
System.out.print(num);
System.out.print(" ");
num = num + 2;
}
System.out.println("Number is to high, please choose again");
main(args);
}
}
Input a number between 1 - 75 please 200
Number is to high, please choose again
Input a number between 1 - 75 please 55
55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 Number is to high, please choose again
Input a number between 1 - 75 please
How do I get it to stop once the correct answer it outputted.
I have to write a program that will print out all of the composite numbers that are less than 100. I have to use nested loops to complete this program. Also, the values must be displayed in a table with 10 numbers in each column.
I have been trying this program for over a week now, and I just am completely lost, could I have some help with this?
I did the composite number part, but how exactly do you put the numbers into columns with 10 numbers in each column? Here is the code:
import java.util.Scanner;
class SwitchStatements {
public static void main(String[]Args) {
for (int i = 0; i <= 100; i++) {
for (int j = 2; j <= i/2; j++) {
if (i % j == 0) {
System.out.println(i);
break;
}
}
}
}
}
Do you mean 10 numbers per row (ie 10 columns total), or 10 numbers per column?
Assuming you mean a "table" in the output as something that looks roughly like this (with 5 columns in this example):
1 2 3 4 5
11 12 13 14 15
then I think what you want to do is keep track of how many numbers you've printed on this line, and only use System.out.println when you've printed 10 numbers, and System.out.print otherwise:
int numbersPrinted = 0;
for (int i = 0; i <= 100; i++) {
for (int j = 2; j <= i/2; j++) {
if (i % j == 0) {
if (numbersPrinted < 9) {
System.out.print(i + " ");
numbersPrinted++;
} else {
System.out.println(i);
numbersPrinted = 0;
}
break;
}
}
}
If you want the numbers to line up neatly, you can add two spaces instead of one if i is less than 10 (and therefore is only one digit).
If you actually mean you want ten numbers per column like this (again, 5 in my example instead):
1 2
3 4
5 6
7 8
9 10
then you'll need to print (number of numbers / 10 numbers per column) columns per line, so you can't print them in your nested loop like in your example. Instead, you'll need to add them to an ArrayList or similar and print them in a separate loop later:
ArrayList<int> numbersToPrint = new ArrayList<int>();
...
if (i % j == 0) {
numbersToPrint.add(i);
break;
}
...
int numbersPerRow = (numbersToPrint.size()/10);
int numbersPrinted = 0;
for (int i : numbersToPrint) {
if (numbersPrinted < (numbersPerRow - 1)) {
...
and the rest of that is the same as my first example above.
If you really want 10 numbers in each column, check this code. It can be done with less amount of cycles, but it will be even harder to understand.
What we do here is collecting all composite numbers to list. Fill a 2-dimensional array from that list in a strange order (not row by row as usual, but column by column). And then print it in the 3rd cycle in the usual order.
public static void main(String[] args) {
List<Integer> compositeNumbers = new ArrayList<>();
for (int i = 0; i <= 100; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
compositeNumbers.add(i);
break;
}
}
}
int n = compositeNumbers.size();
int numberOfRows = 10;
int maxNumberOfColumns = (n / numberOfRows) + 1;
int[][] numbers = new int[numberOfRows][maxNumberOfColumns];
for (int j = 0; j < maxNumberOfColumns; j++) {
for (int i = 0; i < numberOfRows; i++) {
int index = i + j * numberOfRows;
if (index < n) {
numbers[i][j] = compositeNumbers.get(index);
}
}
}
for (int i = 0; i < numberOfRows; i++) {
for (int j = 0; j < maxNumberOfColumns; j++) {
if (i + j * numberOfRows < n)
System.out.print(String.format("% 3d", numbers[i][j]));
}
System.out.println();
}
}
You will get the nice output:
4 20 33 46 58 72 85 96
6 21 34 48 60 74 86 98
8 22 35 49 62 75 87 99
9 24 36 50 63 76 88 100
10 25 38 51 64 77 90
12 26 39 52 65 78 91
14 27 40 54 66 80 92
15 28 42 55 68 81 93
16 30 44 56 69 82 94
18 32 45 57 70 84 95
Edited to fix composite calculation method.
Assuming you're looking for something like this:
4 20 33 46 58 72 85 96
6 21 34 48 60 74 86 98
8 22 35 49 62 75 87 99
9 24 36 50 63 76 88 100
10 25 38 51 64 77 90
12 26 39 52 65 78 91
14 27 40 54 66 80 92
15 28 42 55 68 81 93
16 30 44 56 69 82 94
18 32 45 57 70 84 95
The first step is to divide the problem into two parts.
Generate all the composite numbers from 4 to 100.
Display all the composite numbers in columns.
You mostly did the first part. You had some errors in your for loop configuration.
You can hold all of the composite numbers in a List<Integer>.
You calculate the number of columns with this line:
int columns = (compositeNumbers.size() + columnLength - 1)
/ columnLength;
Since you have to create a full line to print it, you take the composite integer at position 0, then the composite integer at position 10 (assuming 10 numbers per column). then the composite integer at position 20, and so forth, until you have created a full line.
The last few rows may not have a number in the last column. You have to take that into account when creating a display line.
Here's the code that puts all this together. The calculateCompositeNumbers method calculates the composite numbers. The displayCompositeNumbers method displays the composite numbers in columns.
See how the method names tell you what they do.
package com.ggl.testing;
import java.util.ArrayList;
import java.util.List;
public class CompositeOutput {
public static void main(String[] Args) {
CompositeOutput compositeOutput = new CompositeOutput();
List<Integer> compositeNumbers = compositeOutput
.calculateCompositeNumbers();
System.out.println(compositeOutput.displayCompositeNumbers(
compositeNumbers, 10));
}
private List<Integer> calculateCompositeNumbers() {
List<Integer> compositeNumbers = new ArrayList<>();
for (int i = 4; i <= 100; i++) {
boolean found = false;
int maximum = Math.min(i / 2, 10);
for (int j = 2; j <= maximum && !found; j++) {
if (i % j == 0) {
compositeNumbers.add(Integer.valueOf(i));
found = true;
}
}
}
return compositeNumbers;
}
private String displayCompositeNumbers(List<Integer> compositeNumbers,
int columnLength) {
String lineSeparator = System.getProperty("line.separator");
StringBuilder builder = new StringBuilder();
int columns = (compositeNumbers.size() + columnLength - 1)
/ columnLength;
for (int row = 0; row < columnLength; row++) {
int tempIndex = row;
for (int column = 0; column < columns; column++) {
if (tempIndex < compositeNumbers.size()) {
int number = compositeNumbers.get(tempIndex);
builder.append(String.format("%6d", number));
}
tempIndex += columnLength;
}
builder.append(lineSeparator);
}
return builder.toString();
}
}
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