I'm so stuck of how to get the answer below, this question required to use the ArrayList and recursion as well. Code below is what I've got so far, and now I'm so stuck. I've done a lot of research but still not find the answer. If you can, you can explain and provide some answer, THANK YOU.
The elements of your array are: 1 2 3 4 5 6 -1
The multiplication of {1, 2, 3, 4, 5, 6} is 720.
Also, if the user enters the negative number, the ArrayList won't multiply that number. Please help.
public class Arraylist{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("The elements of your array are: ");
int num = scan.nextInt();
ArrayList<Integer> element = new ArrayList<Integer>();
while (true){
element.add(scan.nextInt());
}
}
}
Considering negative value terminate loop
Scanner scan = new Scanner(System.in);
System.out.print("The elements of your array are: ");
ArrayList<Integer> element = new ArrayList<Integer>();
int ans = 1;
while (true){
int num = scan.nextInt();
if(num < 0)
break;
element.add(num);
ans *= num;
}
System.out.println(ans);
Define a recursive function to get the product.
public class Arraylist{
public static int getProduct(ArrayList<Integer> elements, int index) {
if(index == elements.size() ) return 1;
else
return (elements.get(index) > 0)?
elements.get(index): 1 *
getProduct(elements, i+1);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements:");
int num = scan.nextInt(), prod = 1;
ArrayList<Integer> elements = new ArrayList<Integer>();
System.out.println("Enter " + num + " elements:");
for(int i = 0; i < num; i++) {
elements.add(scan.nextInt());
}
prod = getProduct(elements);
System.out.println("Product is: " + prod);
}
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 am creating this code where I am supposed to prompt the user for a maximum of 5 integer numbers. I should store the 5 integers in an array by asking the user to enter them until the array is full or the user exits by entering -99. Then I should print out all the values of the array and calculate the average. The problem is that when I scan and store the values it shows me a null value of 0 of the fifth number instead of the number itself and it does not count it with the sum. This is the piece of code I've been working with:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num==-99 || i==4){
for(int k=0; k<i+1; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/i);
cond = true;
}
number[i] = num;
i++;
}while(!cond);
}
This is the input : 1 2 3 4 5
Every number is on a separate line
This is the output:
run:
1
2
3
4
5
1
2
3
4
0
2.5
number[i] = num;
is what adds the number the user entered to the array. If they enter -99, it's in the correct place. If they've simply entered all 4 however, it is in the wrong place. Also, you have it so it is actually dividing by the wrong number. Something like this should work:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num!=-99){
number[i] = num;
i++;
}
if(num==-99 || i==5){
for(int k=0; k<i; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/(i));
cond = true;
}
}while(!cond);
}
Also, do while loops are really ugly, and you can do it much smoother with just two for loops:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] number = new int[5];
double sum = 0;
int num=0,i;
for(i=0;i<5&&num!=-99;i++){
num = scan.nextInt();
number[i] = num;
}
for(int k=0;k<i;k++){
System.out.println(number[k]);
sum+=number[k];
}
System.out.println(sum/(i+1));
}
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
before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.
How do I take in input from a user from a scanner, then put that input into a 2D Array. This is what I have but I dont think it is right:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [][] a = new int[row][col];
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers: ");
while (in.hasNextInt())
{
int a[][] = in.nextInt();
a [row][col] = temp;
temp = scan.nextInt();
}
Square.check(temp);
}
What I am trying to do is create a 2D array and create a magic Square. I have the boolean part figured out, I just need help with inputting users sequence of numbers into the array so the boolean methods can test the numbers. All help greatly appreciated
I don't believe your code will work how you want it to. If I'm understanding your question correctly, here's what I would do:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int [][] a = new int[row][col];
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
System.out.print("Enter integer for row " + i + " col " + j + ": ");
a[i][j] = in.nextInt();
}
}
// Create your square here with the array
}
In the loops, i is the current row number and j is the current column number. It will ask the user for every row/column combination.
You can use that in order to enter all number at the same time :
int [][] a = new int[3][3];
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers: ");
int row=0,col=0;
while (in.hasNextInt())
{
a [row][col++] = in.nextInt();
if(col>=3){
col=0;
row++;
}
if(row>=3)break;
}
Then you can enter :
1 2 3 4 5 6 7 8 9
to fill your array.