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());
Related
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() );
}
}
}
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;
}
I am having trouble when I call my toString method and my code isn't following the correct format like it should, this is how I've been trying to call it.
public static void loadQueue(Queue<String> queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
queue.toString();
}
}
Here is the toString that I want to format it to:
#Override
public String toString() {
String str = "[ ";
if ( !isEmpty() ) {
for (int i = 0; i < queue.length - 1; i++){
str += queue[i] + ", ";
}
str += queue[queue.length - 1] + " ";
}
str += "]";
return str;
Is there a better way to be calling this so that it prints out the correct out put?
Correct format should be [ a, b, c, d ] but all I'm getting is [ abcd ].
Edit, added toString method
If you're trying to use the values between commas in the str as the values to push onto the queue then you don't need to call toString().
Does this work for you?
public static void loadQueue(Queue<String> queue, String str) {
if (null == queue) throw new IllegalArgumentException("Expected non-null queue");
if (null == str) throw new IllegalArgumentException("Expected non-null str");
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
}
I can't tell which class your toString override is on, but it wouldn't be on string or queue.
Queue.toString will probably not be what you want. Is there some reason you want to override toString rather than just have a method by another name?
Technique #1
Put all the methods in your existing class
public String queueToString(Queue<String> queue) {
String str = "[ ";
if ( !isEmpty() ) {
for (int i = 0; i < queue.length - 1; i++){
str += queue[i] + ", ";
}
str += queue[queue.length - 1] + " ";
}
str += "]";
return str;
}
...
public static void loadQueue(Queue<String> queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
System.out.println( queueToString(queue) );
}
Technique #2
Create a custom class for your queue and modify the behavior.
public class MyStringQueue extends Queue<String>
{
#Override
/* override the toString method here */
}
...
/* in your class, create an use a MyStringQueue instead of Queue<String> */
public static void loadQueue(MyStringQueue queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
System.out.println( queue.toString() );
}
Disclaimer : I'm using this Post, as reference for List<Object> to List<String> and this Post for Java List<String> of strings to a JavaScript array.
I've List<Seat> and I want to get all values of it in a comma separated String, I tried in this way
import java.util.*;
import java.lang.*;
class Rextester
{
public Rextester(){
Seat seat1 = new Seat();
seat1.setSeatNumber(1);
Seat seat2 = new Seat();
seat2.setSeatNumber(2);
Seat seat3 = new Seat();
seat3.setSeatNumber(3);
List<Seat> seatList = new ArrayList<Seat>();
seatList.add(seat1);
seatList.add(seat2);
seatList.add(seat3);
Utility util = new Utility();
String stringSeats = util.toJavascriptArray(seatList);
System.out.println("JavaScriptArray is " + stringSeats);
}
public static void main(String args[])
{
new Rextester();
}
private class Seat {
private Integer seatNumber;
public Integer getSeatNumber() {
return this.seatNumber;
}
public void setSeatNumber(Integer seatNumber) {
this.seatNumber = seatNumber;
}
public String toString() {
return ""+ seatNumber;
}
}
private class Utility {
public String toJavascriptArray(List<Seat> listSeats){
List<String> strings = new ArrayList<String>();
for (Seat object : listSeats) {
strings.add(object != null ? object.toString() : null);
}
String[] arr = new String[strings.size()];
arr = strings.toArray(arr);
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i=0; i<arr.length; i++){
if(i+1 < arr.length){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
}
}
but this gives me
JavaScriptArray is [,,]
on console, am I making some mistakes? an online working code is http://rextester.com/NDUGT61105
You didn't append iterated element, see below
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]); // add this
if (i + 1 < arr.length) {
sb.append(",");
}
}
have a look at the toString implementations of Arrays and List
Simply you can return
strings.toString()
or
Arrays.toString(arr)
To get the expected result
Another option, if you're using Java 8 is using StringJoiner:
https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html
You forgot to append the array elements to the string buffer!
Add
sb.append(arr[i]);
inside the loop where you prepare the string buffer and everything is ok
I created a class for a bingo game. I get an error saying "'class' expected". How could I return the values in the array to the main starter?
Any other comments would also be helpful.
Thank you.
import java.util.Random;
public class Card
{
Random generator = new Random();
private final int BOARDMAX = 4;
private final int NUMMAX = 59;
int i, j, m, n;
private int [][] ArrayBoard = new int[BOARDMAX][BOARDMAX];
String [][] StrArrayBoard = new String [BOARDMAX][BOARDMAX];
public void RandomNumGenerator()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
ArrayBoard[i][j] = generator.nextInt (NUMMAX+1);
}
}
}
public String ShowBoard()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
m=i;
n=j;
if (j != BOARDMAX)
StrArrayBoard[m][n] = ArrayBoard[m][n] + " ";
else
StrArrayBoard[m][n] = ArrayBoard[m][n] + " \n";
}
}
return StrArrayBoard[i][j];
}
public void ShowMark()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
if (CardCheck [i][j] == 1)
StrArrayBoard[i][j] = ArrayBoard[i][j] + "* ";
else
StrArrayBoard[i][j] = ArrayBoard[i][j] + " ";
if (j == BOARDMAX)
ArrayBoard[i][j] = ArrayBoard[i][j] + "\n";
}
}
}
public String toString()
{
return ArrayBoard[][];
}
}
With toString() you need to return a String object but actually you try to return an int[][]. The same is true for ShowBoard, you try to return an array of Stringarrays which is not a compatible type.
Here's the fix:
public String ShowBoard() {
// your code to populate StrArrayBoard
StringBuilder boardBuilder = new StringBuilder();
for (String[] row:StrArrayBoard)
for (String cell:row)
sb.append(cell);
return boardBuilder.toString();
}
public String toString() {
return ShowBoard();
}
I suggest to refactor the code and rename methods and fields:
ShowBoard() --> getBoardAsString()
ArrayBoard --> arrayBoard
StrArrayBoard --> strArrayBoard
And there's no need to declare StrArrayBoard as a field (class member) just because you only need it inside the ShowBoard method. Declare it there as a local variable.
Adding to the bugs others have pointed:
You have if (CardCheck [i][j] == 1), but the array CardCheck is not declared anywhere.
You have ArrayBoard[i][j] = ArrayBoard[i][j] + "\n"; but ArrayBoard is an int array, you cannot add a string "\n" to it's member.
The compiler will complain because of the error on your code:
public String toString()
{
return ArrayBoard[][];
}
It can't convert int[][] (which is your ArrayBoard) to String. My suggestion is that you populate all values stored in StrArrayBoard in a StringBuffer and return the StringBuffer.toString() in the toString() method.
The toString() method requires a String.
Hope this helps.
public String toString()
{
return ArrayBoard[][];
}
This method expects to return a String but you are returning a 2D Integer array, what you need is a String. the toString() method returns a string representation of the object, so in this case, what you can do is to use a StringBuilder to build the string representation of the array and then, use the .toString() of the StringBuilder to return the string representing the 2D Array.
Also, as noted by Alois Cochard, you variable naming does not follow convention. Variable names in Java use a camel case notation.
I for one don't really understand your question but I've got a couple of comments.
The class variables i and j should be local variables in each method.
Your naming convention is nonstandard, seems like a more C# convention. Start variable and method names with a lower case.
CardCheck isn't defined anywhere. I presume it is meant to indicate if a number on a square has been checked, in which case it should be a boolean and not an int.
toString doesnt return a string. You can use Arrays.toString to help you.
Similarily, ShowBoard just returns one element of an array, you probably wanted to show the entire board there.
For your toString and ShowBoard methods you probably want to use a StringBuilder to build up the string representation.
StringBuilder builder = new StringBuilder();
for (int i=0; i<BOARDMAX; i++) {
for (int j=0; j<BOARDMAX; j++) {
builder.append(StrArrayBoard[i][j]);
}
builder.append('\n');
}
return builder.toString();
Here's a version of your class that compiles (and I changed some field names and modifiers to adhere to standard conventions). Try this:
public class Card{
private final Random generator = new Random();
private static final int BOARDMAX = 4;
private static final int NUMMAX = 59;
int i, j, m, n;
private final int[][] arrayBoard = new int[BOARDMAX][BOARDMAX];
private final String[][] strArrayBoard = new String[BOARDMAX][BOARDMAX];
// do something here please
private int[][] CardCheck;
public void RandomNumGenerator(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
arrayBoard[i][j] = generator.nextInt(NUMMAX + 1);
}
}
}
public String ShowBoard(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
m = i;
n = j;
if(j != BOARDMAX){
strArrayBoard[m][n] = arrayBoard[m][n] + " ";
} else{
strArrayBoard[m][n] = arrayBoard[m][n] + " \n";
}
}
}
return strArrayBoard[i][j];
}
public void ShowMark(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
if(CardCheck[i][j] == 1){
strArrayBoard[i][j] = arrayBoard[i][j] + "* ";
} else{
strArrayBoard[i][j] = arrayBoard[i][j] + " ";
}
if(j == BOARDMAX){
// this is probably what you mean:
strArrayBoard[i][j] = arrayBoard[i][j] + "\n";
}
}
}
}
#Override
public String toString(){
// this is probably what you mean:
return Arrays.deepToString(strArrayBoard);
}
}