I'm new to java. I'm trying to make my program output this [5,4] [3] [2,1] but instead I get [5,5] [4,4] [3,3] [2,2] [1,1].. what am I missing? I tried to answer it on my own but I just can't think of the answer.
Here's my full code:
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size:");
int arrSize = sc.nextInt();
System.out.println("The Size of your Array is "+ arrSize);
int arr[] = new int[arrSize];
System.out.println("Enter "+arrSize+" Elements of your Array: ");
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
}
for(int i=0; i<arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.println(" ");
for(int i=arr.length-1; i>=0;i--){
System.out.print(Arrays.asList(arr[i]+","+arr[i]));
}
}
try this code
Scanner sc=new Scanner(System.in);
System.out.print("Enter Array Size:");
int f,midd=0;
int arrSize = sc.nextInt();
System.out.println("The Size of your Array is "+ arrSize);
int arr[] = new int[arrSize];
System.out.println("Enter "+arrSize+" Elements of your Array: ");
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
}
if(arrSize%2==0){
f=0;
}
else {
f=1;
midd=(int)(arrSize/2/2)+1;
}
for(int i=arrSize-1; i>=0;){
if(f==0)
{
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
i-=2;
}
else{
if(midd==i){
System.out.print(Arrays.asList(arr[i]));
i--;
}
else {
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
i-=2;
}
}
}
provide this program inside main method
Output:
Enter Array Size:5
The Size of your Array is 5
Enter 5 Elements of your Array:
1
2
3
4
5
[5,4][3][2,1]
.
Enter Array Size:4
The Size of your Array is 4
Enter 4 Elements of your Array:
1
2
3
4
[4,3][2,1]
.
Enter Array Size:7
The Size of your Array is 7
Enter 7 Elements of your Array:
1
2
3
4
5
6
7
[7,6][5,4][3][2,1]
YOu can try the following. I think what you need is to split the array as a pair.
I am assuming you will have middle pair with one element in case of odd length and all pairs will have two elements in case of even length of the array.
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size:");
int arrSize = sc.nextInt();
System.out.println("The Size of your Array is "+ arrSize);
int arr[] = new int[arrSize];
System.out.println("Enter "+arrSize+" Elements of your Array: ");
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
}
for(int i=0; i<arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.println(" ");
int i=arr.length-1;
for(; i>arr.length/2;i-=2){
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
}
if(arr.length %2 == 0){
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
i-=2;
}else{
System.out.print(Arrays.asList(arr[i]));
i-=1;
}
for(; i>0;i-=2){
System.out.print(Arrays.asList(arr[i]+","+arr[i-1]));
}
}
Related
I use some approaches similar to the following one in Java:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a= new int[3];
//assign inputs
for (int i=0;i<3;i++)
a[i] = scan.nextInt();
scan.close();
//print inputs
for(int j=0;j<3;j++)
System.out.println(a[j]);
}
However, generally the first input parameter is length and for this reason I use an extra counter (c) in order to distinguish the first element. When using this approach, the scanner does not read inputs one by one and checking the first and other elements in two blocks seems to be redundant.
// input format: size of 3 and these elements (4, 5, 6)
// 3
// 4 5 6
public static void getInput() {
int n = 0; //size
int c = 0; //counter for distinguish the first index
int sum = 0; //
int[] array = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
//block I: check the first element (size of array) and assign it
if (scan.nextInt() <= 0)
System.out.println("n value must be greater than 0");
else {
n = scan.nextInt();
array = new int[n];
}
System.out.println("Enter array elements:");
//block II: check the other elements adn assign them
while(scan.hasNextInt() && c<n) {
if (scan.nextInt() >= 100) {
System.out.println("Array elements must be lower than 100");
} else {
array[c] = scan.nextInt();
c++;
}
}
scan.close();
int sum = 0;
for (int j = 0; j < n; j++) {
sum += array[j];
}
System.out.println("Sum = " + sum);
}
My question is "how can I modify this approach with a single block (while and for loop inside while)? I tried 5-6 different variations but none of them works properly?"
Hope this helps,
public static void getInput() {
int n; //size
int c = 0; //counter for distinguish the first index
int sum = 0; //
int[] array;
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
//check the first element (size of array) and assign it
n = scan.nextInt();
while(n <= 0)
{
System.out.println("n value must be greater than 0");
System.out.println("Enter size:");
n = scan.nextInt();
}
array = new int[n];
System.out.println("Enter array elements:");
// check the other elements and assign them
while(c<n) {
int num = scan.nextInt();
if (num >= 100) {
System.out.println("Array elements must be lower than 100");
} else {
array[c++] = num;
}
}
scan.close();
for (int j = 0; j < n; j++) {
sum += array[j];
}
System.out.println("Sum = " + sum);
}
Output:
Enter size:
-1
n value must be greater than 0
Enter size:
4
Enter array elements:
1
2
3
4
Sum = 10
I've optimized your code and fixed some bug.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
int n = scan.nextInt();
if (n <= 0) {
System.out.println("n value must be greater than 0");
return; // need to break from here
}
int c = 0;
int sum = 0; // no need for array
System.out.println("Enter array elements:");
// check the other elements and assign them
while (c++ < n) {
int next = scan.nextInt();
if (next >= 100) {
System.out.println("Array elements must be lower than 100");
c--; // ensure can reenter the number
} else {
sum += next;
}
}
scan.close();
System.out.println("Sum = " + sum);
}
I'm trying to write a simple square matrix multiplication method using multidimensional arrays.
package matrixmultiplication;
import java.util.Scanner;
public class Matrixmultiplication
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int [][] a,b,c;
int size;
System.out.print("Enter the Size of the matrix :");
size = scan.nextInt();
a=b=c=new int[size][size];
System.out.println("Enter the elements of the First matrix");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
System.out.print("Enter the element a[" + i +"]["+ j + "] : ");
a[i][j] = scan.nextInt();
}
}
System.out.println("Enter the elements of the Second matrix");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
System.out.print("Enter the element b[" + i +"]["+ j + "] : ");
b[i][j] = scan.nextInt();
}
}
System.out.println("The Product of the two matrix is : ");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
int sum = 0;
for(int k=0;k<size;k++)
{
sum +=(a[i][k] * b[k][j]);
}
c[i][j] = sum;
System.out.print(c[i][j] + "\t");
}
System.out.println();
}
}
}
When I run this program in Netbeans ,I get the following output:
Enter the Size of the matrix :2
Enter the elements of the First matrix
Enter the element a[0][0] : 1
Enter the element a[0][1] : 1
Enter the element a[1][0] : 1
Enter the element a[1][1] : 1
Enter the elements of the Second matrix
Enter the element b[0][0] : 1
Enter the element b[0][1] : 1
Enter the element b[1][0] : 1
Enter the element b[1][1] : 1
The Product of the two matrix is :
2 3
3 10
The Correct output of this program should be :
2 2
2 2
Can someone tell me what is wrong with this code.
The problem is here:
a=b=c=new int[size][size];
This creates just one array, and makes all of the variables point to it. So, updating the elements of c is also updating the elements of a and b.
Create 3 arrays instead:
a=new int[size][size];
b=new int[size][size];
c=new int[size][size];
Ideone demo
I need help creating an array that counts up to a given number. The output should look something like this:
Enter a positive integer: 8
Counting up: 1 2 3 4 5 6 7 8
Counting down: 8 7 6 5 4 3 2 1
The first 8 multiples of 5: 5 10 15 20 25 30 35 40
The first 8 multiples of 10: 10 20 30 40 50 60 70 80
Here is what I have so far:
Scanner input = new Scanner(System.in);
int[] myList = new int[1];
System.out.print("Enter a positive integer: ");
promptUser(myList);
int[] testArray = { 1, 1, 2, 3, 5, 8, 13 };
System.out.print("Test array: ");
printArray(testArray);
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
}
public static void promptUser(int[] a){
Scanner input = new Scanner(System.in);
for(int i=0; i<a.length; i++){
a[i] = input.nextInt();
}
}
public static void printArray(int[] array){
for(int i=0; i<array.length; i++)
System.out.print(array[i]);
}
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
}
Everything seems to work alright except for the last method called countingUp.
Thank you so much!
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
change this to
public static int[] countUp(int n){
int [] temp=new int[n];
for(int i=0; i<n; i++){
temp[i]=i+1;
}
return temp;
}
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
In this line change to
int[] countingUp = countUp(n);
for(int i=0;i<countingUp.length;i++){
system.out.println(countingUp[i]+" ");
}
We can start by extracting the common logic of counting by providing an initial message, the number of times to run, an initial value and an increment. Something like,
private static void count(String msg, int times, int init, int inc) {
System.out.print(msg);
for (int i = 0; i < times; i++) {
System.out.print(' ');
System.out.print(init);
init += inc;
}
System.out.println();
}
We can then implement the entirety of the requirements with something like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
System.out.flush();
do {
int num = scanner.nextInt();
count("Counting up:", num, 1, 1);
count("Counting down:", num, num, -1);
count(String.format("The first %d multiples of 5:", num), num, 5, 5);
count(String.format("The first %d multiples of 10:", num), num, 10, 10);
System.out.print("Enter a positive integer: ");
System.out.flush();
} while (scanner.hasNextInt());
}
This will produce the requested output given an input of 8, and will then prompt for more input.
First of all, If you are trying to change the Array Size Dynamically then It is NOT POSSIBLE in java Take a look # this accepted answer. I recommend you to use ARRAYLIST instead.
Although I have found below mistakes in your code. In your code I do not understand two things.
First One:
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
What is the value of n? I think it is not being initialized.
Second One:
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
What will return this function? You have not returned anything from it.
Apparently you don't need an array just follow below steps.
First create a class which handle all your calculating and counting
class SupportCounting {
public void countUp(int num) {
System.out.print("Counting up : ");
for (int i = 1; i <= num; i++) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void countDown(int num) {
System.out.print("Counting Down : ");
for (int i = num; i > 0; i--) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void printMultiple(int num, int scalefactor) {
System.out.print("First " + num + " multiples of " + scalefactor + " : ");
for (int i = 1; i <= num; i++) {
System.out.print(i * scalefactor);
System.out.print(" ");
}
System.out.println("");
}}
Then make use of that class in you main method
public class Counting {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a positive integer : ");
int n = reader.nextInt();
SupportCounting sc = new SupportCounting();
sc.countUp(n);
sc.countDown(n);
sc.printMultiple(n, 5);
sc.printMultiple(n, 10);
}}
Hope that helps
I am trying to let the user input the number of elements arrA and arrB should have and also making the user choose the int number they want for each corresponding element in both, arrA and arrB. Then, creating the third arrC with the sum of the corresponding elements in arrA and arrB and then printing arrA, arrB and arrC.
The output should look like this:
Input the length: 5
Enter a value for first array, position 0: 1
Enter a value for first array, position 1: 6
Enter a value for first array, position 2: 13
Enter a value for first array, position 3: -3
Enter a value for first array, position 4: 8
Enter a value for second array, position 0: 9
Enter a value for second array, position 1: -4
Enter a value for second array, position 2: 1
Enter a value for second array, position 3: 65
Enter a value for second array, position 4: 18
first: 1 6 13 -3 8
second: 9 -4 1 65 18
result: 10 2 14 62 26
This is the code I have written so far and I need help as to how would i use scanner to let the user choose the input length of arrA and arrB and the elements in arrA and arrB. This is what the code looks like so far :-
class ArrayArithmetic
{
public static void main ( String[] args )
{
int[] arrA = { 11, -27, 89, 17};
int[] arrB = {-3, 24, -9, -16};
int[] sum = { 0, 0, 0, 0};
for(int i = 0; i < arrA.length - 1; i++)
{
for(int j = 0; i < arrB.length - 1; i++)
{
sum[i] = arrA[i] + arrB[i];
}
}
System.out.println("sum: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );
}
}
Lets suppose you have only 2 arrays to make it easy and don't nest loops, when you understand this pieces of code you can wrap all the method with a new loop and create infinite arrays to sum to result if you want... but you have to understand the basics first:
Create a Scanner and ask user for the lenght of the arrays:
Scanner sc = new Scanner(System.in);
// ask user!
System.out.println("Input the length:");
int arrayLength = in.nextInt();
Create the arrays with given lenght
int[] fistArray = new int[arrayLength];
int[] secondArray = new int[arrayLength];
int[] totals = new int[arrayLength];
Fill fist array iterating positions from 0 to number entered by user:
for (int i = 0; i < arrayLength; i ++) {
System.out.println("Enter a value for first array, position "+ i);
try {
firstArray[i] = Integer.parseInt(sc.nextLine());
} catch (Exception e) {
System.out.println("Not a valid number!!!);
i --;
}
}
Fill second array iterating positions from 0 to number entered by user and get the sum of each pos:
for (int i = 0; i < in.nextInt(); i ++) {
System.out.println("Enter a value for second array, position "+ i);
try {
secondArray[i] = Integer.parseInt(sc.nextLine());
totals[i] = fistArray[i] + secondArray[i];
} catch (Exception e) {
System.out.println("Not a valid number!!!);
i --;
}
}
And print the results:
System.out.println(Arrays.toString(firstArray));
System.out.println(Arrays.toString(secondArray));
System.out.println(Arrays.toString(totalsArray));
Finally, don't forget to close your Scanner to avoid memory leaks as pointed drgPP so:
sc.close();
The following code should do as you wanted:
import java.util.*;
class ArrayArithmetic
{
public static void main ( String[] args )
{
Scanner in = new Scanner(System.in);
System.out.print("Input the length ");
int len = in.nextInt();
int[] arrA = new int[len];
int[] arrB = new int[len];
int[] sum = new int[len];
for (int i = 0; i < len; i++){
System.out.print("Enter a value for first array, position " + i + ": ");
arrA[i] = in.nextInt();
}
for (int i = 0; i < len; i++){
System.out.print("Enter a value for second array, position " + i + ": ");
arrB[i] = in.nextInt();
}
for(int i = 0; i < arrA.length; i++)
{
for(int j = 0; i < arrB.length; i++)
{
sum[i] = arrA[i] + arrB[i];
}
}
System.out.println("sum: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );
} }
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Length of arrays: ");
try {
//Initializing length of array
int length = sc.nextInt();
//Constructing our arrays based on length
int[] arrA = new int[length];
int[] arrB = new int[length];
int[] arrSum = new int[length];
//Populating our array A via a loop
for (int i=0; i<arrA.length; i++) {
System.out.println("Values for arrA at index: "+i);
int value = sc.nextInt();
arrA[i]=value;
}
//Populating our array B via a loop
for (int i=0; i<arrB.length; i++) {
System.out.println("Values for arrB at index: "+i);
int value = sc.nextInt();
arrB[i]=value;
}
//Call the method to calcualte our sum which will be in sum array
arrSum = makeSum(arrA, arrB, length);
System.out.println(Arrays.toString(arrSum));
} catch (Exception e) {
e.printStackTrace();
} finally {
sc.close();
}
}
// Method to calculate our Sum Array based on the length and the Array A and B
public static int[] makeSum (int[] arrA, int[] arrB, int length) {
int[] arrSum = new int[length];
for (int i=0; i<arrA.length; i++) {
for (int j=0; j<arrB.length; j++) {
arrSum[j]=arrA[i]+arrB[j];
}
}
return arrSum;
}
Perhaps this is your question:
Scanner scan = new Scanner(System.in);
System.out.println("Enter size: ");
int size =scan.nextInt();
Integer[] arrA = new Integer[size];
ArrayList<Integer> arrB = new ArrayList<Integer>(size);
I'm doing a Java activity that prints the Numbers the user Input, and here's my codes:
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
for (int x = 1; x<=num1;x++){
for (int i = 0 ; i<num1;){
System.out.print("Enter Value #" + x++ +":");
int ctr1 =Integer.parseInt(in.readLine());
i++;
}
}
How can I print all the input numbers? Here's the result of my code:
Enter How Many Inputs: 5
Enter Value #1:22
Enter Value #2:1
Enter Value #3:3
Enter Value #4:5
Enter Value #5:6
How can I print all this numbers as array. 22,1,3,5,6
Create an int[] array of length num.
On every iteration take the user input and put it in the array at their specified index and break out of the while loop. and at last print the array elements by iterating over it.
Scanner scan = new Scanner(System.in);
System.out.println("enter num of values: ");
int [] arr = new int[scan.nextInt()];
for(int i=0;i<arr.length; i++) {
scan = new Scanner(System.in);
System.out.println("please enter a value: ");
while(scan.hasNextInt()){
int x = scan.nextInt()
;
arr[i]= x;
break;
}
}
for(int i:arr){
System.out.print(i);
}
OUTPUT:
enter num of values:
5
please enter a value:
22
please enter a value:
2
please enter a value:
3
please enter a value:
5
please enter a value:
6
22
2
3
5
6
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
int arr[] = new int[num1];
for (int i = 0; i<num1; i++)
{
System.out.print("Enter Value #" + (i + 1) + ":");
arr[i] =Integer.parseInt(in.readLine());
}
I guess this should do it...
NOT TESTED
PRINTING
for(int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
SORTING
import java.util.Arrays;
Inside the code block
Arrays.sort(arr);