returning the smallest value of an array - java

I have a method that is supposed to return the smallest value of an array. The array is in the parametre of the method, so you input the values of your own choosing when you make an object of the class. This is the method I have come up with so far:
public class minsteNummer {
public minsteNummer() {
}
public int minsteNummer(Integer[] nummer) {
int minste = 0;
for(int i = 0; i< nummer.length; i++){
if(nummer[i] <= nummer.length) {
minste = i;
System.out.println("Minste nummer er " + minste);
} else if(nummer.length == 0) {
return 0;
}
}
return 0;
}
}
It does not execute the way I want it to, and I cant figure out what exacly it prints, but it is definetly not the smalles number of the array. I have tried with a while loop, but that does not work either.
Does anyone know where the fault in the code is, and how to improve it? I would also like it to just return, not print, the smalles number, but when I try to put "return minste;" in the if-statement, it says "unexpected return value".
Thanks in advance.

There are few places in your code that need attention:
As method scope is public you should always check for invalid input
Should not assign: int minste = 0; as there could be a negative number in a given array
When assign minimum number, should always compare it to the loop current number
if (minste > nummer[i]) minste = nummer[i];
Finally always return your minimum number return minste;
All together:
public static int minsteNummer(Integer[] nummer) {
if (nummer==null || nummer.length == 0) {
throw new IllegalArgumentException("Bad or empty array");
}
int minste = nummer[0];
for (int i = 1; i< nummer.length; i++){
if (minste > nummer[i]) minste = nummer[i];
}
System.out.println("Minste nummer er " + minste);
return minste;
}
It is worth to mention that you could use Java build-in functionality for such a basic task, i.e. sort array in ascending order and get first element:
public static int minsteNummer(Integer[] nummer) {
if (nummer==null || nummer.length == 0) {
throw new IllegalArgumentException("Bad or empty array");
}
Arrays.sort(nummer);
return nummer[0];
}

use streams
Integer[] arrayB = null;
OptionalInt min = Arrays.stream(arrayB).mapToInt(Integer::intValue).min();

public int minsteNummer(Integer[] nummer) {
int minste = Integer.MAX_VALUE;
for(int i = 0; i< nummer.length; i++){
if(nummer[i] < minste ) {
minste = nummer[i] ;
}
if(minste != Integer.MAX_VALUE)
return minste;
else
return 0;
}

Related

I keep getting a missing return statement?

In my code I'm trying to go through the arraylist and see if theres any reoccurring numbers. I keep getting an error saying i have a missing return statement. Is my code correct and how do I fix this problem.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(7);
list.add(2);
System.out.println("Type a number: ");
int number = Integer.parseInt(in.nextLine());
if (moreThanOnce(list,number)) {
System.out.println(number + " appears more than once");
}
else
System.out.println(number + " number does not appear more than once");
}
public static boolean moreThanOnce(ArrayList<Integer> list , int number) {
int count = 0;
for (int i = 1; i < list.size(); i ++ ) {
if (list.get(i) == number) {
count ++;
if (count > 1) {
return true;
}
else
return false;
}
}
Just remove the else part and move the "return false" outside the for loop in your moreThanOnce method
Change to:
public static boolean moreThanOnce(ArrayList<Integer> list , int number) {
int count = 0;
for (int i = 1; i < list.size(); i ++ ) {
if (list.get(i) == number) {
count ++;
if (count > 1) {
return true;
}
}
}
return false;
}
This guarantees that a return statement (false) is sent back if either there is not a recurring number that's equal to number and if it never enters the for-loop as well. It will return true if the conditions you put is met.
public static boolean moreThanOnce(ArrayList<Integer> list , int number) {
int count = 0;
for (int i = 1; i < list.size(); i ++ ) {
if (list.get(i) == number) {
count ++;
if (count > 1) {
return true;
}
else //delete this line
return false; // delete this line
}
}
return false;//add return here
}
To solve the error, it only needs a return outside the for loop.
And I think you should delete else logic, that makes the method cannot find the number which appears more than one time correctly.
You are missing a return statement in the case of the for loop not being executed in the moreThanOnce method.
You're missing a closing brace "}" for moreThanOnce(). It has four open braces, but only three closing braces.
Most code-oriented editors will match braces for you, and help track down imbalanced braces (and parens, etc.) Figure out how to do that in your editor, as that's something you'll need throughout your programming career.

Array required but Integer found

I am trying to compare two values present in two different arrays but I end up getting the " Array required but Integer found " compile time error . I am really not able solve this. I have marked the line from where the error was coming. It would be very appreciable if anybody can help me out with this. Here is the code .
public class Banker
{
int proccess, n, allocated[][], need[][], maximum[][], available[], safe[];
boolean done[];
public Banker(int n, int proccess) {
this.n = n;
this.proccess = proccess;
allocated = new int[n][n];
need = new int[n][n];
maximum = new int[n][n];
safe = new int[proccess];
done = new boolean[proccess];
}
public void getSafeSequence() {
int result = 0;
for (int i = 0; i < proccess; ++i) {
result = getLocation();
if (result != -1) {
safe[i] = result;
done[result] = true;
} else {
System.out.println(" No Safe Sequence Exist ");
break;
}
}
if (result != -1)
DisplaySequene();
}
public int getLocation() {
boolean flag = true;
for (int i = 0; i < proccess; ++i) {
if (done[i] != true) {
flag = true;
for (int j = 0; j < n; ++j)
***if (available[i][j] < need[i][j])*** {
flag = false;
break;
}
}
if (flag)
return i;
}
return -1;
}
}
available is one dimensional array so you cannot write available[i][j]. Change it to smh like available[i]
You defined available[] as a one dimensional array and use it with two dimensions available[i][j].

How can I avoid the user to add a repeated int value to an array?

First of all, I'm trying to do this using only simple conditions since I don't know how to use Hashmaps.
Ok, here is what I got so far, but I got stuck. Do you guys know a way in which I can compare an int to all the ints in an array?
public void rep() throws IOException {
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the value for the position # " + (1+i) + " of the array.");
int lol = Integer.parseInt(entrada.readLine());
if(!Arrays.Equals(arr[i], lol))
arr[i] = Integer.parseInt(entrada.readLine());
}
}
You can try this:
boolean repeat = false;
for(int j=0; j<i; j++ )
{
if(arr[j] == lol)
{
repeat = true;
break;
}
}
if(!repeat)
arr[i] = Integer.parseInt(entrada.readLine());
you can use the following method
for(i=0;i<intArray.length;i++){
if(intValue==intArray[i])
{ //write codes for if }
else{
// write codes for else }
You can do
java.util.Arrays.asList(arr).contains(lol)
what the above function is doing it coverts the array to list and the apply contains method to check if element is present

List collections interface in java

Please find below a function in my code:
private static List<String> formCrfLinesWithMentionClass(int begin, int end, String id,
List<String> mList, int mListPos, List<String> crf) {
List<String> crfLines = crf;
int yes = 0;
mListPosChanged = mListPos;
//--------------------------------------------------------------------------
for (int crfLinesMainIter = begin; crfLinesMainIter < end; ) {
System.out.println(crfLines.get(crfLinesMainIter));
//---------------------------------------------------------------------------
//the total number of attributes without orthographic features
//in a crfLine excluding the class attribute is 98
if (!crfLines.get(crfLinesMainIter).equals("") && crfLines.get(crfLinesMainIter).split("\\s").length == 98) {
//in mList parenthesis are represented by the symbol
//in crfLines parenthesis are represented by -LRB- or -RRB-
//we make a check to ensure the equality is preserved
if(val.equals(crfLines.get(crfLinesMainIter).split("\\s")[0])) {
yes = checkForConsecutivePresence(crfLinesMainIter, mList, mListPos, id, crfLines);
if (yes > 0) {
mListPosChanged += yes;
System.out.println("formCrfLinesWithMentionClass: "+mListPosChanged);
for (int crfLinesMentionIter = crfLinesMainIter;
crfLinesMentionIter < crfLinesMainIter + yes;
crfLinesMentionIter++) {
String valString = "";
if (crfLinesMentionIter == crfLinesMainIter) {
valString += crfLines.get(crfLinesMentionIter);
valString += " B";
crfLines.add(crfLinesMentionIter, valString);
}
else {
valString += crfLines.get(crfLinesMentionIter);
valString += " I";
crfLines.add(crfLinesMentionIter, valString);
}
}
crfLinesMainIter += yes;
}
else {
++crfLinesMainIter;
}
}
else {
++crfLinesMainIter;
}
}
else {
++crfLinesMainIter;
}
}
return crfLines;
}
The problem I face is as follows:
crfLines is a List collections interface.
When the for loop (between //-----) starts out, the crfLines.get(crfLinesMainIter) works fine. But once, it enters into the if and other processing is carried out on it, even though "crfLinesMainIter" changes the crfLines.get(crfLinesMainIter) seems to get a certain previous value. It does not retrieve the actual value at the index. Has anyone faced such a scenario? Would anyone be able to tell me why this occurs?
My actual question is, when does it occur that even though the indexes might be different a list.get() function still retrieves a value from before which was at another index?
For example:
List crfLines = new LinkedList<>();
if crfLinesMainIter = 2
crfLines.get(crfLinesMainIter) brings me a value say 20 and this value 20 satisfies the if loop condition. So then further processing happens. Now when the for loop executes the values of crfLinesMainIter changes to say 5. In this case, crfLines.get(5) should actually bring me a different value, but it still brings me the previous value 20.
(Not an answer.)
Reworked (more or less) for some modicum of readability:
private static List<String> formCrfLinesWithMentionClass(int begin, int end, String id, List<String> mList, int mListPos, List<String> crf) {
List<String> crfLines = crf;
mListPosChanged = mListPos;
int i = begin;
while (i < end) {
if (crfLines.get(i).equals("") || (crfLines.get(i).split("\\s").length != 98)) {
++i;
continue;
}
if (!val.equals(crfLines.get(i).split("\\s")[0])) {
++i;
continue;
}
int yes = checkForConsecutivePresence(i, mList, mListPos, id, crfLines);
if (yes <= 0) {
++i;
continue;
}
mListPosChanged += yes;
for (int j = i; j < i + yes; j++) {
String valString = crfLines.get(j);
valString += (j == i) ? " B" : " I";
crfLines.add(j, valString);
}
i += yes;
}
return crfLines;
}
What is mListPostChanged? I find it confusing that it's being set to the value of a parameter named mListPos--it makes me think the m prefix is meaningless.
What is val in the line containing the split?

Returning the element number of the longest string in an array

I'm trying to get the longest method to take the user-inputted array of strings, then return the element number of the longest string in that array. I got it to the point where I was able to return the number of chars in the longest string, but I don't believe that will work for what I need. My problem is that I keep getting incompatible type errors when trying to figure this out. I don't understand the whole data type thing with strings yet. It's confusing me how I go about return a number of the array yet the array is of strings. The main method is fine, I got stuck on the ???? part.
public static void main(String [] args)
{
Scanner inp = new Scanner( System.in );
String [] responseArr= new String[4];
for (int i=0; i<4; i++)
{
System.out.println("Enter string "+(i+1));
responseArr[i] = inp.nextLine();
}
int highest=longestS(responseArr);
}
public static int longestS(String[] values)
{
int largest=0
for( int i = 1; i < values.length; i++ )
{
if ( ????? )
}
return largest;
}
for (int i = 0; i < values.length; i++)
{
if (values[i].length() > largest)
{
largest = values[i].length();
index = i;
}
}
return index;
Note: initialize the int i with 0 - array index is 0-based.
Back in your main, you could then do System.out.println("Longest: " + responseArr[highest]); etc.
Here's how I'd write it:
public static int findIndexOfLongestString(String[] values)
{
int index = -1;
if ((values != null) && (values.length > 0))
{
index = 0;
String longest = values[0];
for (int i = 1; i < values.length; ++i)
{
if (values[i].length() > longest.length())
{
longest = values[i];
index = i;
}
}
}
return index;
}
You will want to store two things in your longestS method: the largest length so far, and the array index of the largest length. Also keep in mind that array indices start at 0 in Java. A for loop initialised with int i = 1 is actually going to start at the second index.
My solution:
public class JavaApplication3
{
public static void main(String[] args)
{
String[] big={"one","two","three"};
String bigstring=null;
int maxlength=0;
for(String max:big)
{
if(maxlength<max.length())
{
maxlength=max.length();
bigstring=max;
}
}
System.out.println(bigstring);
}
}

Categories