Arrays FindMax What am I missing? - java

I have a project that says,"Write a program to read a list of integer numbers and print the largest number among them.
For example: if user enters: 9 11 15 3 7 9
it prints out 15.
What am I missing? Here is the output
import java.util.Scanner;
public class FindMax {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the list");
int size = scan.nextInt();
int[] list = new int[size];
int i;
for (i = 0; i < size; i++) {
list[i] = scan.nextInt();
}
int max = list[0];
for (i = 0; i > size; i++) {
if (list[i] > max)
max = list[i];
}
System.out.println(max);
}
}

The problem is in your second loop:
for ( i=0; i > size; i++)
It should be while i is SMALLER than size:
for ( i=0; i < size; i++)
Otherwise, it skips that loop and returns the default maximum which you set at list[0]

Related

Program that removes duplicated elements and return its new elements and size

My code is almost done but the problem is the returning size it supposed to return the size after the duplicated elements has been removed. it wont output the right size.
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
is there a problem on this part?
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
or this part?
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
The output should be:
Enter Number of Elements: 4
Enter value for num[0]: 2
Enter value for num[1]: 2
Enter value for num[2]: 3
Enter value for num[3]: 4
The inputted values are 2,2,3,4
Duplicated values 2,
The new values of the array are 2,3,4
The new length of the array is 3
The process you are using to find the duplicate elements is fine but you are not actually changing the elements in the array , you are just printing the non-duplicate ones, best approach is to change the value of the duplicate elements as a flag and then to find the length of the array after the duplicates have been removed,it will be easy :
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
System.out.println("duplicate value:"array[j]);
array[j]=-1;
}
}
So, now for the array length after removing the duplicate elements is:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}

How could I add a binary search method using user input in a sorted array

This is a expense sorter which I need to make for my class. I need a binary search method but don't know where to start. I know that binary searching works from the middle of a sorted array but the explanations from websites such as Wikipedia are very confusing.
The code consists of two sorting methods. Linear and selection sort. I have a user input in the variable size which tells the program about the size of the array.Can someone give me an example and explain it in the code using comments.
I want a user to give an input which will be the number that they are looking for. If the number is 57 then the array will scan the middle of the array and determine the number. lets say that number is 56. 56 is less than 57 so it will count upwards from that point until it finds that number
package project;
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class project {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Size;
int order;
System.out.println("Put in the amount of expenses you have");
Size = sc.nextInt();
System.out.println("put in all your expenses");
int userInput[] = new int[Size];
for (int i = 0; i < userInput.length; i++)
userInput[i] = sc.nextInt();
System.out.println(
"do you want it ascending or descending order. If you want it in ascending press 1 or if you want descending press 2");
order = sc.nextInt();
System.out.print("expenses not sorted : ");
printExpenses(userInput);
if (order == 1) {
expensesAscending(userInput);
} else if (order == 2) {
expensedescending(userInput);
}
}
public static void printExpenses(int[] arr) {
// this is were it is printed
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + "$");
}
}
public static void expensedescending(int arr[]) {
// This is were the selection sort starts
int N = arr.length;
for (int i = 0; i < N; i++) {
int small = arr[i];
int pos = i;
for (int j = i + 1; j < N; j++) {
if (arr[j] > small) {
small = arr[j];
pos = j;
}
}
int temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;
System.out.println(": ");
// Printing array after pass
printExpenses(arr);
}
}
public static void expensesAscending(int arr[]) {
int N = arr.length;
for (int i = 1; i < N; i++) {
int j = i - 1;
int temp = arr[i];
while (j >= 0 && temp < arr[j]) {
arr[j + 1] = arr[j];
j--;
;
}
arr[j + 1] = temp;
System.out.println(": ");
// Printing array after pass
printExpenses(arr);
}
}
}

count of odd elements of left side and right side please modify my code without exceeding the time limit

My code is O(n^2), please to decrease as O(n).
My question is count of the left side odd numbers and right side odd numbers. If it is equal on the bothsides(left and right) then print the respecive element other wise print the "-1". my code logic was correct it executing the normal text cases, but it was failing to execute the large value of text cases.It shows the error as "time exceeded".It was exceeding the timelimit of the compiler.i want to decrease the time limit of my code.
example: my input is 4 1 4 3 8 and my output:-1 4 -1 -1
example 2: my input is 6 1 3 4 8 5 7 and my output: -1 -1 4 8 -1 -1
enter code here
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int temp = 0;
int count = 0;
int flag = 0;
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
temp = a[i];
for (int j = 0; j < i; j++) {
if (a[j] % 2 != 0) {
count++;
}
}
for (int k = i + 1; k < n; k++) {
if (a[k] % 2 != 0) {
flag++;
}
}
if (count == flag) {
System.out.print(temp + " ");
} else {
System.out.print("-1 ");
}
count = 0;
flag = 0;
}
}
I have not tested it yet but it should work.
Your algorithm is O(n^2) and this one is O(n).
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
}
int total = 0;
for(int i=0;i<n;i++) {
if(a[j]%2!=0) {
total++;
}
}
int leftTotal = 0;
for(int i=0;i<n;i++) {
int k = a[i];
if (k%2!=0) {
leftTotal++;
}
if (leftTotal = (total-leftTotal)) {
System.out.println(k);
} else {
System.out.println(k);
}
}
}
enter code here
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n],flag=0,count=0;
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
if(a[i]%2!=0)
count++;
}
for(int i=0;i<n;i++) {
if(a[i]%2!=0)
count--;
if(flag==count)
System.out.print(a[i]+" ");
else
System.out.print("-1 ");
if(a[i]%2!=0)
flag++;
}
}
}

Multidimensional Array Java

I am writing a program using a method that returns the location of the largest element in a two dimensional array.
Example:
Enter the number of rows and columns of the array:
3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
the location of the largest element is at (1, 2)
My code is working, but I'm getting the output wrong. Instead of numbers I am getting some weird output with letters and numbers. How can I fix it? Thanks!
My code
import java.util.Scanner;
public class homework1a {
public static int[] locateLargest(double[][] a)
{
int total = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
maxRow = i;
maxColumn = j;
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
double b = 0;
//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");
int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();
//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
}
System.out.println("The location of the largest element is at "+ locateLargest(a));
}
}
Your method locateLargest() returns an int-array, which you are implicitly converting to string while printing it.
I think you want to display the row and cell numbers inside the array:
int[] largest = locateLargest(a);
System.out.println(String.format("The location of the largest element is at %d,%d", largest[0], largest[1]));
locateLargest(a) returns an int[2]. Arrays cannot be converted to strings natively, so the default toString() implementation is invoked on the array. The returned string representation does not contain the array elements.
This question might help you to print a helpful representation of the array. You might also want to print both values independently, not the array as a whole, e.g. like this:
int[] pos = locateLargest(a);
System.out.println("The location of the largest element is at " + pos[0] + ":" + pos[1]);
To print Arrays use Arrays.toString(array) output will be like [x,y]
System.out.println("The location of the largest element is at "+ Arrays.toString(locateLargest(a)));
Your method locateLargest returns an int[] which will not be printed out nicely.
If you want to keep the signature of locateLargest as it is, you could change your code in main like this:
int[] positionOfLargest = locateLargest(a);
System.out.println("The location of the largest element is at " +
positionOfLargest[0] + "/" + positionOfLargest[1]);
This stores the result in positionOfLargest and then prints out x/y coordinates the way you want them.
Hey for finding largest you can have your method like this.
public static int[] locateLargest(double[][] a)
{
int maxValue = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
If(a[i][j] > maxValue)
{
maxValue = a[i][j] ;
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
u should edit your locateLargest as this:
public static int[] locateLargest(double[][] a)
{
//may be ur array is contain negative
//so u can not use zero as MAX it's better to use first array element
int MAX = a[0][0];
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if(MAx < a[i][j]){
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
String result="location of largest num =a["+maxRow+"]["+maxColumn+"]";
return largest;
}

How do I handle multiple inputs using java.util.Scanner?

I am new to Java and when I wrote following code I faced this problem. I want to get a square matrix from user but first I get the number of columns and then I get the matrix and to handle this question I wrote this code:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
List<List<Integer>> matrix = new ArrayList<List<Integer>>();
for (int i = 0; i < n; i++)
{
matrix.add(new ArrayList<Integer>());
for (int j = 0; j < n; j++)
{
n = input.nextInt();
matrix.get(i).add(n);
}
}
}
}
I want to handle this input:
3
1 0 1
1 0 1
1 1 0
However, I type in:
3<enter>
1 0 1<enter>
Program exits just after the first entered row. How do I fix it?
If you are creating a matrix like used in a graph to show connections and you know how many there will be why not try a 2d array.
public static void main(String []args) {
int n,m ;
Scanner input = new Scanner(System.in);
n = input.nextInt();
int[][] matrix = new int[n][n];
for ( int i = 0 ; i < n ; i++ )
{ int j= 0;
while(input.hasNext() && j< matrix[].lenght)
{
m = input.nextInt();
matrix[i][j] = m;
j++
}
}
}
}
This should help :
import java.util.ArrayList;
import java.util.Scanner;
public class A {
public static void main(String []args) {
int n ;
Scanner input = new Scanner(System.in);
System.out.println("Columns : ");
n = input.nextInt();
ArrayList<List<Integer>> matrix = new ArrayList<List<Integer>>();
for ( int i = 0 ; i < n ; i++ )
{
matrix.add(new List<Integer>());
for ( int j = 0 ; j < n ; j++ )
{
int t = input.nextInt();
matrix.get(i).add(t);
}
}
/* This is to check the contents of the data structure */
for ( int j = 0 ; j < n ; j ++)
{
System.out.println();
for ( int k = 0 ; k < n ; k ++)
{
System.out.print(matrix.get(j).getElement(k) + " ");
}
}
}
}
1 Remember to import some of the features when needed; java.util.Scanner must be explicitly imported.
2 Messing with (Array)List is not needed here; use a regular array.
3 Scanner.nextInt() reads the whole line and parses an int at the beginning. Here you need to split the input by spaces.
Final code:
import java.util.Scanner; // note 1
import java.util.Arrays; // small utility
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt(); // load the size
int[][] matrix = new int[size][size]; // create a new array; note 2
for(int row = 0; row < size; ++row) {
String[] input = sc.nextLine().split(" "); // read a row
input = Arrays.copyOf(input, size); // pad/truncate the array
int[] processed = new int[size]; // for storing a row
for(int entry = 0; entry < size; ++entry)
processed[entry] = Integer.parseInt(input[entry]); // parse integers; note 3
matrix[row] = processed; // set the row
}
// for testing purposes:
for(int row = 0; row < size; ++row) {
for(int col = 0; col < size; ++col)
System.out.print(matrix[row][col] + " ");
System.out.println();
}
}
}

Categories