selection sort algorithm using the array in java - java

When the program runs, it asks you to enter a product name and price, and then whenever you press -1 it will be stopped and display a list of the entered product and price. However, the problem is I wrote a selection sort algorithm to sort the list by PRICE in ascending order. The output is not what I expected. Have a look at "//Selection Sort" in this code
import java.util.Scanner;
public class ProductPrices {
private static Scanner keyboard = new Scanner(System.in);
private static Scanner key = new Scanner(System.in);
final static int arrayLength = 1000; //maximum array size
static float[] productPrice = new float[arrayLength]; //stores the prices of products
static String[] productName = new String[arrayLength]; //stores the names of products
public static void main(String[] args) {
System.out.println("SHOPPING. Press -1 to quit anytime.\n");
for(int i=0; i<arrayLength; i++) {
System.out.print("Product: ");
productName[i] = keyboard.nextLine();
if(productName[i].equals("-1"))
break;
System.out.print("Price: $");
productPrice[i] = key.nextFloat();
if(productPrice[i] < 0)
break;
}
System.out.println("\nList of the SHOPPING!\n---------------------");
for(int i=0; i<productPrice.length; i++) {
if(productName[i] == null || productName[i].equals("-1") || productPrice[i] < 0)
continue; // null arrays will not be displayed.
else {
// Selection sort
if(productPrice[i] > productPrice[i+1]) {
float temp = productPrice[i];
productPrice[i] = productPrice[i+1];
productPrice[i+1] = temp;
}
System.out.printf("Item: %s %.2f\n", productName[i], productPrice[i]);
}
}
}
}
For example
:::Input:::
Product: apple
Price: $2.35
Product: pie
Price: $1.36
Product: cereal
Price: $7.4
Product: -1
:::Output:::
Item: apple 1.36
Item: pie 2.35
Item: cereal 0.00
That is incorrect, it should be
Item: pie 1.36
Item: apple 2.35
Item: cereal 7.40

Basically you have implemented selection sort incorrectly. Here is the code to fix it, including a counter to count how many products have been entered (makes the implementation clearer). Also as the other post says, you do not swap the names in your example, only the prices. I think the following should work:
public static void main(String[] args) {
System.out.println("SHOPPING. Press -1 to quit anytime.\n");
int prodCount = 0;
for(int i=0; i<arrayLength; i++) {
System.out.print("Product: ");
productName[i] = keyboard.nextLine();
if(productName[i].equals("-1"))
break;
System.out.print("Price: $");
productPrice[i] = key.nextFloat();
if(productPrice[i] < 0)
break;
prodCount++;
}
System.out.println("\nList of the SHOPPING!\n---------------------");
for (int j = 0; j < prodCount-1; j++) {
int iMin = j;
for (int i = j+1; i < prodCount; i++) {
if (productPrice[i] < productPrice[iMin]) {
iMin = i;
}
}
if ( iMin != j ) {
float temp = productPrice[j];
productPrice[j] = productPrice[iMin];
productPrice[iMin] = temp;
String tempn = productName[j];
productName[j] = productName[iMin];
productName[iMin] = tempn;
}
}
for(int i=0; i<prodCount; i++) {
System.out.printf("Item: %s %.2f\n", productName[i], productPrice[i]);
}
}

Related

Bubble sort and input

I have to enter 3 jumpers who will jump 2 times.
Here is an illustration via my console for the first jump. (it's step is ok)
Then, for the second jump. I have to sort the first jump from the smallest to the biggest.
So, I have to retrieve the jumper Emilie and not Olivia.
I don't understand how to do this ?
I think my problem is my sortBublle() method ?
import java.util.*;
class Main {
public static void main(String[] args) {
String[] arrayJumper = new String[3];
int[] arrayJump = new int[3];
encoding_jump_1(arrayJumper, arrayJump);
sortBublle(arrayJump);
encoding_jump_2(arrayJumper, arrayJump);
}
public static void encoding_jump_1(String[] arrayJumper, int[] arrayJump){
Scanner input = new Scanner(System.in);
int iJumper = 0;
int iJump = 0;
System.out.println("Jump 1 : ");
for(int i=0; i<arrayJumper.length; i++){
System.out.print("Enter jumper " + (i+1) + " : ");
String jumper = input.next();
arrayJumper[iJumper++] = jumper;
System.out.print("Enter for the jumper " + arrayJumper[i] + " the first jump please : ");
int jump = input.nextInt();
while(jump <= 9 || jump >=111){
System.out.print("Error ! The jump should to be between 10 and 100 please : ");
jump = input.nextInt();
}
arrayJump[iJump++] = jump;
}
}
public static void sortBublle(int[] arrayJump){
int size = arrayJump.length;
int tempo = 0;
for(int i=0; i<size; i++){
for(int j=1; j < (size - i) ; j++){
if(arrayJump[j-1] > arrayJump[j]){
tempo = arrayJump[j-1];
arrayJump[j-1] = arrayJump[j];
arrayJump[j] = tempo;
}
}
}
}
public static void encoding_jump_2(String[] arrayJumper, int[] arrayJump){
Scanner input = new Scanner(System.in);
int iJump = 0;
System.out.println("Jump 2 : ");
for(int i=0; i<arrayJumper.length; i++){
System.out.print("Enter for the jumper " + arrayJumper[i] + " the second jump please : ");
int jump = input.nextInt();
while(jump <= 9 || jump >=111){
System.out.print("Error ! The jump should to be between 10 and 100 please : ");
jump = input.nextInt();
}
arrayJump[iJump++] = jump;
}
}
}
Thank you very much for your help.
You are only sorting arrayJump --> You need to sort both arrayJumper and arrayJump`
...
if(arrayJump[j-1] > arrayJump[j]){
tempo = arrayJump[j-1];
arrayJump[j-1] = arrayJump[j];
arrayJump[j] = tempo;
tempName = arrayJumper[j-1];
arrayJumper[j-1] = arrayJumper[j];
arrayJumper[j] = tempName;
}

Compare scanner input to array

Idea:
User inputs their bets by typing either 'W','L' or 'T' (wins, losses or tie). Program generates random results within these parameters. User input and result gets printed, and a score is presented based on correct bets, which is supplied by the program.
Im having issues on how to proceed with comparing user generated input from scanner to an arraylist that produces a random result.
If it were not for the multiple "questions" and "answers" I could use a (val.equals(input)) of sort. However, each individual bet is random and must be matched against the users bets to sum up the users score, that complicates it.
Any help appreciated.
public class test3 {
public static void main(String[] args) {
int score = 0;
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
String array[] = new String[5];
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
array[i]=input.nextLine();
}
List<String> list = new ArrayList<String>();
list.add("w");
list.add("l");
list.add("t");
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
test3 obj = new test3();
for(int i = 0; i < 5; i++){
System.out.print(obj.getRandomList(list) + " ");
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++){
System.out.print(array[i] + " ");
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
private Random random = new Random();
public String getRandomList(List<String> list) {
int index = random.nextInt(list.size());
return list.get(index);
}
}
One way to do this is in the code below.
You basically need to compare each element of your input with each element of the random list so run loop.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Test {
private Random random = new Random();
public static void main(String[] args) {
int score = 0;
System.out
.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
String array[] = new String[5];
for (int i = 0; i < 5; i++) {
System.out.println("Please enter your bet:");
array[i] = input.nextLine();
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++) {
System.out.print(array[i] + " ");
}
List<String> list = new ArrayList<String>();
list.add("w");
list.add("l");
list.add("t");
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
Test obj = new Test();
List<String> randList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
randList.add(obj.getRandomList(list));
}
for(String randBet : randList){
System.out.print( randBet + " ");
}
System.out.println("");
int counter = 0;
for (String yourbet: Arrays.asList(array)){
if(randList.get(counter).equals(yourbet)){
score++;
}
counter++;
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
public String getRandomList(List<String> list) {
int index = random.nextInt(list.size());
return list.get(index);
}
}
I removed test3 for simplicity, but basically you need save results on array and generate random results and saving them (i.e a list). Then you have to iterate through and compare each game result, and if your bet is correct, just add one to score. Check the code below:
Main:
public static void main(String[] args) {
int score = 0;
String array[] = new String[5];
List < String > randomResultList = new ArrayList<String> ( );
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
array[i]=input.nextLine();
}
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
for(int i = 0; i < 5; i++){
String randomResult = getRandomList();
System.out.print( randomResult + " ");
randomResultList.add ( randomResult );
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++){
System.out.print(array[i] + " ");
}
//here is where you compare each result
for(int i = 0; i < 5; i++)
{
if( array[i].equals ( randomResultList.get ( i ) ))
{
score++;
}
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
private static Random random = new Random();
public static String getRandomList() {
List<String> list = Arrays.asList("w", "l", "t");
int index = random.nextInt(list.size());
return list.get(index);
}
I/O Example:
Betting game initiating...
Type 'W' for win, 'L' for loss and 'T' for tie.
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
This week wins, losses and ties loading...
Result:
l l l t w
Your bets were:
w w w w w
You were correct on: 1 bettings
Extra:
You could do all on the same iteration! check this out.
public static void main(String[] args) {
int score = 0;
// Win Loose or Tie
List<String> list = Arrays.asList("w", "l", "t");
Random rand = new Random ( );
//String with result and bets i.e (wwwww) and (wlltw). This avoid another iteration.
String result="";
String bets = "";
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
String bet =input.nextLine();
String randomResult = ( list.get ( rand.nextInt ( list.size ( ) ) ));
//concatenate String with results and bets with +=
result += randomResult;
bets += bet;
//check if u won
if( bet.equals ( randomResult ))
{
score++;
}
}
//This are just the results! no more iterations.
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:" + result);
System.out.println("\n\nYour bets were:" + bets );
System.out.println("\n\nYou were correct on: " + score + " bettings");
}

I'm struggling with methods...particularly the arguments that you pass it.

I'm trying to teach myself Java and I'm having a hell of a time! :)
I just started the other day and I've hit a bit of a road block.
I'm trying to learn arrays, but my methods are also kinda jacked up.
I know when I invoke my method in my main that it isn't right. I thought I was supposed to give the method that I was invoking the arguments that it needs to carry out its processes?
I'm just trying to call my last method and display the data from that method.
package test_arraymethods;
import java.util.Scanner;
public class TEST_arraymethods
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("------------------------------------------");
System.out.println("Please enter the total number of dealers: ");
System.out.println("------------------------------------------");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.println("--------------------------------------------------------");
System.out.printf("Please enter the required data for each of your dealers: %n");
System.out.println("--------------------------------------------------------");
dataCalculation(numDealers);
//displayTotals(numberOfDealers, dealerNames, dealerSales, commissionRate);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: %n");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
double[] dealerSales = new double[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
double sales = input.nextDouble();
dealerSales[i] = sales;
}
}//data calculations
//METHOD 3
public static double[] commission(double[] dealerSales)
{
//Create array
double[] commissionRate = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
commissionRate[i] = dealerSales[i];
if(commissionRate[i] > 0 && commissionRate[i] < 5000)
commissionRate[i] = commissionRate[i] * 0.08;
else if(commissionRate[i] > 5000 && commissionRate[i] < 15000)
commissionRate[i] = commissionRate[i] * 0.15;
else if(commissionRate[i] > 15000)
commissionRate[i] = commissionRate[i] * 0.20;
}
return commissionRate;
}//commission method
public static double[] dealershipSales(double[] dealerSales)
{
//Create array
double[] dealershipSalesTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealershipSalesTotal[i] += dealerSales[i];
}
return dealershipSalesTotal;
}//dealership sales
public static double[] dealerSalesAvg(double[] dealerSales)
{
double[] dealerSalesAvgTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealerSalesAvgTotal[i] += dealerSales[i] / dealerSales.length;
}
return dealerSalesAvgTotal;
}//dealership sales averages
public static double[] dealershipTotalCommission(double[] commissionRate)
{
double[] totalCommission = new double[commissionRate.length];
for(int i = 0; i < commissionRate.length; i++)
{
totalCommission[i] += commissionRate[i];
}
return totalCommission;
}//total commission for the dealership
public static void displayTotals(double[] numberOfDealers, double[] dealerNames, double[] dealerSales, double[] commissionRate)
{
for(int i = 0; i < numberOfDealers.length; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
System.out.println(" " + commissionRate[i]);
}
// pass all of your values to this method and then display them
//display the dealer name and amount of sales
//and the amount of commission for all dealers in a tabular format.
}//display totals */
}//class
The reason that you can't get this to work:
displayTotals(numberOfDealers, dealerNames, dealerSales, commissionRate);
is that it is referring to variables that are not in scope. Those variables are all local variables within methods whose calls have finished. If you want the variables to be accessible in another method, they must be declared as (static, in this case) fields.

How can I add the values that I got from multiplying two arrays?

So I am creating an invoice program and I got stuck at the part when I have to get the total I got from multiplying two arrays. I am able to multiply them and I get the values but unfortunately more than one value if I enter more than one item. I want to be able to add the values I get to get a total.
To give you an idea, here's my code:
public static void main(String []args){
Scanner input = new Scanner(System.in);
String sentinel = "End";
String description[] = new String[100];
int quantity[] = new int[100];
double price [] = new double[100];
int i = 0;
// do loop to get input from user until user enters sentinel to terminate data entry
do
{
System.out.println("Enter the Product Description or " + sentinel + " to stop");
description[i] = input.next();
// If user input is not the sentinal then get the quantity and price and increase the index
if (!(description[i].equalsIgnoreCase(sentinel))) {
System.out.println("Enter the Quantity");
quantity[i] = input.nextInt();
System.out.println("Enter the Product Price ");
price[i] = input.nextDouble();
}
i++;
} while (!(description[i-1].equalsIgnoreCase(sentinel)));
System.out.println("Item Description: ");
System.out.println("-------------------");
for(int a = 0; a <description.length; a++){
if(description[a]!=null){
System.out.println(description[a]);
}
}
System.out.println("-------------------\n");
System.out.println("Quantity:");
System.out.println("-------------------");
for(int b = 0; b <quantity.length; b++){
if(quantity[b]!=0){
System.out.println(quantity[b]);
}
}
System.out.println("-------------------\n");
System.out.println("Price:");
System.out.println("-------------------");
for(int c = 0; c <price.length; c++){
if(price[c]!=0){
System.out.println("$"+price[c]);
}
}
System.out.println("-------------------");
//THIS IS WHERE I MULTIPLY THE PRICE AND THE QUANTIY TOGETHER TO GET THE TOTAL
for (int j = 0; j < quantity.length; j++)
{
//double total;
double total;
total = quantity[j] * price[j];
if(total != 0){
System.out.println("Total: " + total);
}
}
}
}
In your last for loop, you're only multiplying the quantity and the price of the item and putting it as the value of total instead of adding it to total. Also every time it loops it creates a new total.To make it better, declare total out of the loop and move your if statement out
double total = 0.0;
for (int j = 0; j < quantity.length; j++){
total += quantity[j] * price[j];
}
if(total != 0){
System.out.println("Total: " + total);
}

How to arrange an array in descending order alongside a string array

here is my code... I need all the contestants to be ranked according to their votes... as you can see there are seperate arrays for the names and vote count(tally)... I was told that bubble sort would work but i cant see how because bubble sort replaces the insides so if tally[2] is greater than tally[1], it will become the new tally[1] meanwhile the name stays the same as name[1] does not change with name[2]...I would prefer that you use basic codes as i am a total noob with programming and have only recently started...also, any recommendations about how i can write my code better/shorter is appreciated
import java.util.*;
public class FroshNight {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String dec = "0";
System.out.println("How many blocks?");
int contno = sc.nextInt();
int winner = 0;
String winname = "a";
String[] code = new String[contno];
int total = 0;
int counter = 0;
String[] contname = new String[contno];
int[] tally = new int[contno];
while (counter<contno) {
System.out.print("Name of Pair:");
contname[counter]=sc.next();
counter++;
}
counter=0;
while (counter<contno) {
System.out.println("Choose a vote code for "+ contname[counter]+"(must not be x)");
code[counter] = sc.next();
counter++;
}
boolean stop = false;
counter=0;
while(stop == false){
System.out.println("Input Vote (x to exit): ");
dec = sc.next();
if(dec.equals("x")) {
stop = true;
}
counter = 0;
while(counter<contno){
if(dec.equals(code[counter])){
tally[counter] +=1;
counter = contno;
}
counter++;
}
}
//>> aft. else
counter = 0;
while(counter<contno){
total += tally[counter];
counter++;
;
}
counter=0;
while(counter<contno){
if(tally[counter]>winner){
winner = tally[counter];
winname = contname[counter];
}
counter++;
}
System.out.print("The Winner is: "+ winname +" - "+winner );
System.out.println("("+((double)winner/total)*100+"%)");
counter = 0;
while (counter<contno) {
System.out.print(contname[counter]+" - Score:");
System.out.print(tally[counter]);
System.out.println("("+((double)tally[counter]/total)*100+"%)");
counter++;
}
//>>> end while
// add rankings here^^
}
}

Categories

Resources