import java.util.Scanner;
class candidate {
public String name;
public int count;
public candidate(String name) {
super();
this.name = name;
}
}
public class DayScholar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
candidate[] candidates = new candidate[3];
candidates[0] = new candidate("vikas");
candidates[1] = new candidate("ganesh");
candidates[2] = new candidate("teja");
System.out.print("No. of voters : ");
int voters = in.nextInt();
in.nextLine();
for (int i = 0; i < voters; i++) {
System.out.print("vote : ");
String name = in.nextLine().toLowerCase();
for (int j = 0; j < 3; j++) {
Here is the code, although if the statement is true else is also executing. How to check the condition
if (name.equals(candidates[j].name)) {
candidates[j].count++;
} else { **//problem here**
System.out.println("N");
break;
}
}
}
int highest = 0;
String winner = "";
for (int i = 0; i < 3; i++) {
if (candidates[i].count > highest) {
highest = candidates[i].count;
winner = candidates[i].name;
} else if (candidates[i].count == highest) {
winner += ("\n" + candidates[i].name);
}
}
System.out.println(winner);
}
}
Assuming the user enters a valid name, the following loop will increment the count field on the candidate with the matching name, and print N for the other 2 candidates.
for (int j = 0; j < 3; j++) {
if (name.equals(candidates[j].name)) {
candidates[j].count++;
} else {
System.out.println("N");
break;
}
}
To fix, you need the loop to just set the index of the matching candidate, then do the increment or printing after the loop:
int matchingIndex = -1; // -1 = not found
for (int j = 0; j < 3; j++) {
if (name.equals(candidates[j].name)) {
matchingIndex = j;
break;
}
}
if (matchingIndex == -1) {
System.out.println("N");
} else {
candidates[matchingIndex].count++;
}
Related
In the code below I have a double for loop resulting in a time complexity of O^2 in method getResponse(). This code prompts the user for a 10 integer sequence string and an uppercase sensitive pin. It then converts the pin to numbers on a phone pad ie. [ABC] --> 2, [DEF] --> 3. Lastly a response array is generated with each digit of the new phone pin corresponding to indexes of sequence. So input "0123456789","HAM", response = "426"
import java.util.Scanner;
public class Test {
public static final int SEQ_DIGITS = 10;
public static final String ERR_SEQ = "Invalid sequence";
public static final String ERR_PIN = "Invalid PIN";
public static int letterToPhone(char c) {
int phoneNumber = 0;
if (Character.toString(c).matches("[ABC]")) {
phoneNumber = 2;
} else if (Character.toString(c).matches("[DEF]")) {
phoneNumber = 3;
} else if (Character.toString(c).matches("[GHI]")) {
phoneNumber = 4;
} else if (Character.toString(c).matches("[JKL]")) {
phoneNumber = 5;
} else if (Character.toString(c).matches("[MNO]")) {
phoneNumber = 6;
} else if (Character.toString(c).matches("[PQRS]")) {
phoneNumber = 7;
} else if (Character.toString(c).matches("[TUV]")) {
phoneNumber = 8;
} else if (Character.toString(c).matches("[WXYZ]")) {
phoneNumber = 9;
}
return phoneNumber;
}
public static int[] getResponse(String pin, int[] values) {
int[] response = new int[pin.length()];
for(int i = 0; i < pin.length(); i++) {
for (int j = 0; j < values.length; j++) {
int x = letterToPhone(pin.charAt(i));
if(x == j) {
response[i] = values[j];
}
}
}
return response;
}
public static boolean stringIsLengthK(String s, int k) {
boolean isLength = false;
if (s.length() == k) {
isLength = true;
}
return isLength;
}
public static boolean allDigits(String s) {
boolean isDigit = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isDigit(s.charAt(i)))) {
isDigit = false;
break;
}
}
return isDigit;
}
public static boolean allUppercaseLetters(String s) {
boolean isUpper = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isUpperCase(s.charAt(i)))) {
isUpper = false;
break;
}
}
return isUpper;
}
public static int[] digitStringToIntArray(String s) {
int[] arrayS = new int[s.length()];
for(int i = 0; i < arrayS.length; i++) {
for(int j = 0; j < SEQ_DIGITS; j++) {
if (((int) s.charAt(i) - 48) == j) {
arrayS[i] = j;
}
}
}
return arrayS;
}
public static int countValues(int value, int[] values) {
int count = 0;
for(int i = 0; i < values.length; i++) {
if(value == values[i]) {
count++;
}
}
return count;
}
public static int numPossible(int[] response, int[] values) {
int product = 1;
int[] count = new int[response.length];
for (int i = 0; i < count.length; i++) {
count[i] = countValues(response[i], values);
}
for(int i=0; i<response.length; i++){
product = product * count[i];
}
return product;
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.printf("Enter value sequence: ");
final String seq = in.nextLine();
System.out.printf("Enter PIN: ");
final String pin = in.nextLine();
if (!(allUppercaseLetters(pin))) {
throw new AssertionError(ERR_PIN);
} else if (!(allDigits(seq)) || !(stringIsLengthK(seq, SEQ_DIGITS))) {
throw new AssertionError(ERR_SEQ);
}
int[] seqArray = new int[SEQ_DIGITS];
seqArray = digitStringToIntArray(seq);
int[] response = new int[SEQ_DIGITS];
response = getResponse(pin, seqArray);
System.out.printf("Response: ");
for (int i = 0; i < response.length; i++) {
System.out.printf("%d", response[i]);
}
System.out.printf("%n");
numPossible(response, seqArray);
} catch (Error e) {
System.out.println(e.getMessage());
}
}
}
I want to be to able to accommodate larger sequence numbers without a scaling of n^2. Is there a way to change the for loop to instead compare the int x = letterToPhone(pin.charAt(i)); value in getResponse() to a range of integers such as "[0-9]"
One easy optimization of constant factors is to move the call to letterToPhone() out of the inner loop.
And yes, you can compare the x value to a range, eliminating the need for the inner loop.
for(int i = 0; i < pin.length(); i++) {
int x = letterToPhone(pin.charAt(i));
if ( (0 <= x) && (x < values.length)) {
response[i] = values[x];
}
}
Another optimization of constant factors would be to replace all the function calls in letterToPhone() with a switch statement. The compiler may choose to optimize that into a table lookup.
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 trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.
this is an array of process, that have inforamtion like, number of proces, name and sex
private String process[][] = {
{"0001", "Maria Gomes", "Feminino"},
{"0002", "José Santos", "Masculino"},
{"0003", "João Oliveira", "Masculino"}};
and I have doubt here, to get the next new number of process, in array is 0003, and the next is 0004
public String getNewNextNumberOfProcess() {//
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process[i].length; j++) {
return process[i][j];
}
}
return "-1";
}
and I have doubt here, in create process
public boolean createProcess(String number_process, String name, String sex) {
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process[i].length; j++) {
//add number of process
process[i][0] += number_process;
//add name
process[i][1] += name;
//add sex
process[i][2] += sex;
return true;
}
}
return false;
}
and I have doubt here, in delete process
public boolean deleteProcess(String numberProcess) {
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process[i].length; j++) {
//if number of process is the same in array of process
if(numberProcess.equals(process[i][j])){
//delete all information associated with number of process
process[i][j] -= process[i][0];
//return true
return true;
}
}
}
return false;
}
public String getNewNextNumberOfProcess() {//
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process[i].length; j++) {
return process[i][j];
}
}
return "-1";
}
Will always return process[0][0] during the first iteration of the j for loop inside the i for loop.
May I suggest using a different data structure. What if you used a Map with the process as the key and an array with the name and sex as the value?
Here is some more information on Maps.
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
I think it would be better if you create a Process class and implement it like this:
private Map<Integer, Process> processes = new HashMap<Integer, Process>;
public class Process
{
public int processId;
public string processName;
public string processSex;
}
public void AddProcess(Process process)
{
if (processes.get(process.processId) == null)
{
processes.put(process.processId, process);
}
}
public void DeleteProcess(Process process)
{
if (processes.get(process.processId) != null)
{
processes.remove(process.processId);
}
}
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.