How do i get this for loop to work? - java

I made a helper method to sort an array with numbers in it.
Then i call the method in my "main" method and have it return a using string.format.
This code works when the string.format portion is outside of the for loop and if statement but when its inside the i doesn't return anything when i tell it to.
I know the issue might have to do with my if statement but i'm having trouble finding a solution.
public static String getSmallestSalaryString(String[] names, int[] ages, double[] salaries) {
String str= "";
String str2="";
String str3="";
double[] sal= smallestSal(salaries);
for(int i= 0; i < sal.length; i++) {
if(sal[i]== 0) {
str= String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , sal[0], names[0], ages[0]);
return str;
}
else if(sal[i]== 1) {
str2= String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , sal[1], names[1], ages[1]);
return str2;
}
else if(sal[i] == 2) {
str3= String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , sal[2], names[2], ages[2]);
return str3;
}
}
return str;
}
public static double[] smallestSal(double[] salaries) {
Arrays.sort(salaries);
return salaries;
}

The solution requires you to find an "address" and not the "content".
I am assuming here that salaries contains the salary of all the employees, names is their name and ages their age. I am also assuming that ages, names and salaries have the same size and correlates per index. Then with these information, you construct a string to indicate the employee with the lowest salary in the company.
Since none of these information are structured within a single object, you need to find the lowest salary INDEX only. With that information, you can give his/her name and age by accessing ages[INDEX] and names[INDEX].
What you are currently doing is finding the lowest salary and then guess its INDEX in the loop, which would be more complex. Instead, in your method "smallestSal", get the INDEX in the array of the smallest salary. Then with that, your loop becomes simple. See below what I mean.
public static String getSmallestSalaryString(String[] names, int[] ages, double[] salaries) {
int lowestSalaryIdx= getLowestSalaryIndex(salaries);
return String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , salaries[lowestSalaryIdx], names[lowestSalaryIdx], ages[lowestSalaryIdx]);
}
public static int getLowestSalaryIndex(double[] salaries) {
int lowestSalaryIndex = 0;
double lowestSalary = Double.MAX_VALUE;
for(int i=0; i<salaries.length; ++i) {
if (salaries[i] < lowestSalary) {
lowestSalaryIndex = i;
lowestSalary = salaries[i];
}
}
return lowestSalaryIndex;
}

After sorting you get the smallest salary in 1st element(index 0). Then you should find the actual index of that value in original array and get the details from that index. So your code should be modified as follows.
public static String getSmallestSalaryString(String[] names, int[] ages, double[] salaries) {
String str = "";
String str2 = "";
String str3 = "";
ArrayList sal = smallestSal(salaries);
double smallestSalary = (double) sal.get(0);
int salIndex = 0;
for (int i = 0; i < salaries.length; i++) {
if (salaries[i] == smallestSalary) {
salIndex = i;
break;
}
}
str = String.format("Smallest salary:$%,.2f, Name:%s, age:%d", salaries[salIndex], names[salIndex], ages[salIndex]);
return str;
}
public static ArrayList smallestSal(double[] salaries) {
ArrayList salaryList = new ArrayList();
for (int i = 0; i < salaries.length; i++) {
salaryList.add(salaries[i]);
}
Collections.sort(salaryList);
return salaryList;
}

Since you are iterating through your array you should change sal[0], names[0], ages[0] to sal[i], names[i], ages[i] .
for(int i= 0; i < sal.length; i++) {
if(sal[i]== 0) {
str= String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , sal[i], names[i], ages[i]);
return str;
}

Related

Java Find index of an String Array and use that index to find value of an another array hold that index

I have two array like this
String[] StuID=new String[0];
int[] ProgrammingMarks=new int[0];
i use method to store data using Scanner
String id=inputID();
StuID = insertId(StuID, id);
System.out.println();
System.out.println("Student has been added successfully.");
public static String inputID() {
Scanner input=new Scanner(System.in);
System.out.print("Enter ID: ");
String id = input.nextLine();
return id;
}
public static String[] insertId(String[] StuID, String id) {
int length = size(StuID);
String[] newArray = new String[length+1];
for(int i=0;i<length;i++)
{
newArray[i] = StuID[i];
}
newArray[length] = id;
return newArray;
}
and i also add value for ProgrammingMarks Array using another method.
when i use scanner to Enter StuID, i need to print Student Programming Marks.i tried this using another method.
public static int PMarks(int[] ProgrammingMarks) {
MarksSystem.inputID();
int index=0;
for (int i = 0; i < ProgrammingMarks.length; i++) {
if (inputID().equals(ProgrammingMarks)) {
index=i;
break;
}
}
return index;
}
but its not working as i expected. here is my full code so far..
Java marks management system using array
If you are taking the inputId only once in your method then you can try this :
public static int PMarks(int[] ProgrammingMarks) {
String Id = MarksSystem.inputID();
int index=-1;
for (int i = 0; i < ProgrammingMarks.length; i++) {
if (Id.equals(ProgrammingMarks[i])) {
index=i;
break;
}
}
return index;
}
Also, Initialize your index to -1, to handle the case, if you do not get any match in the if block.
Also, If you have to take the inputId in every iteration of the for loop, then
public static int PMarks(int[] ProgrammingMarks) {
int index=-1;
for (int i = 0; i < ProgrammingMarks.length; i++) {
if (inputID().equals(ProgrammingMarks[i])) {
index=i;
break;
}
}
return index;
}
Hope it helps.
Update the equal condition in PMarks() method
if (inputID().equals(ProgrammingMarks[i])) {

Using compareTo to sort one array in ascending order

So I have to create an array of 5 chocolates, but I have to order them based on their quantities. I am not allowed to use the sort function.
import java.util.Scanner;
import java.util.Random;
public class Chocolate {
private String name;
private int quantity;
public Chocolate(String cName, int cQuantity) {
this.name = cName;
this.quantity = cQuantity;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
public int compareTo(Chocolate obj1){
if(this.quantity < obj1.quantity)
return -1;
else if (this.quantity > obj1.quantity)
return 1;
else
return 0;
}
public static void main(String args[]) {
Chocolate[] ch = new Chocolate[5];
Random rand = new Random();
Scanner scan = new Scanner(System.in);
String name;
int result;
int quantity;
for (int i = 0; i < ch.length; i++) {
System.out.println("Enter name of chocolates");
name = scan.nextLine();
quantity = rand.nextInt((19 - 1) + 1) + 1;
ch[i] = new Chocolate(name, quantity);
}
for (int i = 0; i < ch.length; i++) {
result = ch[i].compareTo(ch[i]);
System.out.println(ch[i].getName() + " " + ch[i].getQuantity());
System.out.println(result);
}
}
}
So basically I need to have a loop that uses the compareTo and orders the chocolates by quantity and then print them sorted. Cannot use .sort. Thanks
You cannot sort an array with only one loop. If you are not allowed to used sort method you can do it with a classic bubble sort:
for (int i = 0; i < ch.length; i++) {
for (int j = 0; j < ch.length - 1; j++) {
if (ch[j].compareTo(ch[j + 1]) < 0) {
Chocolate temp = ch[j];
ch[j] = ch[j + 1];
ch[j + 1] = temp;
}
}
}
But you will need for in for to achieve it.
You can do sorting without using any type of common sorting technique as long as you have these constraints:
The field to be used for sorting is integer or can be converted to integer.
The range of integer value of the field is within a small predefined range.
In your case your example satisfies both constraints.
You are sorting by cQuantity field which is an integer.
The cQuantity field is within 0 to 19 range.
What you can do is:
Create an Chocolate[20][20] array. Lets call it sorted.
Iterate over ch and put each Chocolate into the above sorted array using their getQuantity field as index. In case we have more than one Chocolate with the same getQuantity add them together under the same index.
Iterate over sorted and print its value if it is not null.
Here is the code:
Chocolate[][] sorted = new Chocolate[20][20];
for (Chocolate c : ch) {
Chocolate[] bucket = sorted[ c.getQuantity() ];
if (bucket == null) {
bucket = new Chocolate[20];
bucket[0] = c;
sorted[ c.getQuantity() ] = bucket;
}else {
//if we already have entry under this index, find next index that is not occupaed and add this one
for (int i = 0; i < bucket.length; i++) {
if (bucket[i] == null) {
bucket[i] = c;
break;
}
}
}
}
for (Chocolate[] bucket : sorted) {
if ( bucket != null) {
//System.out.println("b");
for (Chocolate c : bucket) {
if (c != null) System.out.println( c.getName() + " " + c.getQuantity() );
}
}
}

Hashset compare 2 string in ArrayList to find code

Hi I am trying to find a way to compare 2 String codes in a dynamic table that I made here's how I declare it:
this adds students
public void ajouteretudiants(Etudiant unetudiants) throws Exception {
if (nbreetudiantss >= 30) {
throw new Exception("Exces d'etudiants");
} else {
etudiants.add(unetudiants);
}
nbreetudiantss++;
this is to get the code of student (first letter of name + first letter of last name + birth year)
public String getCode() {
return this.code;
}
and here's how I try to get it for now:
public String toString() {
String chaine = " ";
for (int i = 0; i < nbreetudiantss; i++) {
chaine += etudiants.get(i).toString();
}
return chaine;
}
this is to class name in alphabetical order
public String listTriee(){
// trier le tableau etudiants en ordre alphabetique
Etudiant temp = null ;
for (int i=0; i<etudiants.size(); i++){
for (int j=i+1; j<etudiants.size(); j++)
if (etudiants.get(i).getNom().compareTo(etudiants.get(j).getNom()) > 0){
temp = etudiants.get(j);
etudiants.set(j,etudiants.get(i));
etudiants.set(i,temp);
}
}
return toString() ;
}
this is to search if the string we look for is in the table of students(here is my problem)
public String rechercher(String code){
Set<String> monHashSet=new HashSet<String>();
monHashSet.add(new String(etudiants.get(i).getCode()));
for (int i=0; i<etudiants.size(); i++){
}
return toString() ;
}
If you are able to use Java 8, you can implement something like this
Set<String> monHashSet = etudiants.stream()
.filter(code::equals)
.collect(Collectors.toSet());

using a method to print an array in java

From my current code how would i print the array{10,20,30,40,50,60,70,88,99,100} using a method display and calling it using System.out.println(myobject.display()) in my main.
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(){
String str = "";
for(int i = 0; i < 10; i++){
str= str+ " ";
}//for
return str;
}//display
My current method display does not display anything.
public TestA()
{
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
System.out.println(display(iA));
}
public static String display(int[] myData)
{
String str = "";
for(int i = 0; i < myData.length; i++){
str += myData[i]+ " ";
}
return str;
}
You need to call the method and print the result. Also use the array iA in your method.
System.out.println(display());
Your for loop is just adding an empty string to an empty string 10 times. You are never adding in the text from your array based on the index i. During your loop, you should be adding the space as well as the value at the current array position.
Your method display() is indeed doing something. It is returning 10 spaces, which are being printed out in your main method. You need to actually use the array at some point. Try something like:
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(int[] iA){
String str = "";
for(int i = 0; i < 10; i++){
str= str + Integer.toString(iA[i]) + " ";
}//for
return str;
}//display

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