partially filled arrays program terminates early runtime - java

Trying to make a program that uses a partially filled array. The beginning of the code deals with getting user input for the array size and getting them to enter a value to be placed in the array. Then I want the values to be sorted as they are entered.
public static void main(String[] args)
{
int userInput;
int[] userArray;
int numElements;
int index;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of values in array (5 to 10): ");
userInput = keyboard.nextInt();
while (userInput < 5 || userInput > 10)
{
System.out.print("Enter number of values in array (5 to 10): ");
userInput = keyboard.nextInt();
}
System.out.println(); //Space, for neatness
userArray = new int[userInput];
for (int item: userArray)
System.out.print(item + " ");
System.out.print("\nEnter an integer value: ");
userInput = keyboard.nextInt();
int numElements = 0;
int index = 0;
if (numElements == userArray.length - 1)
System.out.println("The array is full.");
else
{
while (index < numElements && userArray[index] < userInput)
{
if (userArray[index] != 0) //Shift the array to the right, and add value at the current index as to not overwrite values.
{
for (int i = numElements; i > index; i--)
userArray[i] = userArray[i - 1];
userArray[index] = userInput;
}
userArray[index] = userInput;
index++;
numElements++;
System.out.print("Updated array: ");
for (int item: userArray)
System.out.print(item + " ");
System.out.println("\nEnter an integer value: ");
userInput = keyboard.nextInt();
}
}
}
Having trouble with my output. After I enter a value, the program terminates. For example (I print the empty array on purpose):
Enter number of values in array (5 to 10): 5
0 0 0 0 0
Enter an integer value: 5
Sorry for the lack of comments.

This part of your statement is always FALSE!
index < numElements
index and numElements are both 0 initially. Thus your while loop just skips and is done.

try replacing the last part of your code by this :
int numElements = 0;
while (numElements < userArray.length ) {
System.out.print("\nEnter an integer value: ");
userInput = keyboard.nextInt();
//insert into the first column
userArray[0] = userInput;
// order the table
for (int i=0 ;i<=(userArray.length-2);i++)
for (int j=(userArray.length-1);i < j;j--)
if (userArray[j] < userArray[j-1])
{
int x=userArray[j-1];
userArray[j-1]=userArray[j];
userArray[j]=x;
}
numElements++;
}
System.out.print("Updated array: ");
for (int item: userArray)
System.out.print(item + " ");
System.out.println("\nEnter an integer value: ");
userInput = keyboard.nextInt();
System.out.println("The array is full.");

Related

How to show only occurrences of numbers user input in java?

I'm new to programing and trying to solve this problem, but have no idea what I did wrong.
The program is supposed to take user input until 0 is entered and after that, print out information of occurrences of numbers user input - and here is my problem.
The program I wrote shows occurrences of all numbers (up to max number that can be input), not only those that user wrote.
My code:
package numbers;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] occurences = new int[11];
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occurences[num]++;
num = scan.nextInt();
}
for (int i = 0; i < 11; i++) {
System.out.print("Value: " + i + " Occurences: " + occurences[i] + " ");
}
}
}
Use if statement to print only numbers with occurences higher than 0.
Side notes:
Array values initialization is not needed:
for (int i = 0; i < 11; i++) {
occurences[i] = 0;
}
Value at each index is already 0, check this question.
While loop condition, does not make much sense
while (num > 0 && num <= 11) {
occurences[num]++;
num = scan.nextInt();
}
Array size is 11, meaning indexes range from 0 to 10 inclusive. Since you allow input 11, you will get ArrayIndexOutOfBoundsException.
You can make use of map.
Map<Integer, Integer> occ = new HashMap<>();
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occ.put(num, occ.getOrDefault(num, 0)+1);
num = scan.nextInt();
}
for(int i : occ.keySet()){
System.out.print("Value: " + i + " Occurences: " + occ.get(i) + " ");
}

Java program not producing correct result

I am trying to write a program that takes a set of 10 numbers from the user, finds the smallest and largest value within the set, and displays it to the user. I kind of got the program to work but I am experiencing an issue. It looks like it skips through the first number and assigns the second number to be the smallest value. In class we haven't gotten to arrays yet so, I have to assume that the first value entered in the smallest and largest value Here's what I have:
int smallestValue;
int largestValue;
int numInput;
int counter = 1;
int numSets = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a set of 10 numbers: ");
numInput = input.nextInt();
smallestValue = input.nextInt();
largestValue = input.nextInt();
counter++;
while (counter != 9)
{
numInput = input.nextInt();
counter++;
if (numInput > largestValue)
{
largestValue = numInput;
}
else if (numInput < smallestValue )
{
smallestValue = numInput;
}
}
System.out.println( "Smallest is " + smallestValue );
System.out.println("Largest is " + largestValue);
Thanks in advance!
It skips value because you call input.nextInt() before the loop, you don't need to, and use Integer.MAX_VALUE and Integer.MIN_VALUE to initialize the min and max. Also when you iterate depending on a counter, it's commonly with a for loop
int numInput;
int smallestValue = Integer.MAX_VALUE;
int largestValue = Integer.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.print("Enter a set of 10 numbers: ");
for(int i=0; i<10; i++){
numInput = input.nextInt();
if (numInput > largestValue){
largestValue = numInput;
}else if (numInput < smallestValue ){
smallestValue = numInput;
}
}
System.out.println( "Smallest is " + smallestValue );
System.out.println("Largest is " + largestValue);

How can I fix my loop to stop when i enter number less than 1 and greater than 50 and to stop when more than 20 inputs?

I need the code to stop if the user enters a number less than 1 or greater than 50. I have written what is below so far. The loop also goes in an infinite loop and I need it to stop after 20 inputs. Any suggestions?
KeyboardReader reader = new KeyboardReader();
Ex4Method object = new Ex4Method();
int occurences [] = new int [51];
int [] nums = new int[20];
int i=0;
System.out.println("Enter a number (1-50): ");
nums[i] = reader.readInt();
while(nums[i]>= 1 && nums[i]<=50)
{
while(i<19)
{
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
}
Change while(nums[i]>= 1 && nums[i]<=50) with while(nums[i]>= 1 && nums[i]<=50 && i<19), put i++ inside the loop and remove the while(i<19) loop.
Sample:
KeyboardReader reader = new KeyboardReader();
Ex4Method object = new Ex4Method();
int occurences [] = new int [51];
int [] nums = new int[20];
int i=0;
System.out.println("Enter a number (1-50): ");
nums[i] = reader.readInt();
while(nums[i]>= 1 && nums[i]<=50 && i<19)
{
i++;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
}
you can code like this .
while(nums[i]>= 1&&nums[i]<50&&i<20)
{
i++;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
}

asking a user to reenter data in a 2d array - java

Good afternoon,
I'm writing a program that asks a user to enter two numbers into a 2d array. The 1st number needs to be between 1 and 20 and the second number needs to be between 1 and 5.
I've written the part to take the input from the user
import java.util.Scanner;
public class store {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[][] maxtrix = new double[4][2];
for (int i = 0; i < maxtrix.length; i++) {
System.out.print("Enter the amount of apples (1-20) and oranges (1-5) for bag " + (i+1) + ": ");
for (int j = 0; j < maxtrix[i].length; j++) {
maxtrix[i][j] = input.nextDouble();
}
}
The question I have is what would be the best way to ask the user to reenter the data if they are outside the given ranges. I have used a do while before to ask a user to reenter if they input is outside the range but can't seem to figure it out within a 2d array.
Thanks for any tips or hints in advance.
Try this... I intentionally kept 2 nested loops as you did. You can also enter apples and oranges separately to simplify this.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[][] maxtrix = new double[4][2];
boolean areApplesEntered = false, areOrangesEntered = false;
for (int i = 0; i < maxtrix.length; i++) {
areApplesEntered = false;
areOrangesEntered = false;
for (int j = 0; j < maxtrix[i].length; j++) {
double apples, oranges;
if (areApplesEntered == false) {
do {
System.out.println("Enter the # of apples between 1 and 20 for the bag ["+(i+1) +"] -->");
apples = input.nextDouble();
} while (apples < 1 || apples > 20);
maxtrix[i][j] = apples;
areApplesEntered = true;
} else {
do {
System.out.println("Enter the # of oranges between 1 and 5 for the bag ["+(i+1)+"] -->");
oranges = input.nextDouble();
} while (oranges < 1 || oranges > 5);
maxtrix[i][j] = oranges;
areOrangesEntered = true;
}
}
}
}
You might want to set up some while loops to check for your conditions:
System.out.println("Please enter the number of apples (from 1 to 20): ");
while (input.hasNextDouble()) {
double temp = input.nextDouble();
if (temp < 1 || temp > 20) {
System.out.println("\nThe number of apples must be a number in [1..20]. \nPlease enter a valid amount: ");
continue;
}
else {
matrix[0][0] = temp;
break;
}
}
System.out.println("Please enter the number of oranges (from 1 to 5): ");
while (input.hasNextDouble()) {
double temp = input.nextDouble();
if (temp < 1 || temp > 5) {
System.out.println("\nThe number of oranges must be a number in [1..5]. \nPlease enter a valid amount: ");
continue;
}
else {
matrix[0][1] = temp;
break;
}
}
I am assuming by your post that you are just entering two numbers total..

How do I add an evaluated scan object into an array?

I want to scan 20 integers from the user. Once the user enters a negative value, the scan stops.
After that, how can I add the positive values that the user entered into an array?
System.out.println("\nEnter up to 20 non-negative numbers:");
for(i = 0; i <= list20.length; i++) {
System.out.print("Number " + (i+1) + ": ");
input = scan.nextInt();
if(input > 0) {
input = input.list20[i] // How to add positive integer here??
}
else
break;
}
// first, zero out the array using whatever method you want
for(i = 0; i < list20.length; i++)
{
list20[i] = 0;
}
// then request the values
System.out.println("\nEnter up to 20 non-negative numbers:");
for(i = 0; i < list20.length; i++)
{
System.out.print("Number "+ (i+1) + ": ");
input = scan.nextInt();
if(input>=0)
{
list20[i] = input;
}
else
{
break;
}
}
// then total the non-negative values
int total = 0;
if(i >= 20) {
for(int value : list20)
{
if(value > 0) {
total += value;
}
}
}

Categories