error in the number stored in the array java - java

While I was writing the code, I had to print out total 25 numbers, so I put the number 25 inside the numberArray, however when I run the program, it dd not print out 25 numbers. Instead the number of the random numbers kept changing and did not stick to the specific value. What should I do in this case to make my code print out 25 numbers?
public static void printArray(int[] ear) {
System.out.println("ODD NUMBERS : ");
for (int e = 0; e<ear.length ; e ++) {
ear[e] = (int)(Math.random()* 100);
if(ear[e]%2!=0)
System.out.print(ear[e] + " ");
}
System.out.println("\n" + "EVEN NUMBERS : ");
for (int e = 0; e<ear.length ; e ++) {
ear[e] = (int)(Math.random()* 100);
if(ear[e]%2==0)
System.out.print(ear[e] + " ");
}
}
public static void main(String[] args) {
int[] numberArray = new int[25];
printArray(numberArray);
}
}

As stated in the code, you are only printing the ODD and EVEN numbers of the array. That's why you get different outcomes on each run.
If you change the code to print the array index instead of the value you can see that you are printing
ODD NUMBERS :
4 10 12 13 14 15 18 19 22 23 24
EVEN NUMBERS :
0 1 3 4 5 6 9 13 16 17 18 19 20 22 23

Related

Java For Loop Repeating Sequence Triangle Program

Can someone help me write the program in Java that prints the following triangle? I'm having trouble coming up with a solution.
Example User input:
Enter increment amount: 5
Enter number of terms in sequence: 7
The number of rows is always set at 10.
What I have written so far:
import java.util.Scanner;
public class Drawtriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter increment amount:");
int incAmt=scanner.nextInt();
System.out.print("Enter number of terms in the sequence:");
int numOfTerms=scanner.nextInt();
int number=1;
for(int row=1; row<=10;row++) {
for(int col=1; col<=row; col++) {
System.out.print(number);
}
System.out.println();
}
scanner.close();
}
}
Output:
1
6 11
16 21 26
31 1 6 11
16 21 26 31 1
6 11 16 21 26 31
16 11 16 21 26 31 1
6 11 16 21 26 31 1 6
11 16 21 26 31 1 6 11 16
21 26 31 1 6 11 16 21 26 31
The triangle is simply a triangle where the next number is greater by +5 than the previous number. So we need to increment number by 5 each time something is printed out of the loop.
In your code, you took number = 1 before entering the loop, but then didn't mention any changes it must go through in order to print this triangle.
Mistake number 1 in the code
Now the output also has one error. In the 7th line of output you posted the first value the inner loop will print is 16. This is not true as, after printing 31, the loop will start again from 1 and increment by 5 again. I think there was a space between 1 and 6 of 16 in the 7th line. Here is the solution with just minor changes that I've come up with:
import java.util.Scanner;
public class Drawtriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter increment amount:");
int incAmt=scanner.nextInt();
System.out.print("Enter number of terms in the sequence:");
int numOfTerms=scanner.nextInt();
int number=1;
for(int row=1; row<=10;row++) {
for(int col=1; col<=row; col++) {
System.out.print(number+" ");
number = number + 5 ;
if(number>31){
number = 1;
}
}
System.out.println();
}
scanner.close();
}
}
The output is also here:
CORRECT OUTPUT IN ACCORDANCE WITH THE CORERCTLOGIC
Hope you can are able to solve this now. I took the same inputs given at the start to avoid any problems. Anyways, All the best.
Simple logic to print the pattern using for loop
import java.util.Scanner;
public class DrawTriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
var out = System.out;
System.out.print("Enter increment amount:");
int incAmt=scanner.nextInt();
System.out.print("Enter number of terms in the sequence:");
int numOfTerms=scanner.nextInt();
int number=1;
int count = 0;
for(int row=0; row<10;row++) {
for(int col = 0;col<=row;col++){
out.print(number+" ");
number += incAmt;
count ++;
if(count>=numOfTerms){
number = 1;//initialising number with 1 if number of terms it has reached
count = 0;//resetting counter
}
}
out.println();
}
scanner.close();
}
}
Output:
$ javac DrawTriangle.java && java DrawTriangle
Enter increment amount:5
Enter number of terms in the sequence:7
1
6 11
16 21 26
31 1 6 11
16 21 26 31 1
6 11 16 21 26 31
1 6 11 16 21 26 31
1 6 11 16 21 26 31 1
6 11 16 21 26 31 1 6 11
16 21 26 31 1 6 11 16 21 26

How can i determine the formula for determining the first number in Java's loop array for floyd's triangle?

Hi so i have java loop problem.
So i'm trying to figure out how to determine the first number(in the top of the pattern) in the loop for floyd's triangle by entering the height on the triangle.
Note: only the height is to be inputted to determine the first number and the last number should be fixed to 1.
for example:
Enter the height: 5
The first number is: 15
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
Another one is
Enter the height: 6
The first number is: 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
I've figured out how to do the pattern and the decrementing of the value but i cant seem to figure out the first number. I've been trying to figure out the sequence but it's still confusing to me because i'm still new at java.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int startingnumber = ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
System.out.print("The first number is "+startingnumber);
for(int i =1; i<=n; i++){
for(int j =1; j<=i; j++){
System.out.print(startingnumber);
startingnumber--;
}
System.out.println();
}
}
}
The code is still not finished because i cant figure out the formula :(
I would appreciate any help that i can find. Thanks!
This mathematical problem is Triangular number and here is a visual demonstration
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n
=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
An also have a look at System.out.printf
public static void main(String[] args) {
int n;
int startingnumber;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
startingnumber = n * (n + 1) / 2;
System.out.println("The first number is " + startingnumber);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d ", startingnumber);
startingnumber--;
}
System.out.println();
}
}
Output
Enter the height of the triangle: 6
The first number is 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
The way you solve that type of question is by finding a mathematical relationship. In this case, you know (when input's 6) that the height's 6. You also know that at each row, you have one less number than at the one that goes after it. The bottom one has 6, as its the same as the height.
Therefore, you need to do 6+5+4+3+2+1 to obtain the starting number.
Now that formulated as a generic solution: n+(n-1)+((n-1)-1)..+1.
A possible implementation for that is:
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
int startingNumber = 0;
for (int i=n;i>0;i--) startingNumber+=i;

Putting values from file separated by space into multi dimension array

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();
}

Java: incrementally shifting elements in a 2D array to the right

I am trying to shift elements in a 2D array (specifically a square matrix) so that the result is a "staircase" pattern:
Original:
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
Objective:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
I've managed to write a program that can perform the task in a 1D array for the first line of the matrix (see below), but I can't seem to translate the code so that it functions in a 2D array.
How do I get my code to function in a 2D array in Java?
And, for later, how would I go about incrementing the change so that, as the row increases (from upper to lower levels of the matrix), the number of shifts also increases?
public class StaircaseMatrix
{
public static void main(String[] args)
{
int[] num = {1,2,3,4,5};
shiftRight(num);
System.out.println("After shifting the array is:");
for (int x = 0; x < num.length; x++)
System.out.print(num[x] + " ");
}
public static void shiftRight(int[] list)
{
int last = list[list.length - 1];
for (int j = list.length - 1; j > 0; j--) {
list[j] = list[j - 1];
}
list[0] = last;
}
}
You call shiftRight() 0 times for array2D[0], 1 time for array2D[1], 2 times for array2D[2], and so on, using a for loop.

Triangular Multiplication Table

I'm new to Java. I'm trying to make a triangular multiplication table that looks somewhat like this:
Enter # of rows 7
1 2 3 4 5 6 7
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
Each row/column has to be numbered, and I have no idea how to do this. My code is seemingly waaay off, as I get an infinite loop that doesn't contain the correct values. Below you will find my code.
public class Prog166g
{
public static void main(String args[])
{
int userInput, num = 1, c, d;
Scanner in = new Scanner(System.in);
System.out.print("Enter # of rows "); // user will enter number that will define output's parameters
userInput = in.nextInt();
boolean quit = true;
while(quit)
{
if (userInput > 9)
{
break;
}
else
{
for ( c = 1 ; c <= userInput ; c++ )
{ System.out.println(userInput*c);
for (d = 1; d <= c; d++) // nested loop required to format numbers and "triangle" shape
{
System.out.print(EasyFormat.format(num,5,0));
}
}
}
}
quit = false;
}
}
EasyFormat refers to an external file that's supposed to format the chart correctly, so ignore that. If someone could please point me in the right direction as far as fixing my existing code and adding code to number the columns and rows, that would be greatly appreciated!
Two nested for loops will do the trick:
for (int i = 1; i < 8; i++) {
System.out.printf("%d\t", i);
}
System.out.println();
for (int i = 1; i < 8; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%d\t", i * j);
}
System.out.println();
}
OUTPUT
1 2 3 4 5 6 7
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49

Categories

Resources