How do you repeat this method in array.length? - java

In this program, I want the user to type in 20 product names. from the main method. which will pass down to the method named searchProducts. But for some reason, it doesn't work. It only let me type in once, and then it prints out all 16 products.
public static void main(String[] args) {
String[] products= {"Pencil pouch", "pen", "Pencil sharpener", "High lighters", "Markers", "Erasers",
"Binder", "Notebooks", "Index cards", "Folders", "Glue", "Ruler", "Scissors", "Calculator",
"Calendar", "Backpack"};
System.out.println("Unordered list");
displayProducts(products);
sortProducts(products, 16);
System.out.println("");
System.out.println("Ordered list");
displayProducts(products);
}
private static int searchProducts(String[] products) {
Scanner sc = new Scanner(System.in);
String x = sc.nextLine();
System.out.println("Enter name of product: ");
for (int i = 0; i < products.length; i++) {
if (products[i].equals(x))
return i;
}
return -1;
}
private static void sortProducts(String products[],int n) {
for(int i = 0; i < n - 1; i++) {
int minindex = i;
String minStr = products[i];
for(int j = i + 1; j < n; j++) {
if(products[j].compareTo(minStr) < 0)
{
minStr = products[j];
minindex = j;
}
}
if(minindex != i)
{
String temp = products[minindex];
products[minindex] = products[i];
products[i] = temp;
}
}
}
private static void displayProducts(String[] products) {
for(int i = 0; i < products.length; i++){
System.out.println(products[i] + " ");
}
}

The way you pass array parameter is just good.
There are several ways to pass arrays as parameter:
(/*Other params,*/ String[] param) // this way
(String[] param /*, Other params*/) // or
(/*Other params,*/ String param[]) // this way
(String param[] /*, Other params*/) // or
// special case
// only as unique or last param of the params
// because with it you can enter several String params as individuals
(/*Other params, */ String... param)
// arrays of arrays
(String[] param[])
(String[][] param)
(String param[][] )
This is your problem:
sortProducts(products, 20);
...
private static void sortProducts(String products[],int n) {
You pass 20 although your array is 16 sized. So error.
Change this way to not depend on the size.
sortProducts(products);
....
private static void sortProducts(String products[]) { // no size passed
int n = products.length; // read the size from the array
EDIT 1 -------------
In the code below, the user to type in N products. Then the array is printed, sorted and printed. (NOT TESTED)
public static void main(String[] args) {
int N = 20;
String[] products = new String[N];
Scanner sc = new Scanner(System.in);
for(int i=0; i < N; i++) {
System.out.println("Enter name of product "+ (i+1) +" : ");
String x = sc.nextLine();
products[i] = x;
}
System.out.println("Unordered list");
displayProducts(products);
sortProducts(products);
System.out.println("");
System.out.println("Ordered list");
displayProducts(products);
// search block
}
To search in the array, you can do something like that (NOT TESTED):
public static void main(String[] args) {
// ... previous code
// search block in main method
System.out.println("Enter name of product to search, or \"stop\" to stop : ");
String y = sc.nextLine();
while(y != "stop") {
int index = searchProducts(products, y);
if( index == -1 )
System.out.println("Product "+ y +" is not in array");
else
System.out.println("Product "+ y +" is at position "+ index);
System.out.println("Enter name of product to search, or \"stop\" to stop : ");
y = sc.nextLine();
}
}
private static int searchProducts(String[] products, String p) {
for (int i = 0; i < products.length; i++) {
if (products[i].equals(p))
return i;
}
return -1;
}

Related

What is wrong with this swapping program in Java, why and what should I do?

I am making a multiple string input random swap without using a temp variable.
But when I input, this happens a few times:
This happens more frequently... (note that the first output is always null and some outputs occasionally repeat)
My code:
import java.util.Arrays;
import java.util.Scanner;
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
String[] swappedInput = new String[input.length];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter > 0) {
do{
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + swappedInput[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}
Because of randomality some times useCounter is the same as swapCounter and now look at those lines (assume useCounter and swapCounter are the same)
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
In the second line you are changing the value of xxx#www to be www so in the third line when doing split you dont get an array with two values you get an empty result thats why exception is thrown in addition you should not use swappedInput because it beats the pourpuse (if i understand correctly yoush shoud not use temp values while you are using addition array which is worse) the correct sollution is to only use input array here is the solution
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter >= 0) {
do {
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
// Skip if results are the same
if (useCounter == swapCounter) {
swapCounter++;
continue;
}
input[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
input[useCounter] = input[swapCounter].split("#")[0];
input[swapCounter] = input[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + input[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}

Insertion Sort - How to accept input and print the sorted array

I was trying to do a Insertion Sort Program that accepts any Data Type (Int, Double, String) then print's the sorted array. I know that my code work's but i can't figure out the real problem.
import java.util.*;
public class MyInsertionSort
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter anything you want");
String insertionSort = in.nextLine();
int num=Integer.parseInt(insertionSort);
String array[] = new String [num];
for (int i = 0; i < array.length; i++)
{
System.out.print("Input the Number at array index "+i+": ");
array[i] = in.nextLine();
}
public static void insertionSort(int array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) )
{
array [i+1] = array [i]; i--;
}
array[i+1] = key;
printNumbers(array);
}
}
}
Generic type Insertion Sort
I did a quick check and fixed all of the errors. Just compare your code and this one in a comparing tool. So that you can learn what you missed. This code is capable of doing sorting with Multiple data types like String, double, int as of now. It can be altered for any object that implements comparable.
Below is working code
import java.util.Scanner;
public class MyInsertionSort
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter data type to sort : ");
String type = in.nextLine();
System.out.print("Enter number of elements : ");
String insertionSort = in.nextLine();
int num=Integer.parseInt(insertionSort);
String array[] = new String[num];
for (int i = 0; i < array.length; i++)
{
System.out.print("Input the Number at array index "+i+": ");
array[i] = in.nextLine();
}
MyInsertionSort.insertionSortByType(array,type);
in.close();
}
public static void insertionSortByType(String array[], String type)
{
switch (type) {
case "double":
Double[] ConvertedArrayDouble = new Double[array.length];
for (int i = 0; i<array.length; i++) ConvertedArrayDouble[i] = Double.parseDouble(array[i]);
MyInsertionSort.insertionSort(ConvertedArrayDouble);
break;
case "int":
Integer[] ConvertedArrayInt = new Integer[array.length];
for (int i = 0; i<array.length; i++) ConvertedArrayInt[i] = Integer.parseInt(array[i]);
MyInsertionSort.insertionSort(ConvertedArrayInt);
break;
default:
MyInsertionSort.insertionSort(array);
}
}
public static <E extends Comparable<? super E>> void insertionSort(E array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
E key = array[j];
int i = j-1;
while ( (i > -1) && ( array[i].compareTo(key) > 0 ) )
{
array [i+1] = array [i]; i--;
}
array[i+1] = key;
}
printNumbers(array);
}
public static <E> void printNumbers(E array[]) {
for (E i : array) {
System.out.println(i);
}
}
}

My sort method and find/count method are messing up and I have no idea what's wrong?

I have to write a program that sorts names alphabetically while removing duplicates and counting the amount of times the names appear and capitalizes all of it. My partner and I have been working on this and have found no way to have the sorting method work properly and have the program find and count the times the names appear. We have to use certain methods to do this...which I linked the pdf down at the bottom. I really want to understand what's wrong and why the output is not coming out right.
public class Names {
/**
* #param args the command line arguments
*/
static ArrayList<String> fnArray = new ArrayList<String>();
static ArrayList<String> lnArray = new ArrayList<String>();
public static void main(String[] args) throws IOException {
// TODO code application logic here
getNames(fnArray, lnArray);
sort(lnArray);
find(fnArray,1);
capitalize(fnArray,lnArray);
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What file would you like to read from ?: ");
String n = kb.next();
File inputFile = new File(n);
Scanner in = new Scanner(inputFile);
while (in.hasNext()) {
String firstName = in.next();
fn.add(firstName);
String lastName = in.next();
ln.add(lastName);
}
for (int i = 0; i < fnArray.size(); i++) {
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}
public static void capitalize(ArrayList<String> fnArray, ArrayList<String> lnArray) {
String capfn = " ";
String capln = " ";
int i = 0;
int j = 0;
System.out.println("****************Names***************");
while (i < fnArray.size() && j < lnArray.size()) {
capfn = fnArray.get(i);
capln = lnArray.get(j);
String capFname = capfn.substring(0, 1).toUpperCase() + capfn.substring(1).toLowerCase();
String capLname = capln.substring(0, 1).toUpperCase() + capln.substring(1).toLowerCase();
fnArray.set(i, capFname);
lnArray.set(i, capLname);
System.out.println(lnArray.get(j) + ", " + fnArray.get(i));
i++;
j++;
}
}
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
int count = 0;
for (String str : a) {
if (str.equalsIgnoreCase(s))
count++;
}
return count; }
public static void removeDuplicates(ArrayList<String> s) {
for (int j = 0; j < s.size(); j++) {
int i = -1;
while ((i = find(s, j)) >= 0) {
s.remove(i);
}
}
}
public static void backwards(ArrayList<String> names) {
for (int i = names.size() - 1; i > 0; i--) {
names.get(i);
for (int j = 0; j < names.size(); i++) {
if ((names.get(i).equals(names.get(j)))) {
names.remove(i);
}
}
}
}
public static void sort(ArrayList<String> array) {
for (int i = 1; i < array.size(); i++) {
// find the index of the ith smallest value
int s = i - 1;
for (int j = i; j < array.size(); j++) {
if (array.get(j).compareTo(array.get(s)) < 0) {
s = j;
}
}
// swap the ith smallest value into entry i-1
String temp = array.get(i - 1);
array.set(i - 1, array.get(s));
array.set(s, temp);
}
}
public static void showUnique(ArrayList<String> names){
System.out.println("Unique name list contains:");
for(int i=0 ;i< names.size() ;i++){
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}}
You can use the Collections.sort() method to sort an array list; once it is sorted, you will have entries like this:
ArrayList = { "Alpha", "Beta", "Beta", "Gamma", "Theta", "Theta" ... }
The important point to note, however, is that the duplicates will be next to each other in the sorted array.
Finally, if you want to remove duplicates, you can put all the elements of the ArrayList into a Set: set is a data-structure which removes duplicates.
Example:
Set<String> foo = new HashSet<String>( yourArrayList );
EDIT: Use this approach which is both: easy and simple-to-comprehend.
for( int i = 0; i < array.size() - 1; i++ )
{
for( int j = i + 1; j < array.size(); j++ )
{
if( array[i] > array[j] )
{
// Swap the contents of array[i] and array[j].
}
}
}

Count variable not working

I am writing a program to take in a tweet as input and return a value of the unique hashtags used in the tweet. However in the countUniqueHashtags method, my hashtagCount variable will only return a value of 1 if the input contains hashtags(even if there is more than one) and a value of 0 if the input doesn't contain any hashtags.
public class UniqueHashtagCounter
{
static ArrayList<String> uniqueHashTags = new ArrayList<String>();
int numberOfTweetsToFollow;
public String tweetSpace = "";
Scanner in = new Scanner(System.in);
public int getTweetsToFollow()
{
System.out.println("Enter the number of Tweets you wish to follow: ");
numberOfTweetsToFollow = in.nextInt();
return numberOfTweetsToFollow;
}
public String tweetsInput()
{
for(int i = 0; i <= numberOfTweetsToFollow ; ++i)
{
if(in.hasNextLine()){
tweetSpace = tweetSpace + in.nextLine();
}
}
return tweetSpace;
}
public ArrayList<String> populateArray()
{
uniqueHashTags.add(tweetSpace);
for(String s: uniqueHashTags)
s.toLowerCase().split(" ");
for(int x = 0; x < uniqueHashTags.size(); x++){
countUniqueHashtags(uniqueHashTags);}
return uniqueHashTags;
}
static void countUniqueHashtags(ArrayList<String> strings)
{
int hashtagCount = uniqueHashTags.size();
ListIterator<String> listIterator = strings.listIterator();
while(listIterator.hasNext())
{
String e = listIterator.next();
if(e.startsWith("#"))
hashtagCount = hashtagCount + 1;
}
System.out.println("The number of unique hashtags is: " + hashtagCount);
}
"My hashtagCount variable will only return a value of 1 if the input contains hashtags(even if there is more than one) and a value of 0 if the input doesn't contain any hashtags"
That's because you are using startsWith():
if(e.startsWith("#"))
hashtagCount = hashtagCount + 1;
You need to loop through the string and count the hashtag characters:
for(int i=0; e.length();i++){
if(e.charAt(i)=='#') hashtagcount++;
}

Search large array for lowest number

Hey everyone so I have a very large array that has names and popularity ranks listed in them, and generally the lower the number the more popular that name is. I need a way to search through the array to find 20 of the lowest numbers for a certain decade. So let me show you what my list looks like and my code.
This is my list.
And here is my code:
Name
public class Name{
private String givenName;
private int[] ranks = new int[11];
public Name(String name, int[] popularityRanks){
givenName = name;
for (int i = 0; i < 11; i++){
ranks[i] = popularityRanks[i];
}
}
public String getName(){
return givenName;
}
public int getPop(int decade){
if (decade >= 1 && decade <= 11){
return ranks[decade];
}
else{
return -1;
}
}
public String getHistoLine(int decade){
String histoLine = ranks[decade] + ": ";
return histoLine;
}
public String getHistogram(){
String histogram = "";
for (int i = 0; i < 11; i++){
histogram += ranks[i] + ": " + this.getHistoLine(i)
+ "\n";
}
return histogram;
}
}
And then NameApp:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NameApp{
private static boolean validInput;
private static boolean stillWorking = true;
private static boolean validDecade;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException{
String[] nameArray = readNamesFile();
Name[] list = new Name[nameArray.length];
loadNames(list, nameArray);
char choice;
do {
do {
displayMenu();
choice = getUserInput();
} while (!validInput);
switch (choice){
case 'A':
displayHistogram(list);
break;
case 'B':
compareTwoNames(list);
break;
case 'C':
displayTopTenNames(list);
break;
case 'D':
writeAnomaliesToFile(list);
stillWorking = false;
break;
default:
break;
}
} while (stillWorking);
}
private static String[] readNamesFile() throws FileNotFoundException{
String[] nameArray = new String[4429];
Scanner inputStream = null;
String fileName = "names.txt";
inputStream = new Scanner (new File(fileName));
int i = 0;
while (inputStream.hasNextLine()){
nameArray[i] = inputStream.nextLine();
i++;
}
inputStream.close();
return nameArray;
}
private static void loadNames(Name[] list, String[] nameArray){
int length;
int spacePos;
int[] popRanks = new int[11];
String name;
String linePop;
for (int i = 0; i < nameArray.length; i++){
length = nameArray[i].length();
spacePos = nameArray[i].indexOf(" ");
name = nameArray[i].substring(0,spacePos);
linePop = nameArray[i].substring(spacePos + 1, length);
for (int j = 0; j < 11; j++){
popRanks[j] = Integer.parseInt(linePop.split(" ")[j]);
}
list[i] = new Name(name, popRanks);
}
}
private static void displayMenu(){
System.out.println("Enter the character corresponding to your selection:");
System.out.println("\ta - Print histogram for a name");
System.out.println("\tb - Compare two names in a decade");
System.out.println("\tc - Print top ten names for a decade");
System.out.println("\td - Quit (display file anomalies)");
}
private static char getUserInput(){
String selection = keyboard.nextLine();
System.out.println(" Your selection: " + selection);
checkUserInput(selection);
char choice = stringToChar(selection);
return choice;
}
private static boolean checkUserInput(String selection){
if (!selection.equalsIgnoreCase("a") && !selection.equalsIgnoreCase("b") && !selection.equalsIgnoreCase("c") && !selection.equalsIgnoreCase("d")){
System.out.println("Invalid input. Try again...");
return validInput = false;
}
else {
return validInput = true;
}
}
private static char stringToChar(String selection){
char choice = selection.charAt(0);
choice = Character.toUpperCase(choice);
return choice;
}
private static void displayHistogram(Name[] list){
String nameInput;
String histogram;
int nameLocation;
nameInput = nameEntry();
nameLocation = checkListArray(nameInput, list);
histogram = list[nameLocation].getHistogram();
System.out.println("Histogram for name, " + list[nameLocation].getName() + ":");
System.out.println(histogram);
}
private static void compareTwoNames(Name[] list){
String nameOne;
String nameTwo;
String oneHistoLine;
String twoHistoLine;
int oneLocation;
int twoLocation;
int decade;
nameOne = nameEntry();
oneLocation = checkListArray(nameOne, list);
nameTwo = nameEntry();
twoLocation = checkListArray(nameTwo, list);
decadeMenu();
decade = decadeSelection();
oneHistoLine = list[oneLocation].getHistoLine(decade);
twoHistoLine = list[twoLocation].getHistoLine(decade);
System.out.println("Data for " + list[oneLocation].getName());
System.out.println(" " + oneHistoLine);
System.out.println("Data for " + list[twoLocation].getName());
System.out.println(" " + twoHistoLine);
}
private static void displayTopTenNames(Name[] list){
int decade;
int temp = 1000;
int tempTwo;
String[] topTen = new String[20];
decadeMenu();
decade = decadeSelection();
for (int i = 0; i < 20; i++){
for (int j = 0; j < list.length; j++){
if (list[j].getPop(decade) > 0 && list[j].getPop(decade) < temp){
temp = list[j].getPop(decade);
tempTwo =
}
}
}
}
private static void writeAnomaliesToFile(Name[] list){
}
private static String nameEntry(){
String nameInput = "";
System.out.println("Enter a name: ");
nameInput = keyboard.nextLine();
return nameInput;
}
private static int checkListArray(String nameInput, Name[] list){
int nameLocation = -1;
int listLength = list.length;
for (int i = 0; i < listLength; i++){
if (nameInput.equalsIgnoreCase(list[i].getName())){
return nameLocation = i;
}
}
if (nameLocation == -1){
System.out.println("The name, " + nameInput + ", was not found!");
return nameLocation;
}
return nameLocation;
}
private static void decadeMenu(){
System.out.println("Enter number correpsonding to your decade:");
System.out.println(" 1 - 1900-1909");
System.out.println(" 2 - 1910-1919");
System.out.println(" 3 - 1920-1929");
System.out.println(" 4 - 1930-1939");
System.out.println(" 5 - 1940-1949");
System.out.println(" 6 - 1950-1959");
System.out.println(" 7 - 1960-1969");
System.out.println(" 8 - 1970-1979");
System.out.println(" 9 - 1980-1989");
System.out.println(" 10 - 1990-1999");
System.out.println(" 11 - 2000-2005");
}
private static int decadeSelection(){
String decadeChoice;
int decade;
do {
System.out.println("Enter a decade: ");
decadeChoice = keyboard.nextLine();
decade = checkDecade(decadeChoice);
} while (!validDecade);
return decade;
}
private static int checkDecade(String decadeChoice){
int decade = 0;
try {
decade = Integer.parseInt(decadeChoice);
}
catch (Exception e){
System.out.println("That is not an integer. Please try again.");
return decade;
}
if (decade < 1 || decade > 11){
System.out.println("Enter an integer between 1 and 11");
validDecade = false;
return decade;
}
else {
validDecade = true;
return decade;
}
}
}
so where I need help at is the displayTopTenNames method. I was sort of messing around with it a bit earlier but every loop that I have come up with always makes duplicates that I don't want... Anyway my output should look like this:
Ten most popular names (male and female) during the decade 1910-1919 were:
John (1) Mary (1)
Helen (2) William (2)
Dorothy (3) James (3)
Margaret (4) Robert (4)
Joseph (5) Ruth (5)
George (6) Mildred (6)
Anna (7) Charles (7)
Edward (8) Elizabeth (8)
Frances (9) Frank (9)
Marie (10) Walter (10)
so yeah help would be much appreciated and thanks in advance.
There are probably more efficient ways to do this, but this shows the theory. You maintain a small list of 20 items. You scan your large list to see if its a candidate for your short list. If the list is small than 20, anything gets added. If it has reached 20, you check to see if anything in the list is larger than the item you would like to add. if it is, this item is evicted and replaced with the smaller value.
public class Low20 {
private List<Integer> list = new ArrayList<Integer>();
public static final void main(String[] args) {
new Low20();
}
public Low20() {
Random random = new Random();
for (int x=0;x<100000;x++) {
add(random.nextInt(100000));
}
System.out.println(list);
}
public void add(int value) {
if (list.size() < 20) {
list.add(value);
} else {
for (int x=0;x<list.size();x++) {
if (list.get(x) > value) {
list.remove(x);
list.add(value);
return;
}
}
}
}
}
The result. (random numbers, but the lowest 20). You could then sort these, or incorporate sort into the eviction algorithm.
[6, 0, 5, 17, 18, 11, 10, 27, 22, 27, 28, 16, 34, 33, 0, 8, 28, 0, 15, 14]
The benefit of this method over using a blanket sort on your list, is that your list doesn't have to fit in memory and can be applied from a file or database scan.
Check out Arrays.sort() method:
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

Categories