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;
}
Related
Im not really sure why the selection sort isn't working with negative numbers and zeros in the array. It works perfectly fine with all positive integers. Feedback would be greatly appreciated.
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
}
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
Selection sort method along with the class for the project:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = 0;
do {
n = getNumDigits(in);
if (n != 0) {
int[] digits = new int[n];
getDigits(digits, in);
displayDigits(digits);
selectionSort(digits);
}
} while (n != 0);
in.close();
System.out.println("No digits to sort? Goodbye! ");
}
// Given a Scanner as input, prompts the user for the number of digits they will
// be
// entering into an array. If the number given by the user is less than 0,
// display
// an error message and ask for a number that is 0 or greater. When a valid
// number is
// received, return it to the calling program.
private static int getNumDigits(Scanner inScanner) {
int digits = 0;
do {
System.out.print("Please enter the number of digits to be stored: ");
digits = inScanner.nextInt();
if (digits < 0) {
System.out.println("ERROR! You must enter a non-negative number of digits!\n");
}
} while (digits < 0);
return digits;
}
// Given an array and a Scanner as input, prompt the user to input integers to
// fill the
// array. The procedure should display a prompt for the user to enter an
// integer, and
// should loop until the entire array is filled with integer.
private static void getDigits(int[] digits, Scanner inScanner) {
int i = 0;
while (i < digits.length) {
System.out.print("Enter integer " + i + ": ");
digits[i] = inScanner.nextInt();
i++;
}
}
// Given an array as input, displays the total number of digits contained in the
// array
// and displays the contents of the array in order, starting at index 0 and
// ending
// with the final index of the array.
private static void displayDigits(int[] digits) {
System.out.println("\nArray before sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i = 0; i < digits.length; i++) {
System.out.print(digits[i] + " ");
}
System.out.println("\n");
}
// FOR LAB10B
// Given an array of integers as input, sorts the array using the Selection Sort
// algorithm
// provided in the Closed Lab 10 write-up.
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
}
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
Thanks & I apologize for all the edits. I never use online forums.
Try doing swapping outside inner for loop :-
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
//previously u were doing swapping here
//System.out.println("inner : " + convert(digits));
}
//i shifted the swapping block to this place
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
//System.out.println("outer : " + convert(digits));
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
============
input : 4,0,-4,5,2,1,
Array after sorrting:
Number of digits in array: 6
Digits in array: -4 0 1 2 4 5
============
input : 3,4,2,5,3,21,-7,3,26,-43,-12,22,
Array after sorrting:
Number of digits in array: 12
Digits in array: -43 -12 -7 2 3 3 3 4 5 21 22 26
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 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]
The problem:
a program that updates a list of students’ grades after the end of drop period. The program should reads from the user number of students who dropped and their indexes, and then the program should copies the remaining student’s grades to new array. In addition, the program should display both the original and the updated list. [Hint: the new array must have suitable length equivalents to number of remaining students]
my code:
public class Q5{
static Scanner scan = new Scanner (System.in);
public static void main (String args[]){
double [] list={1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};
System.out.println("enter number of students who dropped:");
int num=scan.nextInt();
double [] list2 = new double [num];
System.out.println("Enter index Of the student who dropped ");
for (int j=1 ; j<=num ; j++)
{
System.out.println("student" + j + ":");
int index=scan.nextInt();
list[index]=0;
}
int j=0;
for(int i=0; i<list.length ; i++)
if (list[i]!=0)
{
list2[j]=list[i];
j++;
}
System.out.print("The original list : " );
for(int i=0; i<list.length ; i++)
System.out.print(list[i] + " " );
System.out.print("remaining students " );
for(int i=0; i<list2.length ; i++)
System.out.print(list2[i] + " " );
}
}
what is the problem ? it is not working !!!
in Line 16 it says :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q5.main(Q5.java:23)
how I can correct this
That's because of the size of your list2.
You shouldn't set its size to num, but rather to the size of the original list. Because the list2 is going to contain just as many elements as the original list. You need the num only to fetch that many inputs from the user and assign those indexes with the value 0.
double[] list2 = new double[list.length]; // This should be the size of your list2
If you don't need to keep the original size, then you need to subtract the num from the original size, as suggested by #Joetjah.
double[] list2 = new double[list.length - num]; // This should be the size of your list2
Pseudo-code:
You start of with 10 students. Say you want to drop 2 students. That means you set the list2 size to 2.
Next thing you do, is trying to add all the students (10) from list to list2. But, list2 is too small for this. Thus you get your Exception.
What you want, is this:
double [] list2 = new double [list.length - num];
Guess that problem with predefined array 'list'.
Step 1: Created the list with one of the initializing ways. Here the size is fixed.
Step 2: Took input from user : lets assume it is 11.
list doesn't need to contain the size given as input.
You initialize list2 with wrong size.
You get from the user number of dropped students and then try to put in list2 all the remaining students.
double [] list2 = new double [list.length - num];
Your code will fail if the value entered by user is out of bounds for the array :
int index=scan.nextInt();
list[index]=0; // This may fail. Value entered by the user may exceed the array length
Its working fine
import java.util.Scanner;
public class Q5 {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("enter number of students who dropped:");
int num = scan.nextInt();
double[] list2 = new double[num - 1]; // should be num-1
System.out.println("Enter index Of the student who dropped ");
for (int j = 0; j < num; j++) {
System.out.println("student" + j + ":");
int index = scan.nextInt();
list[index] = 0;
}
int j = 0;
for (int i = 0; i < num; i++) {
if (list[i] != 0) {
list2[j] = list[i];
j++;
}
}
System.out.print("The original list : ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("remaining students ");
for (int i = 0; i < list2.length; i++) {
System.out.print(list2[i] + " ");
}
}
}
output is
enter number of students who dropped:
2
Enter index Of the student who dropped
student0:
1
student1:
2
The original list : 1.0 0.0 0.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 remaining students 1.0
This will remove the exception you got. From next time you don't use static values.
Edit:
It is not a good practice to assign values to any variable by yourself. As the array is having size of 10. If user enters more than 10 students dropped then it will cause a problem.
import java.util.*;
public class Q5 {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("enter number of students who dropped:");
int num = scan.nextInt();
double[] list2 = new double[list.length-num]; // should be num-1
System.out.println("Enter index Of the student who dropped ");
for (int j = 0; j < num; j++) {
System.out.println("student" + j + ":");
int index = scan.nextInt();
list[index] = 0;
}
int j = 0;
for (int i = 0; i < list.length; i++) {
System.err.println(""+list[i]);
if (list[i] > 0) {
list2[j] = list[i];
j++;
}
}
System.out.print("The original list : ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("remaining students ");
for (int i = 0; i < list2.length; i++) {
System.out.print(list2[i] + " ");
}
}
}
A run is a sequence of adjacent repeated values . Write a program that generates a sequence of random die tosses and that prints the die values, marking only the longest run. The program should take as input the total number of die tosses (ex 10), then print:
1 6 6 3 (2 2 2 2 2) 5 2
Im quite confused on how to compare each number in order to get the correct output. Maybe using an array to store the values. Any answers or input will be of help thank you!
import java.util.Random;
import java.util.Scanner;
public class Dice
{
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
public void DiceCount()
{
int count;
int sides = 6;
int number;
System.out.println("How many die? ");
count = keyboard.nextInt();
for(int i=0; i < count; i++)
{
number = generator.nextInt(sides);
System.out.print(number);
}
}
}
First, replace int number; with int[] numbers = new int[count];. Next, replace number = ... with numbers[i] = ....
This will give you an array of random numbers (don't print them yet!). As you generate your numbers, note how many equal numbers you get in a row (add a special counter for that). Also add variable that stores the length of the longest run so far. Every time you get a number that's equal to the prior number, increment the counter; otherwise, compare the counter to the max, change the max if necessary, and set the counter to 1. When you update the max, mark the position where the run starts (you can tell from the current position and the length of the run).
Now it's time to detect the longest run: go through the numbers array, and put an opening parenthesis where the run starts. Put a closing parenthesis when you reach the end of the run, and finish the printing to complete the output for the assignment.
import java.util.Random;
import java.util.Scanner;
public class Dice {
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
public void DiceCount() {
int sides = 6;
System.out.println("How many die? ");
int count = keyboard.nextInt();
int[] array = new int[count];
int longestLength = 1, currentLength = 1, longestLengthIndex = 0, currentLengthIndex = 1;
int currentNum = -1;
for (int i = 0; i < count; i++) {
array[i] = generator.nextInt(sides);
System.out.print(array[i] + " ");
if (currentNum == array[i]) {
currentLength++;
if (currentLength > longestLength) {
longestLengthIndex = currentLengthIndex;
longestLength = currentLength;
}
} else {
currentLength = 1;
currentLengthIndex = i;
}
currentNum = array[i];
}
System.out.println();
for (int i = 0; i < count; i++)
System.out.print((i == longestLengthIndex ? "(" : "") + array[i] + (i == (longestLengthIndex + longestLength - 1) ? ") " : " "));
}
}
Note: this will only take the first longest range. So if you have 1123335666 it will do 112(333)5666.
If you need 112(333)5(666) or 1123335(666) then I leave that to you. It's very trivial.
import java.util.Random;
public class Dice {
public static void main(String[] args) {
//make rolls
Random rand = new Random();
int[] array = new int[20];
int longestRun = 1;
int currentRun = 1;
int longestRunStart = 0;
int currentRunStart = 1;
System.out.print("Generated array: \n");
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(6); //add random number
System.out.print(array[i] + " "); //print array
if (i != 0 && array[i - 1] == array[i]) {
//if new number equals last number...
currentRun++; //record current run
if (currentRun > longestRun) {
longestRunStart = currentRunStart; //set index to newest run
longestRun = currentRun; //set above record to current run
}
} else {
//if new number is different from the last number...
currentRun = 1; //reset the current run length
currentRunStart = i; //reset the current run start index
}
}
//record results
System.out.print("\nIdentifying longest run: \n");
for (int i = 0; i < longestRunStart; i++) { System.out.print(array[i] + " "); } //prints all numbers leading up to the run
System.out.print("( "); //start parentheses
for (int i = longestRunStart; i < (longestRunStart + longestRun); i++) { System.out.print(array[i] + " "); } //prints the run itself
System.out.print(") "); //end parentheses
for (int i = (longestRunStart + longestRun); i < 20; i++) { System.out.print(array[i] + " "); } //all remaining numbers
}
}```