how to ranking of race time - java

I need to write a program that can ranking race time of 10 runners
so I created 2 arrays
ID of runners (10 runners)
race time of 10 runners (race time must be less than or equal to 20.0 sec)
and I found that my sorting algorithm can't be used correctly, I don't want to use Arrays.sort(x); because I need to sort "those race time and ID" here is my code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ID = new String[10];
double[] time = new double[10];
for (int i = 0; i < ID.length; i++) {
System.out.print("Please enter ID and times: ");
ID[i] = sc.nextLine();
time[i] = sc.nextDouble();
}
Run a = new Run(ID, time);
System.out.println("Top 3 is ");
a.Sort();
}
}
and
public class Run {
private String[] ID = new String[10];
private double[] time = new double[10];
public Run(String[] ID, double[] time) {
for (int i = 0; i < ID.length; i++) {
this.ID[i] = ID[i];
}
for (int i = 0; i < time.length; i++) {
if (time[i] <= 20.0) {
this.time[i] = time[i];
}
}
}
public void Sort() {
double tem1;
String tem2;
for (int i = 0; i < time.length; i++) {
for (int j = 0; j < time.length; j++) {
if (time[j] > time[j+1]) {
tem1 = time[j];
time[j] = time[j+1];
time[j+1] = tem1;
tem2 = ID[j];
ID[j] = ID[j+1];
ID[j+1] = tem2;
}
}
}
for (int i = 0; i < 3; i++) {
System.out.println(ID[i] + " " + time[i]);
}
}
}
so I need to know why my sorting algorithm can't be used correctly, it's pop an error on my console.
One more question, in the input stage when I input first ID and time, if I press like this
ID[0] -> Enter -> time[0]
then the input is correct but if I press
ID[0] -> Spacebar -> time[0]
then the input is wrong.
Why? And how do I fix it?

First thing I see is that you are passing an array of 10 elements in the constructor of Run; this is not necessary, you can directly pass the arrays:
In main:
Run a = new Run(ID, time);
In run:
public Run(String[] ID, double[] time) {
this.ID = ID;
this.time = time;
}
Can you post the error log?
Read here for the problem in reading the inputs: Read integers and strings from a single line of a console
The problem is that you are trying to get in an array cell that doesn't exist: array.length returns the length of the array, so in that case returns 10.
You are doing a for cycle from 0 to 10, then you are trying to get (in the if statement) inside time[11] (it was time[j+1]).
Change the for cycle to:
for (int i = 0; i < time.length - 1; i++) {
for (int j = 0; j < time.length - 1; j++) {
System.out.println(i + " "+ j);
if (time[j] > time[j+1]) {
tem1 = time[j];
time[j] = time[j+1];
time[j+1] = tem1;
tem2 = ID[j];
ID[j] = ID[j+1];
ID[j+1] = tem2;
}
}
}

#Pleasant94 answered your question regarding the index error.
To answer your question about why you need to enter a new line (press enter) after inputting the ID is because you are scanning the whole line into the ID value using nextLine(). Instead of using nextInt() like you did for time with nextDouble().
like so:
...
ID[i] = sc.nextInt();
time[i] = sc.nextDouble();
...
Check out the Java docs for the scanner class here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
And because you are now scanning in a int you'll have to update all your ID variables to int. Combining it with Pleasant94's answer you should be able to do just do this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] ID = new int[10];
double[] time = new double[10];
for (int i = 0; i < ID.length; i++) {
System.out.print("Please enter ID and times: ");
ID[i] = sc.nextInt();
time[i] = sc.nextDouble();
}
Run a = new Run(ID, time);
System.out.println("Top 3 is ");
a.Sort();
}
}
class Run {
private int[] ID = new int[10];
private double[] time = new double[10];
public Run(int[] ID, double[] time) {
for (int i = 0; i < ID.length; i++) {
this.ID[i] = ID[i];
}
for (int i = 0; i < time.length; i++) {
if (time[i] <= 20.0) {
this.time[i] = time[i];
}
}
}
public void Sort() {
double tem1;
int tem2;
for (int i = 0; i < time.length - 1; i++) {
for (int j = 0; j < time.length - 1; j++) {
if (time[j] > time[j+1]) {
tem1 = time[j];
time[j] = time[j+1];
time[j+1] = tem1;
tem2 = ID[j];
ID[j] = ID[j+1];
ID[j+1] = tem2;
}
}
}
for (int i = 0; i < 3; i++) {
System.out.println(ID[i] + " " + time[i]);
}
}
}

Related

How to show 2 or more duplicates with this array using java?

i would like to display 2 or more duplicated customers using joptionpane. It is working if there is only 1 duplicate customer but unfortunately the message dialogue wasnt showing if there is 2 or more duplicated customer. Here is my code.
public static void main(String[] args) {
int number;
number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of customers: "));
int[] one = new int[number];
int[] two = new int[number];
for (int i = 0; i < number; i++) {
one[i] = Integer.parseInt(JOptionPane.showInputDialog("Customer number: "));
}
int y = 0;
for (int i = 0; i < one.length - 1; i++) {
for (int w = i + 1; w < one.length; w++) {
if (one[i] == one[w]) {
two[y] = one[w];
y = y + 1;
break;
}
}
for (int p = 0; p < y - 1; p++) {
if (one[p] == two[p - 1]) {
y = y - 1;
break;
}
}
}
if (y == 0) {
JOptionPane.showMessageDialog(null, "\nHONEST CUSTOMERS");
} else if (y != 0) {
JOptionPane.showMessageDialog(null, "Duplicates:");
for (int o = 0; o < y; o++) {
JOptionPane.showMessageDialog(null, "Customer #" + two[o]);
//jop.showMessageDialog(null, "Duplicates: Customer #" + two[l]);
//}
}
}
}
}
How can i show the message dialogue if i want to show 2 or more duplicated customers? thank you for the help.
Break down your code into the following:
A function that takes the two lists and return a list of pairs of duplicates.
A function that takes the list of duplicates and create a string stating: "Duplicates: value1, value2..."
Show message box.
here is an solution for your problem using Collections:
public static Integer[] getDuplicates(Integer[] list) {
List<Integer> duplicates = new ArrayList<>(Arrays.asList(list));
Set<Integer> seen = new HashSet<>(Arrays.asList(list));
for (Integer i : seen) {
duplicates.remove(i);
}
Set<Integer> uniqueDuplicate = new HashSet<>(duplicates);
return uniqueDuplicate.toArray(Integer[]::new);
}
public static void main(String[] args) {
int number;
number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of customers: "));
Integer[] one = new Integer[number];
for (int i = 0; i < number; i++) {
one[i] = Integer.parseInt(JOptionPane.showInputDialog("Customer number: "));
}
Integer[] two = getDuplicates(one);
if (two.length == 0) {
JOptionPane.showMessageDialog(null, "\nHONEST CUSTOMERS");
} else {
JOptionPane.showMessageDialog(null, "Duplicates:");
for (int o = 0; o < two.length; o++) {
JOptionPane.showMessageDialog(null, "Customer #" + two[o]);
// jop.showMessageDialog(null, "Duplicates: Customer #" + two[l]);
// }
}
}
}

Function is just reversing the order of the input instead of sorting it in descending order

I need to make a program that will take string inputs from user and store it in an array. I will then need to make a function that first: sorts each String {character by character} in descending order and second: will sort all String input in descending order {Strings}.
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static String sortString(String str)
{
char[] chArr = str.toCharArray();
String SortString = "";
// For sorting each individual strings character by character
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j < chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
//converting all of the character into a single string
for (int k = 0; k<chArr.length;k++)
{
SortString = SortString + chArr[k];
}
//Assigning the current String Sortstring to an array
String[] OldArray = new String[5];
for (int counter = 0; counter<5; counter++)
{
OldArray[counter] = SortString;
}
//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
return OldArray[0];
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println((sortString(names[i])));
}
}
}
Input:
Input String #1: Stackoverflow
Input String #2: Java
Input String #3: ZZrot
Input String #4: coding
Input String #5: sorting
Output
tsronig
onigdc
zztro
vjaa
wvtsroolkfeca
Expected Output:
zztro
wvtsroolkfeca
vjaa
tsronig
onigdc
Sorry for the question I honestly don't know what to do
You're very close to the solution.
It's impossible to sort the array of strings in sortString because it only has access to the one string you pass in. Move the array sorting code to a separate method, and then you can call it while passing it the entire array:
static String sortString(String str) {
char[] chArr = str.toCharArray();
String SortString = "";
// For sorting each individual strings character by character
for (int i = 0; i < chArr.length; i++) {
for (int j = 0; j < chArr.length; j++) {
if (chArr[i] > chArr[j]) {
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
//converting all of the character into a single string
for (int k = 0; k < chArr.length; k++) {
SortString = SortString + chArr[k];
}
return SortString;
}
static void sortArray(String[] OldArray) {
//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
}
The main method needs a small change too: the characters in the strings have to be sorted before you sort the array. Here, the characters are sorted while reading the input, and then the array is sorted with one call to sortArray:
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = sortString(UserInput.next().toLowerCase());
}while(names[counter].length() > 25);
}
sortArray(names);
//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println(names[i]);
}
}
Just made some changes to your code. sortString() was working fine.
Made only changes to main() method:
Got expected output, Try this:
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
//will print the assorted array
String[] namesReversed = new String[names.length];
for(int i=0;i<names.length;i++){
namesReversed[i]=sortString(names[i]);
}
Arrays.sort(namesReversed, String::compareToIgnoreCase);
for(int i = namesReversed.length-1; i>=0; i--)
{
System.out.println(namesReversed[i]);
}
}

how to insert in two dimensional array?

i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}

Sorting strings alphabetically in an array. Java

I have to sort strings in an array for a school project. Our teacher won't allow us to use array,sort().
i have to use 2 sort methods but they aren't working too well.
The first one returns double of each value. ie John, jack, adam, tom will return adam,adam,jack,jack,john,john,tom,tom.
public static void sort() {
inputFileNames();//inputs list of names from a file.
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (stArr[i].compareTo(stArr[j])>0) {
temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
}
}
}
display("The names are: ");// method to display array
System.out.println("");
}
the second sort doesn' run:
public static void bubbleSort() {
inputFileNames();
for (int i = size - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
if (stArr[j].compareTo(stArr[j+1])>0) {
temp = stArr[j];
stArr[j] = stArr[j + 1];
stArr[j + 1] = temp;
}
}
}
display("The names are: ");
System.out.println("");
}
input and display:
static void display(String heading) {
System.out.println(heading + "\n");
for (int i = 0; i < size; i++) {
System.out.println(stArr[i]);
}
}
static void inputFileNames() {
try {
Scanner scFile = new Scanner(new File("Names.txt"));
while (scFile.hasNext()) {
stArr[size] = scFile.nextLine();
size++;
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
}
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{ Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i,j;
String[] stArr = new String[n];
for(i=0;i<n;i++)
{
stArr[i]=sc.next();
// System.out.println(stArr[i]);
}
//inputs list of names from a file.
for (i = 0; i < n ; i++) {
for (j = i+1 ; j < n; j++) {
if (stArr[i].compareTo(stArr[j])>0)
{
String temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
// System.out.println(stArr[i]);
// System.out.println(stArr[j]);
}
}
}
for(i=0;i<n;i++)
{
System.out.println(stArr[i]);
}
// your code goes here
}
}
This Is the answer for first code. I am not good in file handling so you have to use your input method. I know Scanner thats why i have used here.
In Your Second Example Your j loop is wrong it should be for ( j = 0; j <= i-1; j++). And Please Mark It as answer if your problem is solved

Sort strings in an array based on length

I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
String[] sortedArr = new String[arr.length];
for(int i=0;i<sortedArr.length;i++)
{
sortedArr[i] = compareArrayElements(arr);
}
System.out.println("The strings in the sorted order of length are: ");
for(String sortedArray:sortedArr)
{
System.out.println(sortedArray);
}
}
public static String compareArrayElements(String[] arr) {
String temp = null;
for(int i=0;i<arr.length-1;i++)
{
temp = new String();
if(arr[i].length() > arr[i+1].length())
temp = arr[i+1];
else
temp = arr[i];
}
return temp;
}
}
If you really want to learn Java: use a Comparator. Any other way is bad Java code.
You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.
For your actual code, here are some hints:
Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.
Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".
Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.
You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
Use bubble sort, but instead of comparing ints, just compare String lengths.
I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.
Good luck.
References:
Bubble sort in Java
Sorting an array of strings
Implement bubbleSort() and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
bubbleSort(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String item : arr) {
System.out.println(item);
}
}
// Mutates the original array
public static void bubbleSort(String[] arr) {
boolean swapped = false;
do {
swapped = false;
for (int i = 0; i < arr.length - 1; i += 1) {
if (arr[i].length() > arr[i + 1].length()) {
swap(arr, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
// Mutates the original array
public static void swap(String[] arr, int index0, int index1) {
String temp = arr[index0];
arr[index0] = arr[index1];
arr[index1] = temp;
}
}
Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string
import java.util.*;
class strings {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>(2);
System.out.println("Start entering your words or sentences.");
System.out.println("Type stop to stop.");
String b;
int c = 0, d;
do {
b = in.nextLine();
b = b.trim();
a.add(b);
c++;
}
while (!b.equalsIgnoreCase("stop"));
if (c > 1)
a.remove(a.size() - 1);
System.out.println("Choose the sort you want. Type the corresponding
number");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int sc=in.nextInt();
switch(sc) {
case 1: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] > sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
case 2: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] < sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
}
}
}
For instance, the following:
ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);
By lambda:
str.sort((String s1, String s2) -> s1.length() - s2.length());
By static Collections.sort
import static java.util.Collections.sort;
sort(str, new Comparator<String>{
#Override
public int compare(String s1, String s2) {
return s1.lenght() - s2.lenght()
}
});
Both options are implemented by default sort method from List interface
Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]
we can use Comparator for sorting the given string array to sort it based on length with the following code:
String[] sortByLength(String[] inputArray) {
Arrays.sort(inputArray, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
return inputArray;
}
//sort String array based on length
public class FirstNonRepeatedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your String");
String str = in.nextLine();
String arrString[] = str.split("\\s");
arrString = sortArray(arrString);
System.out.println("Sort String ");
for(String s:arrString){
System.out.println(s);
}
}
private static String[] sortArray(String[] arrString) {
int length = arrString.length;
String s;
for (int i = 0; i < length ; i++) {
s= new String();
for(int j = 0; j < length; j++ ){
if(arrString[i].length()< arrString[j].length()){
s = arrString[i];
arrString[i] = arrString[j];
arrString[j] = s;
}
}
}
return arrString;
}
}
import java.util.*;
public class SortStringBasedOnTheirLength {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String[] str1=str.split("\\s");
for(int i=0;i<str1.length;i++)
{
for(int j=i+1;j<str1.length;j++)
{
if(str1[i].length()>str1[j].length())
{
String temp= str1[i];
str1[i]=str1[j];
str1[j]=temp;
}
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]+" ");
}
}
}

Categories

Resources