I'm trying to obtain specific outputs for an array. The array's been put in a while loop to continue to set up new arrays until it reaches its counter. The counter and the amount of elements in each array line up, but once I try to get my output, it doesn't work out. What should I fix to work it out?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i; int j; int n; int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while(count < n) //counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);//represents how many numbers within a line
count++;
for(j = 0; j < numbers.length; j++) //numbers within line
{
numbers[j] = input.nextInt();}
for(int p = 0; p < numbers.length - 1; p++) //prints specific values in line
{
numbers[p] = numbers[numbers.length - 1 ];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers)); }
input.close();}
} }
First User Input:
3
2
10
1
Expected Output:
10
Instead, I get 1. What I wanted to do was subtract the last element of the array from the rest of the array to get the desired output. This includes the last element as well.
code works fine, just need to close scanner outside while. Fix the brackets.
input.close(); outside while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i;
int j;
int n;
int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while (count < n) // counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);// represents how many numbers within a line
count++;
for (j = 0 ; j < numbers.length ; j++) // numbers within line
{
numbers[j] = input.nextInt();
}
for (int p = 0 ; p < numbers.length - 1 ; p++) // prints specific values in line
{
numbers[p] = numbers[numbers.length - 1];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers));
}
}
input.close();
}
output
2
Times repeated: 2
2
Length of Array: 2
1
2
2
[2, 2]
2
Length of Array: 2
1
2
2
[2, 2]
Related
I have a problem with an exercise trying to solve it. Here is the task:
Write a program that moves that rotates a list several times (the first element becomes last).
list = 1,2,3,4,5 and N = 2 -> result = 3,4,5,1,2
Note that N could be larger than the length of the list, in which case you will rotate the list several times.
list = 1,2,3,4,5 and N = 6 -> result = 2,3,4,5,1
Input
On the first line you will receive the list of numbers.
On the second line you will receive N
Output
On the only line of output, print the numbers separated by a space.
Here are the TEST:
TEST 1:
Input 5,3,2,1 2
Output 2,1,5,3
TEST 2:
Input 2,1,3,4 5
Output 1,3,4,2
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] elements = input.split(",");
int[] array = new int[elements.length];
for (int i = 0; i < elements.length; i++) {
array[i] = Integer.parseInt(elements[i]);
}
int a = scanner.nextInt();
int[] rotated = new int[elements.length];
for (int x = 0; x <= array.length - 1; x++) {
rotated[(x + a) % array.length] = array[x];
}
for (int i = 0; i < rotated.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(rotated[i]);
}
}
}
The first TEST is passed. But the second test is not passed and my program gives me wrong output: 4,2,1,3 instead of the right one: 1,3,4,2.
I cant figure it out where is the problem.
Thank you in advance for any help.
Your logic can be simplified to :
public static void shiftLeft(int shiftBy, int arr[]) {
for (int j = 0; j < shiftBy; j++) {
int a = arr[0]; // storing the first index
int i;
for (i = 0; i < arr.length - 1; i++) { // shifting the array left
arr[i] = arr[i + 1];
}
arr[i] = a; // placing first index at the end
}
}
Now call it :
public static void main(String[] args) {
// Fetch all data from user as you have done
int arr[] = { 1, 2, 3, 4, 5 };
shiftLeft(n % arr.length, arr);
// print out the array
}
Notice that if the number n is greater than the length of the array, you don't have to actually shift it that many times. Instead you just need to shift it n % arr.length times.
Refreshing my Java, With 2 numbers as user input , I'm trying to display all numbers in between. My code works using different types, likse strings, String builder and using Java8. But somehow, the Array part does not work..
Here is my code..
System.out.println("Enter the first number :");
Scanner key = new Scanner(System.in);
int num1 = key.nextInt();
int num2 =0;
System.out.println("Enter the Second number :");
try{
num2 = key.nextInt();
do {
if (num2 < num1) {
System.out.println("Second number " + num2 + " is less than " + num1);
System.out.println("Enter the Second number :");
num2 = key.nextInt();
}
} while(num2 <num1);
}
catch (ArithmeticException e) {
if (num2 <num1)
{
System.out.println("Second number " +num2 + "cannot be less than " + num1);
}
}
int length = (num2 - num1) +1;
int [] numOfIntegers = new int [length];
System.out.println("Now the length of numOfInteger is : " + numOfIntegers.length);
// TimeUnit.SECONDS.sleep(2);
//int counter = num1;
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
RESULT is like this :
Numbers within 2 and 8 Using an Array is [0, 0, 2, 3, 4, 5, 6]
What am I doing wrong..
Java 8 allows to do that in one line with IntStream
DOCUMENTATION
public static void main(String[] args) {
int[] a = IntStream.range(num1, num2+1).toArray();
for(int aa:a)
{
System.out.println(aa);
}
}
EXAMPLE: If you Substitute Num1= 2 and Num2=8 , Output Will be 2 3 4 5 6 7 8
When you fill your array, you start at index num1. You should start at index 0. That is
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
should be
for(int i=0; i < length; i++)
{
numOfIntegers[i] = num1 + i;
}
You need to add an variable to loop the array index from 0 th position to array length. Since your for loop first point to an index in the middle. i.e. here it is 2 and it goes forward up to array length. You could change it as below.
for ( int i = num1, k = 0; k < length; i++ )
{
numOfInteger[k++] = i;
}
Here in this loop:
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
You start adding at index num1, which is why the first couple slots in your Array are still your default value. You want to start the index at zero:
for(int i = num1, j = 0; j < length; i++) {
numOfInteger[j++] = i;
}
Which will produce:
[2, 3, 4, 5, 6, 7, 8]
In the final loop:
for(int i = num1 ; i < length; i++)
{
numOfIntegers[i] = i ;
}
You are basically counting from num1 to length i.e the loop counter is being assigned values (2,3,4,5,6) and 0,1 positions of the array are being left out with 0 as default values.
Adjust the loop to iterate from 0 to length like below:
for(int i = 0 ; i < length ; i++)
{
numOfIntegers[i] = num1 + i;
}
It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.
I am trying to write a program that sums up the total of two large numbers. I used two arrays for the numbers to sum up and the third array to store the result of the summation, But I am getting the wrong output, would you check?
Here is my method:
public static int [] sumBigInt(int [] A, int [] B, int n)
{
int sumPerCol = 0;
int carriedValue = 0;
int[] totalArray = new int[A.length + 1];
for(int i = A.length - 1; i >= 0; i--)
{
sumPerCol = A[i] + B[i] + carriedValue;
if( i == 0)
totalArray[i] = carriedValue;
else if(sumPerCol >= 10)
{
carriedValue = sumPerCol / 10;
totalArray[i] = sumPerCol % 10;
}
else
{
totalArray[i] = sumPerCol;
carriedValue = 0;
}
}// end of for-Loop
return totalArray;
}
**** In main, I am not getting the correct output:
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(TwoTo_n(8));
int[] arrayA = {6,9,4,6,9,1,8,9,3,5,6};
int[] arrayB = {5,9,6,4,3,1,6,7,6,9,5};
int[] arrayTest = new int[arrayA.length + 1];
for (int i = 0; i < arrayTest.length; i++)
arrayTest[i] = sumBigInt(arrayA, arrayB, 14)[i];
for (int i = 0; i < arrayTest.length; i++)
System.out.print(arrayTest[i] + " ");
}
Here is the output I get :
1 9 1 1 2 3 5 7 0 5 1 0
The output should be:
1 2 9 1 1 2 3 5 7 0 5 1 => now the digit in position 1 disappears :(
There is ONE digit missing; that digit should be added at position zero in my final array, but its not showing up.
Thank you
Your code is almost correct. In order to fix it, think what happens to carriedValue after you finish the loop:
When the loop ends, and carriedValue is zero, your program returns the correct value
When the loop ends, and carriedValue is one, the most significant digit of the result gets dropped.
All you need to do to fix this is to "shift" digit positions in your totalArray by one, and assign carriedValue to the top digit after the end of the loop:
for(int i = A.length - 1; i >= 0; i--) {
sumPerCol = A[i] + B[i] + carriedValue;
if(sumPerCol >= 10) {
carriedValue = sumPerCol / 10;
totalArray[i+1] = sumPerCol % 10;
} else {
totalArray[i+1] = sumPerCol;
carriedValue = 0;
}
}// end of for-Loop
totalArray[0] = carriedValue;
Note the use of totalArray[i+1] in place of totalArray[i]. This is because your method automatically extends the number of significant digits by one. You could change this behavior by re-allocating the array and copying data into it only when carriedValue is non-zero.
Demo.
So close to having this program working but I'm stuck.
What I want it to do is simply print out the numbers that have actual occurrences,
so if the user inputs : 1, 2, 3, 2, 6
It needs to display
1 - 1 times
2 - 2 times
3 - 1 times
6 - 1 times
What I'm actually getting with the same input is something like:
1 - 1 times
2 - 2 times
3 - 1 times
4 - 0 times
5 - 0 times
6 - 1 times
I need to remove the case where there are no occurrences.
import java.util.Arrays;
import java.util.Scanner;
public class CountOccurrences
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
//Create Array for numbers
int numbers[] = new int[100];
//Prompt user input
System.out.println("Enter integers between 1 and 100: ");
//For loop to continue input
for (int i = 0; i < numbers.length; i++) {
int next = input.nextInt();
//Breaks loop if 0 is inputted
if (next==0)
{
break;
}
numbers[i] = next;
}
//Calls on countInts method
int[] count = countInts(numbers);
//Calls on display counts
displayIntCount(count);
}
//Counts each instance of a integer
public static int[] countInts(int[] ints)
{
int[] counts = new int[100];
for(int i = 1; i <=counts.length; i++)
for(int j=0;j<ints.length;j++)
if(ints[j] == i)
counts[i-1]++;
return counts;
}
//Displays counts of each integer
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++)
System.out.println((i+1) +" - " +counts[i] +" Times");
}
}
Just use a simple if statement to check if counts[i] is not 0, like this:
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println((i+1) +" - " +counts[i] + " Times");
}
}
}