I have an input file called input.txt with a list of names. I have no problem displaying all the names and putting them in alphabetical order with both display and sort methods. But what I am currently struggling to do is create a method where I can count the recurrence of each name in the file. I would grealty appreciate if anyone could help me with this, and find a way to create this method.
public class Names {
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
for (int i = 0; i < a.size(); i = i + 1) {
String str = a.get(i);
if (str.equals(s)) {
return i;
}
}
return -1;
}
public static void capitalize(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
String name = names.get(i);
if (!name.isEmpty()) {
String firstLetter = "" + name.charAt(0);
names.set(i, firstLetter.toUpperCase() + name.substring(1).toLowerCase());
}
}
}
public static void sort(ArrayList<String> names) {
for (int i = 0; i < names.size() - 1; i = i + 1) {
int Min = i;
for (int j = i + 1; j < names.size(); j = j + 1) {
if (names.get(j).compareTo(names.get(Min)) < 0) {
Min = j;
}
}
String tmp = names.get(i);
names.set(i, names.get(Min));
names.set(Min, tmp);
}
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What is the input flie?");
String names = kb.next();
File inpFile = new File(names);
Scanner in = new Scanner(inpFile);
while (in.hasNext()) {
String firstName = in.next();
String lastName = in.next();
fn.add(firstName);
ln.add(lastName);
}
}
private int countOccurence(String name, ArrayList<String> names){
int count = 0;
for(int i =0; i <= names.size; i++){
if(name.equalsIgnoreCase(names.get(i))){
count++;
}
}
return count;
}
public static void main(String[] args) throws IOException {
ArrayList<String> first = new ArrayList<>();
ArrayList<String> last = new ArrayList<>();
getNames(first, last);
capitalize(first);
capitalize(last);
ArrayList<String> allNames = new ArrayList<>();
for (int i = 0; i < first.size(); i++) {
allNames.add(last.get(i) + ", " + first.get(i));
}
System.out.println("*******All Names******");
sort(allNames);
display(allNames);
System.out.println("*****First Name Count***");
for(int i =0; i <= first.size; i++){
int count = countOccurence(first.get(i), first);
System.out.println(first.get(i) + " occured " + count + " times.");
}
System.out.println("****Last Name Count****");
sort(last);
display(last);
}
}
Use Map structure for those case:
Map<String, Integer> recurence = new HashMap<>();
int count;
for (String name : names) {
if (recurence.containsKey(name)) {
count = recurence.get(name) + 1;
} else {
count = 1;
}
recurence.put(name, count);
}
create a method that counts the occurences:
public static int countOccurence(String name, ArrayList<String> names){
int count = 0;
for(int i =0; i <= names.size(); i++){
if(name.equalsIgnoreCase(names.get(i))){
count++;
}
}
return count;
}
To use it, go through the loop in you Main ( or you can create another method)
for(int i =0; i <= first.size; i++){
int count = countOccurence(first.get(i), first);
System.out.println(first.get(i) + " occured " + count + " times.");
}
Related
I'm a beginner and I'm having trouble trying to display the output so that if its too big it will move it to the next line.
This is what I have so far:
import java.util.Scanner;
public class numberBracket {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("howMany: ");
int howMany = scanner.nextInt();
System.out.println("lineLength: ");
int lineLength = scanner.nextInt();
scanner.nextLine();
printNumbers(howMany, lineLength);
}
public static void printNumbers(int howMany, int lineLength) {
Integer charLength = Integer.valueOf(lineLength);
for(int i = 1; i <= howMany; i ++) {
String t = "[" + i + "]";
while(t.length() > charLength ) {
int index = t.lastIndexOf(' ', charLength);
System.out.print(t.substring(0, index));
t = t.substring(index + 1);
}
System.out.print(t);
}
}
}
So if they enter 10 for the lineLength it would be
[1][2][3]
[4]
and if they entered 12 it would be
[1][2][3][4]
You can use this snippet:
public static void printNumbers(int howMany, int lineLength) {
StringBuilder sb = new StringBuilder();
int length = 0;
for (int i = 1; i <= howMany; i++) {
String t = "[" + i + "]";
if (length + t.length() > lineLength) {
sb.append("\n");
length = 0;
}
length += t.length();
sb.append(t);
}
System.out.println(sb.toString());
}
public static void printNumbers(int howMany, int lineLength) {
String printed = "";
for (int i = 1; i <= howMany; i++) {
String t = "[" + i + "]";
if ((printed.length() + t.length()) > lineLength) {
printed = "";
System.out.println();
}
printed += t;
System.out.print(t);
}
}
I believe you have to check if it has room in the current line before printing.
If it does have room print it, if it doesn't, print in a new line.
public static void printNumbers(int howMany, int lineLength) {
int alreadyPrintedLength = 0;
for(int i = 1; i <= howMany; i ++) {
String t = "[" + i + "]";
int actualCharLength = t.length();
boolean hasRoomInCurrentLine = (alreadyPrintedLength + actualCharLength) <= lineLength;
if (hasRoomInCurrentLine) {
System.out.print(t);
alreadyPrintedLength += actualCharLength;
} else {
System.out.print(System.lineSeparator() + t);
alreadyPrintedLength = actualCharLength;
}
}
}
I am receiving this error when I submit my code. This only happens when I submit my code on an online compiler necessary for my course, however, when I run my code via InteliJ it compiles properly.
Main.java:335: error: cannot find symbol
while (!(TeamMember.contains("Stop"))){
^
symbol: method contains(String)
location: class TeamMember
1 error
<
My classes are as follows:
Main:
package com.company;
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String name = "";
String id = "";
ArrayList<TeamMember> list = new ArrayList<>();
while (!(TeamMember.contains("Stop"))) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name: ");
name = scan.nextLine();
System.out.println("Please enter the id: ");
id = scan.nextLine();
list.add(new TeamMember(name.toLowerCase(), id));
System.out.println(Main.selectionSort(list));
}
int size = list.size();
for (int j = size; j > (list.size() + 2); j--) {
list.remove(j);
}
}
public static ArrayList<TeamMember> selectionSort(ArrayList<TeamMember> list) {
TeamMember[] teamArray = new TeamMember[list.size()];
for (int i = 0; i < list.size(); i++) {
teamArray[i] = list.get(i);
}
for (int i = 0; i < teamArray.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < teamArray.length; j++) {
if (teamArray[j].compareTo(teamArray[minIndex]) < 0) {
minIndex = j;
}
}
TeamMember holder = teamArray[i];
teamArray[i] = teamArray[minIndex];
teamArray[minIndex] = holder;
}
for (int i = 0; i < list.size(); i++) {
list.set(i, teamArray[i]);
}
return list;
}
}
TeamMember:
package com.company;
import java.util.ArrayList;
class TeamMember{
private String fullName;
private String idString;
public TeamMember(String name, String id){
fullName = "";
name = name.toLowerCase();
String [] charName = new String[name.length()];
for(int i = 0; i < charName.length; i++){
charName[i] = Character.toString(name.charAt(i));
if(i == 0){
charName[0] = charName[0].toUpperCase();
}
}
for(int i = 0; i < charName.length - 1; i++){
if(charName[i].equals(" ") && !charName[i + 1].equals(" ")){
charName[i + 1] = charName[i + 1].toUpperCase();
}
}
for(int i = 0; i < charName.length; i++){
fullName = fullName + charName[i];
}
idString = id;
}
public static boolean contains(String stop) {
return false;
}
public String getID(){
return idString;
}
public String toString(){
return fullName;
}
public int compareTo(TeamMember other){
if(idString.compareTo(other.getID()) < 0){
return -1;
}
else if(idString.compareTo(other.getID()) > 0){
return 1;
}
else{
return 0;
}
}
}
It looks like class TeamMember is not accessible from your Main class. Try this code as it should work having the classes in the same file.
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args) {
String name = "";
String id = "";
ArrayList<TeamMember> list = new ArrayList<>();
while (!(TeamMember.contains("Stop"))) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name: ");
name = scan.nextLine();
System.out.println("Please enter the id: ");
id = scan.nextLine();
list.add(new TeamMember(name.toLowerCase(), id));
System.out.println(Main.selectionSort(list));
}
int size = list.size();
for (int j = size; j > (list.size() + 2); j--) {
list.remove(j);
}
}
public static ArrayList<TeamMember> selectionSort(ArrayList<TeamMember> list) {
TeamMember[] teamArray = new TeamMember[list.size()];
for (int i = 0; i < list.size(); i++) {
teamArray[i] = list.get(i);
}
for (int i = 0; i < teamArray.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < teamArray.length; j++) {
if (teamArray[j].compareTo(teamArray[minIndex]) < 0) {
minIndex = j;
}
}
TeamMember holder = teamArray[i];
teamArray[i] = teamArray[minIndex];
teamArray[minIndex] = holder;
}
for (int i = 0; i < list.size(); i++) {
list.set(i, teamArray[i]);
}
return list;
}
}
class TeamMember{
private String fullName;
private String idString;
public TeamMember(String name, String id){
fullName = "";
name = name.toLowerCase();
String [] charName = new String[name.length()];
for(int i = 0; i < charName.length; i++){
charName[i] = Character.toString(name.charAt(i));
if(i == 0){
charName[0] = charName[0].toUpperCase();
}
}
for(int i = 0; i < charName.length - 1; i++){
if(charName[i].equals(" ") && !charName[i + 1].equals(" ")){
charName[i + 1] = charName[i + 1].toUpperCase();
}
}
for(int i = 0; i < charName.length; i++){
fullName = fullName + charName[i];
}
idString = id;
}
public static boolean contains(String stop) {
return false;
}
public String getID(){
return idString;
}
public String toString(){
return fullName;
}
public int compareTo(TeamMember other){
if(idString.compareTo(other.getID()) < 0){
return -1;
}
else if(idString.compareTo(other.getID()) > 0){
return 1;
}
else{
return 0;
}
}
}
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 + ".");
}
}
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].
}
}
}
This is what I want :
Let the user enter as many numbers as they want until a non number is entered (you may
assume there will be less than 100 numbers). Find the most frequently entered number. (If
there are more than one, print all of them.)
Example output:
Input: 5
Input: 4
Input: 9
Input: 9
Input: 4
Input: 1
Input: a
Most common: 4, 9
I have got to the point in my code where I have managed to find out which are the most common numbers. However, I don't want to print out the same number over and over again; example from above: Most common: 4, 9, 9, 4
What needs to be done?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
Found the solution!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
you could use the hash table for this to store the frequenceis as the limit is very less i.e. less than 100.
pseudo code would be like:
vector<int> hash(101)
cin>>input
if(isnumeric(input))
hash[input]++
else{
max=max_element(hash.begin(),hash.end());
for(int i=0;i<100;i++)
if(hash[i]==max)
print i
}
Set<Integer> uniqueMaxOccur = new HashSet<Integer>();
for (int i = 0; i < size ; i++) {
if(occur[i] == maxOccur) {
//System.out.println(input[i]);
uniqueMaxOccur.add(input[i]);
}
}
and display the values in the set
You can use a Set and store the values already printed.
What about something like this?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<string,int> numberLookup = new HashMap<string,int>();
Boolean doContinue = true;
while (doContinue)
{
System.out.print("Input: ");
String input = in.readLine();
if (isNumeric(input))
{
if (!numberLookup.containsKey(input))
numberLookup.put(input,1);
else
numberLookup.put(input, numberLookup.get(input) + 1);
}
else
doContinue = false;
}
maxOccur = numberLookup.values().max();
System.out.print("These numbers were all entered " + maxOccur + " times:");
Iterator it = numberLookup.entrySet().iterator();
while (it.hasNext())
{
(Map.Entry)it.next();
System.out.println(pairs.getKey());
}
}
Sorry, I'm a C# person and don't have a Java compiler on me, so this might need some tweaking.