JAVA Creating a program using an array - java

So I have an array of 20 elements:
int[]a = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40};
The array starts from 1 and ends at 20. So everything is doubled. 1 = 2, 2 = 4, 4 =6, etc.
And I am trying to create a program that when the user selects a number say for example 30. It adds the total from place point 15 to 20. So 30 + 32 + 34 + 36 + 38 + 40).
How would I tell the program to calculate the total based on the number the user inputs?
I cannot seem to figure this out. Would I use a for statement? I'm lost. Any help would be great. I am new to Java.

You can try something likewise,
int[]array = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40};
System.out.println("Enter Your choice Number : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int index = n/2;
int sum = 0;
if(index < array.length){
for(int i = index;i<array.length;i++){
if( i > index){
System.out.print("+ ") ;
}
System.out.print(array[i]);
sum += array[i];
}
System.out.println("Answer : " + sum);
}
else{
System.out.println("InValid Value Entered, Try Again...!!");
}
Output :

public class Array {
public static void main(String[] args) {
int[]a = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40};
System.out.println("Enter the value");
Scanner s=new Scanner(System.in);
int in=s.nextInt();
int sum=0;
for(int i=0;i<a.length;i++)
{
if(in==a[i]){
for(int j=i;j<a.length;j++){
sum=a[j]+sum;
System.out.println(sum+"===="+j);
}
}
}
}

Related

Specific output pattern of array in java

I've figured out how to create an array in which the output look like this:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
if the user enters a 4 indicating a 4x4 array.
My question is how could I manipulate this code in a way that it would out put the array in this order
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
where every other row is "backwards"
`import java.util.Scanner;
import java.util.Arrays;
import java.util.Arrays;
public class Question2 {
public static void main(String[] args) {
//Title
System.out.println("[----------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[----------------------]");
System.out.println("");
//declare scanner
Scanner keyboard = new Scanner (System.in);
//Prompt user to enter a digit greater than or equal to 3
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");
//read user input
int num = keyboard.nextInt();
//place constraints on int num so that if it is less than 3, the program does not execute
while(num<3 )
{
System.out.println("Lets's try this again....");
System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
num = keyboard.nextInt();
}
//2D array with number of rows and columns entered by user
int[][] array = new int [num][num];
int inc=1;
for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
//replace all square brackets in array display & format into order
//replace all commas in array display
String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replaceAll("[\\[\\],]", "");
System.out.println(a);`
This loop will do it:
int reverse = 0;
for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
{
if(i%2 == 0){
if(j == 0){
inc = reverse;
if(i > 0 )inc = inc + num + 1;
}
array[i][j]=inc;
inc++;
}
else{
if(j == 0)reverse = inc + num - 1;
array[i][j]=reverse;
reverse--;
}
}
Every other row it place numbers in a descending order.
Also to print out the numbers with tabs between them use:
String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replace(", ", "\t").replaceAll("[\\[\\],]", "");
System.out.println(a);
This will stop a table forming diagonally.
What you could do is reverse the order of the for loop on every other line, so that it decrements instead:
for(int i=0;i<array.length;i++)
{
if(i%2 == 0){
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
}
else{
for(int j=num-1;j>=0;j--)
{
array[i][j]=inc;
inc++;
}
}
}
I don't really know how to format the columns the way you wrote the code (with Arrays.deepToString) but if you instead loop through it manually you could pad the string:
String [][]stringConvertedTable= new String[num][num];
for(int i=0; i<num; i++) {
for(int j=0; j<num; j++) {
stringConvertedTable[i][j]= Integer.toString(array[i][j]);
System.out.print(stringConvertedTable[i][j] + "\t");
}
System.out.println("");
}
It's not the most elegant way to do it though...

Loop Counting in Java

What I have is a program that prints out 4000+ random digits in the range of 1 to 99999. After printing, it shows the range, and a couple of other things, and then asks user for 5 numbers to be input and tells how many times it had to run the loop, but I'm getting an exception in main upon print, it's coming from the main for loop. Screenshot is attached. Desired should look something like:
(Randomly generated numbers):
25
192
33
(User Enters) Please enter number: 33
(System Response) It took 3 times to find the number.
If the number is not listed, as it is over 4000 integers, it will say, not found.
Here is code and screenshot:
Screenshot
Exception in Main java.lang.ArrayIndexOutOfBoundsException:0
Thank You!
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] input = new int[0];
int[] arrayone = new int[4096];
int loop = 0;
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
for(int in = 0; in<input.length; in++) {
if (arrayone[i] == input[in]) {
loop++;
}
}
}
for (int i = 0; i < 5; i++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[0] = s.nextInt();
if (min <= input[0] && input[0] <= max) {
System.out.println("It took " + loop + " time(s) to find the number " + input);
}
}
}
The problem with your input array is that you initialize it with a size of 0, so when you try to access the first location [0], you run out of the bounds since your array has a size of 0. In your answer you were also trying to determine the loops before asking the question. While doing this you were also trying go past the bounds of your input array with a size 0. What you should do is initialize your array of numbers first then for each guess loop through and determine if it's within the bounds of your max and min. Also note that just because the numbers are within the max and min doesn't guarantee the number is contained in the array because the numbers are not going to be sequential from max to min. You should check where you end up after your for-loop check for the input.
public static void main(String random[])
{
Scanner s = new Scanner(System.in);
int input = new int[5];
int[] arrayone = new int[4096];
int loop = 0;
//don't do anything here except fill the array with values
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
}
//ask the user for 5 inputs
for (int index = 0; index < input.length; index++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[index] = s.nextInt();
//check to see if the number is valid
if (min <= input[index] && input[index] <= max) {
//loop through the arrayone to determine where it is
for(int i = 0; i < arrayone.length; i++) {
//if it is not in the current index at i increment the loop count
if (arrayone[i] != input[index]) {
loop++;
}
//we have found where it is and should break out of the loop
else {
break;
}
}
//check if we found it based on how much we incremented
if(i != arrayone.length)
{
//output how long it took to find the number
System.out.println("It took " + loop + " time(s) to find the number " + input[index]);
}
else
{
System.out.println(input[index] + " not found!");
}
//now reinitialize the loop to 0 for the next guess
loop = 0;
}
}
//always remember to close your scanners
s.close();
}
}
int[] input = new int[0];
This creates an array with size of 0, so when you try save value it throws an exception because you are exceeding array size.
Solution: set valid size of array or use list.
The ArrayList is (simplifying) resizeable version of array. Use it like this:
List<Integer> input = new ArrayList<>();
input.add(5); //Adds 5 to list
input.get(0); //Read object of index 0
for(int value : list) { //Loop: for each element in list ...
System.out.println(value);
}
//Checks whether list contains 5
System.out.println(list.contains(5));
Also, do you actually need input to be an array? Because right now it looks like you don't need it at all.

Write a program that reads a set of integers and prints the sum of the even and odd integers

This is what I have so far. I am supposed to write this code with a For loop and if/else statement, but /i am stuck on how to do it properly. It would be nice if someone can tell me how to properly use a For loop and if/else statement together instead of giving the answer:
import java.util.*;
public class SumEvenOdd
{
public static void main(String []args)
{
Scanner keyboard= new Scanner(System.in);
int counter;
int i= 0;
int num=0;
int sumOdd= 0;
int sumEven= 0;
System.out.println("Enter integers other then Zero: ");
num=keyboard.nextInt();
System.out.println("The numbers you entered are: ");
for (i =num; i !=0; i=i)
{
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
i = keyboard.nextInt();
}
System.out.println("Even sum: " + sumEven);
System.out.println("Odd sum: " + sumOdd);
}
}
Your loop never executes because your loop condition is false to begin with:
for (i =num; i !=0; i=i) // i already equals 0 so i != 0 equates to false
You also aren't incrementing or decrementing with i=i so even if your condition was true you'd be stuck in an infinite loop. Use i++ to increment the value of i by 1 in each iteration of your for loop.
Also, you're only taking in one number from the user. One simple way of handling this would be to first ask the user how many numbers they want to enter first, then use that input to loop that many times asking for the numbers to sum. For example:
System.out.println("How many numbers do you want to enter? ");
num=keyboard.nextInt();
int[] addThese = new int[num]; // create an array of size num to store numbers
for(int i = 0; i < num; i++) {
System.out.print(": ");
addThese[i] = keyboard.nextInt();
}
// now use your for loop to iterate over addThese[] and find your sums
...
EDIT
You've confused yourself (and me) with your print statements and lack thereof. Your program runs fine but I don't think you're realizing it because of this.
Add something like this inside your loop so you know it's waiting for input:
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
System.out.print(": "); // <-- let the user know you're expecting more input
i = keyboard.nextInt();
You can use an array like I used above to store the user input so you actually can tell the user what numbers they entered.
In your application you do not need a for loop as you are breaking the loop as long you dont enter 0.
for loops is used to iterate through collections (for each loop) or iteratively increment a counter till it satisfies the break(classic for loop).
A do while(i!=0) loop would be more appropriate in your scenario.
If you want the answer in while loops
import java.util.*;
/*
EXPLANATION
Question: write a program that reads a set of integers and tells the sum of the even and odd numbers
First: Initialize 4 variables(all integers)
Second: Take input and print title
Third: Take a while loop that will run when i is smaller than a
Fourth: take inputs of the numbers and check for condition od or even and add the numbers
Fifth: Break the while loop if input =
*/
public class EvenOddSum
{
public static void main(String[]args)
{
//initializing variables
int InputNums = 0, OddNums = 0, EvenNums = 0, loopingVar = 0, PrintAmount;
//initializing scanner class
Scanner scanner = new Scanner(System.in);
//Input using Scanner
System.out.print("How many numbers you want to input: ");
PrintAmount = scanner.nextInt();
//Loop to execute if PrintAmount is bigger than or equal to The loop Variable
while(loopingVar <= PrintAmount)
{
//increase Loop Variable by 1 if it is smaller than PrintAmount
loopingVar++;
//The input which will be sorted into odd or even
System.out.print("Please input a number : ");
InputNums = scanner.nextInt();
//Conditional statements to Sort Input into Odd or even
if (InputNums % 2 == 0)
{
//store input numbers into OddNums var if it is not divisible by 2
OddNums = OddNums + InputNums;
}
else
{
//store input numbers into EvenNums var if it is divisible by 2
EvenNums = EvenNums + InputNums;
}
if(loopingVar == PrintAmount)
{
//If the loop variable is equal to the print amount the break will end the loop
break;
}
}
//if the condition is true the sums are printed and the code is stopped
if (loopingVar == PrintAmount)
{
System.out.println("Sum of even numbers is : " + OddNums);
System.out.println("Sum of odd numbers is : " + EvenNums);
System.exit(0);
}
//if InputNums is smaller than 0 there has been some error in the code
if (InputNums < 0)
{
System.out.print("Invalid input");
System.exit(0);
}
}
}
Scanner input = new Scanner(System.in);
int num;
int i;
int x = 0;
int y = 0;
System.out.print("How many numbers you want to input: ");
i = input.nextInt();
for (;;) {
i--;
System.out.print("Please input a number : ");
num = input.nextInt();
if (num % 2 == 0) {
x = x + num;
} else {
y = y + num;
}
if (num < 0) {
System.out.print("Inivald input");
System.exit(0);
}
if (i == 0) {
System.out.println("Sum of even numbers is : " + x);
System.out.println("Sum of odd numbers is : " + y);
System.exit(0);
}
}
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// printing the sum of even and odd number input from the user
int evensum = 0 ;
int oddsum = 0 ;
System.out.println("Enter the number:");
for(int n1= sc.nextInt(); n1>0; n1=sc.nextInt()) {
if(n1 % 2 == 0) {
evensum+=n1 ; // evensum = evensum + n1 ;
}
else {
oddsum+=n1 ; // oddsum = oddsum + n1 ;
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
// asking for continuing y or n?
System.out.println("Do you want to continue ? yes = 1 or no = 0");
int choice = sc.nextInt();
if(choice==1) {
System.out.println("Enter the number :");
}
else {
System.out.println("End");
break;
}
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
}
}

Adding the first ten odd numbers - incorrect output

I'm writing a program that adds the first ten odd numbers, and gets the sum at the end.
Here is my code so far. My code reads the odd number in a list of 10 numbers. I want my code to be able to read 10 odd numbers even if there are more than 10 numbers entered. I know the problem is i < 10, which makes the program stop after the 10th number.
import java.util.Scanner;
public class question14
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i = 0;
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
}
}
Wrap it in a while loop instead.
While oddnumbers < 10 ask for a new number.
int i = 0
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
EDIT:FULL CODE
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author stevengreen22
*/
public class NewMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int input;
int inputCount = 0;
while (i < 10){
//Having this inside the while loop prompts the user every time.
System.out.println("New number?");
input = scan.nextInt();
inputCount++;
if(input % 2 == 1){
sum += input;
i++;
}
}
System.out.println("sum: "+sum);
System.out.println("Number of odds:" + i);
System.out.println("Numbe of inputs: " +inputCount);
System.out.println("Average cos I miss typing sout tab:" + (inputCount/sum));
}
}
The principle thing is that you don't know how many numbers the user is going to enter into the program, so you want to use a while loop instead of a for loop.
One chooses a for loop when they know how many elements they want to iterate over; one chooses a while loop when they don't know how many elements they'll need to iterate over.
You'll need to define another variable called counter outside of the loop, and use this as your loop variable constraint.
while(counter < 10) {
// loop
}
You'll also need to update counter whenever you encounter an odd value.
This should work
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i=0;
while (i<10){
odd=keyboard.nextInt();
if (odd%2!=0){
sum=sum+odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is "+sum);
}
Just replace your for loop with a while loop and track the number of odd numbers in an integer:
int oddNumberCount = 0;
int inputNumber;
while(oddNumberCount<10)
{
inputNumber = keyboard.nextInt();
if(inputNumber%2!=0)
{
sum = sum+inputNumber;
oddNumberCount++;
}
}

Put a range on the input of an array in java

I am new to java programming. I would like to know if there is a way that I can fill the array with integers from the keyboard(range: 10 to 65). Here is my code:
public static void main(String[] args)
{
//Keyboard Initialization
Scanner kbin = new Scanner(System.in);
//a.Declare an array to hold 10 intgers values
int list[]=new int[10];
int i=0;
//b.Fill the array with intgers from the keyboard(range: 10 to 50).
System.out.print("\n\tInput numbers from 10 to 50: \n");
list[i]= kbin.nextInt();
if(10<=list[i] && list[i] <= 50)
{
for(i=1; i<=9;i++)
{
list [i] = kbin.nextInt();
}
}
}
please help.Thanks!
If I understand you intent properly...
You need to loop until you have 10 valid numbers. If a number entered by the user is out of range, then it needs to be discarded.
import java.util.Scanner;
public class TestStuff {
public static void main(String[] args) {
//Keyboard Initialization
Scanner kbin = new Scanner(System.in);
//a.Declare an array to hold 10 intgers values
int list[] = new int[10];
int i = 0;
System.out.print("\n\tInput numbers from 10 to 50: \n");
while (i < 10) {
//b.Fill the array with intgers from the keyboard(range: 10 to 50).
int value = kbin.nextInt();
if (value >= 10 && value <= 50) {
list[i] = value;
i++;
} else {
System.out.println("!! Bad number !!");
}
}
for (int value : list) {
System.out.println("..." + value);
}
}
}
Example output...
Input numbers from 10 to 50:
1
!! Bad number !!
2
!! Bad number !!
3
!! Bad number !!
4
!! Bad number !!
5
!! Bad number !!
6
!! Bad number !!
7
!! Bad number !!
8
!! Bad number !!
9
!! Bad number !!
10
11
12
13
14
15
16
17
18
19
...10
...11
...12
...13
...14
...15
...16
...17
...18
...19
This should fix it...
System.out.print("\n\tInput numbers from 10 to 50: \n");
for(int i=0; i<10;)
{
int k = kbin.nextInt();
if (k >= 10 && k <= 50)
{
list[i] = k;
++i;
}
}
I am not really sure what you are trying to do. But, I am guessing that you are trying to take the first 10 numbers the users enters?
One important thing to remember is that java (and other languages) uses 0 based indexing. So your for loop where i = 1, i <= 9; i++ I think that i should start at 0, but again I am not sure what you are going for here.
Though this question has been answered already but I noticed that no one provided or talked about the .hasNext() regex method so below I am providing an answer to this question using regex expression:
import java.util.Scanner;
public class Main3 {
public static void main (String [] args) {
int list [] = new int [10];
for (int i = 0; i < 10; i ++) {
Scanner sc = new Scanner (System.in);
if (sc.hasNext("([1-4][0-9])?(50)?")) {
list[i] = sc.nextInt();
} else {
System.err.println("Entered value is out of range 10 - 50. Please enter a valid number");
i --;
}
}
for (int i = 0; i < 9; i ++) {
System.out.print(list[i] + " ");
}
System.out.println(list[9]);
}
}

Categories

Resources