The given program compiles, but doesn't run the way I want it though. I think it's not applying the methods I wrote. any ideas?
import java.util.Scanner;
public class Assignment_1_q1 {
static Scanner input = new Scanner(System.in);
public static int i;
public static int counter;
public static int n;
//main method
public static void main(String[] args) {
System.out.println("Enter n's value: " );
n = input.nextInt(); //Prompts the user to input the integer number n.
int[] table = new int[10]; //Create an array of size 10.
getArrayValues(table); //Calls the first method
matchCriteria(table, counter, n); //Calls the second methods
System.out.println("There is "+ n +"numbers greater than n!" ); //display the result.
}
//the first method to input array values from the user,
//allows nonnegative numbers only to be stored into the array.
public static int[] getArrayValues(int table[]){
while (table[i] < 0)
System.out.println("Pleas try a nonnegative number!" );
for (int i = 0; table[i] < table.length; i++){
System.out.println("Enter an array value: ");
table[i] = input.nextInt();
}
return table;
}
// the second method determines how many of array values are greater than the value of n.
public static int matchCriteria(int array[], int counter, int n){
counter = 0;
for(int i = 0; i < array.length && i > n;) {
if (i > n) counter++;
}
return counter;
}
}
You need to store the result of getArrayValues() to table as such:
table = getArrayValues(table);
int newcounter = matchCriteria(table, counter, n);
On top of that, realize your for loop is using table[i] instead of i in the selection criteria. it would be better to do it in a while loop:
Consider refactoring as such:
for (int i = 0; i < table.length; i++){
System.out.println("Enter an array value: ");
table[i] = input.nextInt();
while(table[i] < 0) {
System.out.println("Pleas try a nonnegative number!" );
table[i] = input.nextInt();
}
}
Like Elliott said, you aren't really doing anything with the data from invoking the methods. You have to use that depending on what you're trying to do.
Related
I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}
I just want to add a simple where I can add an input line part by user instead of hard code defining an array. So I can just enter a couple number as a part of an array.
Here is my original code:
public class Test {
public static void main(String[] args) {
System.out.println("Largest in given array is " + max());
}
static int array[] = {10, 324, 45, 90, 9808};
// Method to find maximum in arr[]
public static int max() {
int i;
// Initialize maximum element
int max = array[0];
// Traverse array elements from second and
// compare every element with current max
for (i = 1; i < array.length; i++)
if (array[i] > max)
max = array[i];
return max;
}
}
My logic is this, tell me if I'm right or not
I need to add import java.util.Scanner; and then enter Scanner input = new Scanner(System.in);
But next part confuses me, should I change the max() into a string?
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Largest in given array is " + max(int[] array));
}
Scanner input = new Scanner(System.in);
static int array[] = {10, 324, 45, 90, 9808};
// Method to find maximum in arr[]
public static int max(int[] array) {
int x;
// Initialize maximum element
int max = array[0];
// Traverse array elements from second and
// compare every element with current max
for (x = 1; x < array.length; x++)
if (array[x] > max)
max = array[x];
return max;
}
}
I'd recommend a re-evaluation of your general design before adding user input. Using a global array variable is unnecessary and arbitrarily restricts the ability of the max function to perform work on anything other than the hard-coded global array. max should accept a parameter array to operate on; this enables reusability.
Your max function's logic seems accurate but will crash the program on empty input arrays.
When handling user input, you may want to be able to respond to variable sizes. For this, using an ArrayList is the easiest way to go.
I also recommend initializing loop counters such as i in loop scope.
Here's a possible rewrite on the way to dynamic arrays that you can use:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[] = new int[8];
for (int i = 0; i < arr.length; i++) {
System.out.print("Enter an integer: ");
arr[i] = in.nextInt();
}
System.out.println("Largest in given array is " + max(arr));
}
public static int max(int arr[]) {
if (arr.length == 0) {
return -1;
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
}
Output:
Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 6
Enter an integer: 5
Enter an integer: 3
Enter an integer: 4
Enter an integer: 1
Largest in given array is 6
I was trying to have my main method call on a non static array method. After calculating the minimum gap, that number is to be returned and printed by the main method, but nothing is happening after I enter the numbers for the array. Can someone tell me what is wrong?
public class Lab1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("How many elements would you like the array to have?");
Scanner input = new Scanner(System.in);
int arraySize = input.nextInt();
int value[] = new int[arraySize];
System.out.println("Enter numbers for the array.");
for (int i = 0; i < value.length; i++) {
value[i] = input.nextInt();
Lab1 lab1 = new Lab1();
lab1.minGap(value);
}
}
public int minGap(int[] value) {
if (value.length < 2)
return 0;
int minGap = value[1] - value[0];
for (int i = 2; i < value.length; i++) {
int gap = value[i] - value[i - 1];
if (gap < minGap)
minGap = gap;
}
return minGap;
}
}
You called the method for calculating the minimum number inside the for loop. But you will need the value returned by it. You will have to call that method and then print out the value returned by
that method.
Also you need to initialize the object outside the for loop.
This is how your main method code should look like :
public static void main(String[] args) {
System.out.println("How many elements would you like the array to have?");
Scanner input = new Scanner(System.in);
int arraySize = input.nextInt();
int value[] = new int[arraySize];
System.out.println("Enter numbers for the array.");
Lab1 lab1 = new Lab1();
for (int i = 0; i < value.length; i++) {
value[i] = input.nextInt();
}
System.out.println(lab1.minGap(value));
}
You are not ever printing your value. Output it to the console or application. It is returning but it does not become visible to end user unless you output it in some way.
System.out.println(ReturnedVal);
I need help with this program, I need to
Ask the user to input rows and column sizes using scanner
if the column size is greater than 4+5, they need to re-enter it
I need to fill all the array elements with doubles in range of 4.0, 11.0 by using random object
Find the above array and call two methods,
Method one, I need to find and print the largest sum of columns in the 2D array
Method two, I need to find the average of all elements in the array and return the average value.
Here's my code, it sort of accomplishes it, but it's also sort of messed up and I'm confused.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter row size");
int rows = input.nextInt();
System.out.println("Please enter column size");
int columns = input.nextInt();
double n = 4.0;
if (columns < n+5.0){
} else{
System.out.println("The column size is too large, please enter a smaller integer");
}
Random rand = new Random();
int[][] array = new int[rows][columns];
for(int a = 0; a<rows; a++)
for(int b = 0; b<columns; b++)
array[a][b] = rand.nextInt(11-4) + 4;
for(int i = 0; i<rows; i++){
double sum = 0;
int sum2 = 0;
for(int j = 0; j<columns; j++){
sum += array[j][i];
sum2 = sum2 + array[i][j];
System.out.println(Arrays.deepToString(array));
}
double average = sum/array.length;
System.out.println("largest sum of the columns is " + sum);
System.out.println("The average of all elements in the array is " + average);
}
}
}
You can use while loops to check if the input is even a valid integer and then if the columns count is larger than 4 + 5 ( i just assumed 9 ). I made the program flow a bit more structured and made a neat output. Basically you just would have to move the System.out.println out of the Loop like #Codebender pointed out.
package array;
import java.util.Random;
import java.util.Scanner;
public class ArrayUtil {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int columns;
int rows;
Scanner input = new Scanner(System.in);
System.out.println("Please enter row size :");
while (!input.hasNextInt()) {
System.out.println("That is not a valid Number! Try again.");
input.next();
}
rows = input.nextInt();
System.out.println("Please enter column size :");
while (!input.hasNextInt()) {
System.out.println("That is not a valid Number! Try again.");
input.next();
}
columns = input.nextInt();
while (columns > 9) {
System.out.println("The column size is too large, please enter a smaller integer!");
columns = input.nextInt();
}
Random rand = new Random();
int[][] array = new int[rows][columns];
for (int a = 0; a < rows; a++) {
for (int b = 0; b < columns; b++) {
array[a][b] = rand.nextInt(11 - 4) + 4;
}
}
for (int[] arr : array) {
StringBuilder sb = new StringBuilder();
for (int i : arr) {
sb.append("[");
sb.append(i);
sb.append("]");
}
System.out.println("Array :" + sb.toString());
System.out.println("Average : " + average(arr));
System.out.println("Max : " + max(arr));
}
}
public static double average(int[] values) {
double d = 0;
for (double value : values) {
d = value + d;
}
return (d / values.length);
}
public static double max(int[] values) {
double d = 0;
for (double value : values) {
if (value > d) {
d = value;
}
}
return d;
}
}
I am trying to create a program that sorts user inputted integers from greatest to least. Also I need to find a way to print the maximum and minimum numbers. The code was sorting fine when I had defined values but now that I have switched it to user input it sends back "0"s for some reason. This is my code
import java.util.Scanner;
public class SortInteger {
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i>number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length-1; i++){ //outputs the array to user
System.out.println(number[i]);
}
}
}
you have taken only one number
int num = input.nextInt();
and you are using it for array size :
int number [] = new int [num];
but in rest of the code you haven't taken any input so your array is empty.
Code::
import java.util.*;
class test{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int number [] = {num1,num2,num3}; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i<number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length; i++){ //outputs the array to user
System.out.println(number[i]);
}
}}
Output::
Please input three numbers
1
5
4
1
4
5
you are only initializing your array. you never initialized your array with elements, thus your array elements get default values.
System.out.println("Please enter size");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
for(int i=0; i<number.length; i++){
System.out.println("Please enter element at index " + i);
number[i] = input.nextInt()
}
As others pointed out you need to populate your array with multiple values, currently you are requesting only one int.
Also, are you sure that works? Should't your first for loop read:
for(int i = 0; i<number.length-1; i++ )
Instead of:
for(int i = 0; i>number.length-1; i++ )
On a side note, it looks to me that your sorting algorithm is O(n2) you may want to look into mergesort and quicksort.