package com.company;
import java.util.*;
public class Main {
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
for (int i = 0; i <= 5; i++) {
if (array[i] > largest) {
array[i] = largest;
}
System.out.println(largest);
}
return largest;
}
public static void main(String[] args) {
// write your code here
Scanner sc = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i <= 5; i++) {
array[i] = sc.nextInt();
System.out.println(array[i]);
}
Largest(array);
System.out.println("largest element is : "+Largest(array));
}
}
This is the code to find the largest no. in an array but the output I'm getting for this code isn't desirable. Please check and let me know the problems in this code.
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
//for (int i = 0; i <= 5; i++) {
//wrong loop range
for (int i = 0; i < array.length; i++) {
if (array[i] > largest) {
//array[i] = largest;
//wrong assignment
largest = array[i];
}
System.out.println(largest);
}
return largest;
}
Try like this :
package com.company;
import java.util.*;
public class Main {
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 5; i++) {
if (array[i] > largest) {
largest = array[i];
}
System.out.println(largest);
}
return largest;
}
public static void main(String[] args) {
// write your code here
Scanner sc = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i < 5; i++) {
array[i] = sc.nextInt();
System.out.println(array[i]);
}
Largest(array);
System.out.println("largest element is : "+Largest(array));
}
}
You are wrong on two thing :
the loops on your array go until index = 5, however your array has a length of 5, so the last index is 4.
you were assigning array[i] = largest instead of largest = array[i]
Related
Why do Min & Max show up as 0 in this array?
I tried to figure it out for a while now but I couldn't wrap my head around it.
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int []x=new int[n-1];
random(x);
sizeArray(x);
System.out.println("The min is "+ min(x));
System.out.println("The max is "+ max(x));
System.out.println("The Total is "+ getTotal(x));
}
public static int random(int[]x){
Random rand=new Random();
for (int i = 0; i < x.length; i++) {
x[i]=rand.nextInt(101);
}
return 0;
}
public static int sizeArray(int []x){
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
return 0;
}
Here is the 'min'.
public static int min(int[]x){
int min=0;
for (int i = 0; i < x.length; i++) {
if(x[i]<min){
min=x[i];
}
}
return min;
}
And the 'max' I am not sure what the issue is.
public static int max(int[]x){
int max=0;
for (int i = 0; i < x.length; i++) {
if(x[i]>max)
x[i]=max;
i++;
}
return max;
}
public static int getTotal(int[]x){
int total=0;
for (int i = 0; i < x.length; i++) {
total=total+x[i];
}
return total;
}
}```
||SOLVED||
Changed min and max and also added maximum(x); minimum(x); in main while removing ^^ System.out.println("The min is "+ min(x)); ^^
^^ System.out.println("The max is "+ max(x));.^^
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int []x=new int[n];
random(x);
sizeArray(x);
maximum(x);
minimum(x);
System.out.println("The Total is "+ getTotal(x));
}
public static int random(int[]x){
Random rand=new Random();
for (int i = 0; i < x.length; i++) {
x[i]=rand.nextInt(101);
}
return 0;
}
public static int sizeArray(int []x){
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
return 0;
}
|Changed max|
public static void maximum(int x[]) {
int max = x[0];
for (int i = 1; i < x.length; i++) {
if (x[i] > max) {
max = x[i];
}
}
System.out.println("maximum is:" + max);
}
|And changed min|
public static void minimum(int x[]) {
int min = x[0];
for (int i = 1; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
}
System.out.println("minimum is:" + min);
}
public static int getTotal(int[]x){
int total=0;
for (int i = 0; i < x.length; i++) {
total=total+x[i];
}
return total;
}
}
Here you are probably setting every element in the array to 0. And in any case, max is always going to return 0
public static int max(int[]x){
int max=0;
for (int i = 0; i < x.length; i++) {
if(x[i]>max)
x[i]=max;
i++;
}
return max;
}
And here, you are starting with min = 0 (which isn't necessarily a value in the array) and since all the values are greater than 0, the return value is 0.
public static int min(int[]x){
int min=0;
for (int i = 0; i < x.length; i++) {
if(x[i]<min){
min=x[i];
}
}
return min;
}
And honestly, it would have been very easy or you to figure this out if you'd used the debugger to step through your functions. Learning how to use a debugger is an invaluable skill!
I have an issue where it seems like when I try to display my new array full of even numbers from the first array, it only outputs the last value? I don't see where the problem lies within the nested for loop inside my GetEven method?
package allevenproj;
import java.util.*;
public class AllEvenProj {
static int Read(int[] arr) {
Scanner scan = new Scanner(System.in);
int count = 0;
for (int i = 0; i < arr.length; i++) {
System.out.printf("Enter arr[%d]: ", i);
arr[i] = scan.nextInt();
if (arr[i] % 2 == 0) {
count++;
}
}
System.out.printf("There are %d even numbers\n", count);
return count;
}
static int[] GetEven(int[] arr, int count) {
int[] evenArr = new int[count];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < count; j++) {
if (arr[i] % 2 == 0) {
evenArr[j] = arr[i];
}
}
}
return evenArr;
}
static void Print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of array: ");
int n = scan.nextInt();
int[] arr = new int[n];
int a = Read(arr);
Print(GetEven(arr, a));
}
}
You'are getting only the last value because due to the inner for loop in the GetEven method: every time you do a full inner loop (you do it for every number in arr) you rewrite the whole evenArr.
So the fix is removing the inner loop:
static int[] getEven(int[] arr, int count) {
int[] evenArr = new int[count];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
evenArr[j++] = arr[i];
}
}
return evenArr;
}
By the way, methods name should be lowercase. Naming conventions
As Ruben said the problem is in your loop. I took the liberty to refactor your code a bit just to show you a better approach to the problem
package allevenproj;
import java.util.*;
public class AllEvenProj {
static int[] read(int size) {
Scanner scan = new Scanner(System.in);
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
System.out.printf("Enter arr[%d]: ", i);
arr[i] = scan.nextInt();
}
return arr;
}
static void print(int[] arr) {
System.out.printf("There are %d even numbers\n", arr.length);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of array: ");
int size = scan.nextInt();
print(Arrays.stream(read(size)).filter(x -> x % 2 == 0).toArray());
}
}
I'm trying to create a program that asks the user to input a number which is how many random numbers between 1-100 will be generated in an array. Then I want the largest number to be swapped with the last number and the smallest number to be swapped with the first number. Here is my code so far:
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
}
if (myArray[i] < smallest) {
smallest = myArray[i];
}
}
for (int j = 1; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
}
}
}
I can't seem to get the numbers to properly swap. I created a loop which determines the smallest and largest numbers from the ones generated and these are stored. Then I create a loop which performs the necessary swaps but I can't seem to get it to work properly. It works fine for swapping the largest number with the last number but most of the time(not always) the outputted last number is also present somewhere else in the array. Here is what I mean:
input: 10
output: 62 48 34 0 91 14 64 60 91
I know there is a swapper method that I could use but I want to do it by manually swapping the numbers. Any help is appreciated, thanks.
you have one simple mistake, your loop should start from '0' when you perform the swap
for (int j = 0; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
Instead of a loop do
//find and stores poition of small
int smallPos = myArray.indexOf(small);
//stores tge values at 0
int tempSmall = myArray[0];
//swaps the values
myArray[0] = small;
myArray[smallPos] = smallTemp;
Just repeat this with the largest value and print it using a for loop. Tell me if it works.
I just tried this. Hope this helps.
public class App {
static int[] a = new int[100];
public static void main(String[] args) {
int i;
for(i = 0; i<a.length;i++)
a[i] = (int)(java.lang.Math.random() * 100);
int smallest = 0, largest = 0;
for(i =1; i<a.length; i++){
if(a[i] < a[smallest])
smallest = i;
if(a[i] > a[largest])
largest = i;
}
swap(0,smallest);
swap(a.length-1,largest);
for(i =0; i<a.length;i++)
System.out.print(a[i] + " ");
}
public static void swap(int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Your last loop doesn't do anything loopy. It just does the same thing over and over. And what it does is not correct. It is swapping the smallest into the first element but it's not moving the first element anywhere: it's gone.
You need to keep track of where the largest and smallest elements were. Your swap logic doesn't take that into consideration.
Write this code
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
int pos1,pos2;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
pos1=i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
pos2=i;
}
}
myArray[pos1]=myArray[myArray.length-1];
myArray[myArray.length-1]=largest;
myArray[pos2]=myArray[0];
myArray[0]=smallest;
for (int j = 1; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
}
i would advise against using a scanner or random values for testing since the result cannot be reproduced (at least not in an easy way). Be careful with what is an arrays index and what is the value at a specific index. This can lead to confusion very quickly. ^^
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
private static int[] myArray;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
//int num = scan.nextInt(); //skip this for testing ^^-d
int num = 10;
myArray = new int[num];
for (int i = myArray.length-1; i > 0; i--) {
//int randomInt = randomGenerator.nextInt(100);
int randomInt = i; //use test condition that can be reproduced!
myArray[i] = myArray.length-i;
}
int smallest = 0;
int largest = 0;
int smallestIndex = 0;
int largestIndex = 0;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
largestIndex = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
smallestIndex = i;
}
}
switchIndexOfmyArray(0, smallestIndex);
switchIndexOfmyArray(myArray.length-1, largestIndex);
for (int j = 0; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
public static void switchIndexOfmyArray(int index, int switchWithIndex){
int temp = myArray[index];
myArray[index] = myArray[switchWithIndex];
myArray[switchWithIndex] = temp;
}
}
Yielding
0 1 8 7 6 5 4 3 2 9
I admit i was slow on this one since i am hungry and tired xD
Happy coding! ^^
You did well by finding smallest and largest. Issue was in swap. I refactor the swap method. May be it works.
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
System.out.println();
int smallest = myArray[0];
int largest = myArray[0];
int sIndx = 0;
int lIndx = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
lIndx = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
sIndx = i;
}
}
System.out.println();
System.out.println("Smallest = "+smallest);
System.out.println("largest = "+largest);
System.out.println("Smallest Index = "+sIndx);
System.out.println("largest Index = "+lIndx);
swapSmallAndLargest(num, myArray, sIndx, lIndx);
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
}
private static void swapSmallAndLargest(int num, int[] myArray, int sIndx, int lIndx) {
int temp = 0;
temp = myArray[sIndx];
myArray[sIndx] = myArray[0];
myArray[0] = temp;
temp = myArray[lIndx];
myArray[lIndx] = myArray[num-1];
myArray[num-1] = temp;
}
}
I'm a beginner at java and I have a hopefully simple question.
I can get the numbers in order, but only a certain amount of numbers are added to the array. When there is a number less than the smallest number, it replaces that smallest number (the previous smallest gets removed from array). What can I do so that all of the array spots can be filled in?
public class apples {
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num=IO.readInt();
double array[]=new double[num];
double temp;
boolean fixed=false;
while (fixed==false){
fixed=true;
for(int j=0; j<num;j++){
double x = IO.readDouble();
array[j] = x;
for (int i = 0; i < ( num - 1 ); i++) {
for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j+1]) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
fixed=false;
}
}
}
System.out.println("Sorted list of integers:");
for (int i = 0; i < num; i++)
System.out.println(array[i]);
}
}
}
}
First read in the numbers, then sort the array (and it's an array of double not int). Something like,
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num = IO.readInt();
double array[] = new double[num];
for (int j = 0; j < num; j++) {
System.out.printf("Please enter double %d:%n", j + 1);
array[j] = IO.readDouble();
}
System.out.println("unsorted array: " + Arrays.toString(array));
Arrays.sort(array); // <-- or however you want to sort the array.
System.out.println("sorted array: " + Arrays.toString(array));
}
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num = IO.readInt();
double array[] = new double[num];
for (int i = 0; i < num; i++) {
System.out.print("["+i+"]Please enter your double");
array[i] = IO.readDouble();
}
//Sort
double temp = 0;
for (int i = 0; i < num - 1; i++) {
for (int j = i + 1; j < num ; j++) {
if (array[j] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//Result
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr[]=new int [n];
for (int i =0;i<n;i++){
arr[i]=sc.nextInt();}
Arrays.sort(arr);
//if(n%2==0){median}
System.out.println( Arrays.toString(arr));
}
}
This is my code for the Bubble Sort. I cannot get the actual sorted values to output. The program reads the inputted numbers, but does not print it sorted.
I'm not sure what I have to do to make them sort.
Any advice or suggestions would be helpful.
package sortingalgorithm2;
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int[] num = new int[15];
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}
BubbleSort (num);
for (int i=0; i < num.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort(int[] num)
{
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}
Try this Bubble sort :
private static void BubbleSort(int[] num) {
for (int i = 0; i < num.length; i++) {
for (int x = 1; x < num.length - i; x++) {
if (num[x - 1] > num[x]) {
int temp = num[x - 1];
num[x - 1] = num[x];
num[x] = temp;
}
}
}
}
You are printing the actual numbers in the order the user entered. Try this instead:
int[] sortedNumbers = new int[15];
sortedNumbers = BubbleSort (num);
for (int i=0; i < sortedNumbers.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(sortedNumbers[i]+ " ");
}
public static int[] BubbleSort(int [] num)
{
int temp;
for (int i=1; i<num.length; i++)
{
for(int j=0; j<num.length-i; j++)
{
if (num[j] > num [j+1])
{
temp = num [j];
num [j] = num [j+1];
num [j+1] = temp;
}
}
}
return num;
}
Try this :
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
if (num[i] > num[j]) {
num[i] = num[i] + num[j] - (num[j] = num[i]);
}
}
}
you are passing the array variable num (which is not static) to BubbleSort()(which does not returns a value and shadows the global num variable with its own) and trying to use the same num variable to access your sorted array from your main method which is not right.
The genuine fix to this is to declare your variable num as static just before the main method( in the class declaration). So I have made the changes in the program and here is the solution.
import java.util.Scanner;
public class sol {
static int num [] =new int [15]; //declaring num as static in the class definition.
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
read.close();
/*for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}*/ //I have disabled this just to check with the sort method.
BubbleSort ();//no need to pass the array as it is static and declared as a //class variable hence can be used to by all the methods of that class
System.out.println("The sorted numbers are: ");
for (int i=0; i < num.length; i++)
{
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort()
{
for (int i=0; i < num.length; i++)// required changes in the looping
for (int x=0; x < num.length-i-1; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}