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);
}
}
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.
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++;
}
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].
}
}
}
I am trying to compare two values present in two different arrays but I end up getting the " Array required but Integer found " compile time error . I am really not able solve this. I have marked the line from where the error was coming. It would be very appreciable if anybody can help me out with this. Here is the code .
public class Banker
{
int proccess, n, allocated[][], need[][], maximum[][], available[], safe[];
boolean done[];
public Banker(int n, int proccess) {
this.n = n;
this.proccess = proccess;
allocated = new int[n][n];
need = new int[n][n];
maximum = new int[n][n];
safe = new int[proccess];
done = new boolean[proccess];
}
public void getSafeSequence() {
int result = 0;
for (int i = 0; i < proccess; ++i) {
result = getLocation();
if (result != -1) {
safe[i] = result;
done[result] = true;
} else {
System.out.println(" No Safe Sequence Exist ");
break;
}
}
if (result != -1)
DisplaySequene();
}
public int getLocation() {
boolean flag = true;
for (int i = 0; i < proccess; ++i) {
if (done[i] != true) {
flag = true;
for (int j = 0; j < n; ++j)
***if (available[i][j] < need[i][j])*** {
flag = false;
break;
}
}
if (flag)
return i;
}
return -1;
}
}
available is one dimensional array so you cannot write available[i][j]. Change it to smh like available[i]
You defined available[] as a one dimensional array and use it with two dimensions available[i][j].
I know this question was asked many times, but I didn't find any of the answers helpful in my case. I have a method that receives a String. I want to check if any of the characters in the string are repeated. If so the method will return an empty String. If not it will return the String back.
The method is looking for any repeated character in the String.
private String visit(String word) {
int count = 0;
if(word == ""){
return "<empty>";
}
//alphabet is an array that holds all characters that could be used in the String
for(int i = 0; i < alphabet.length; i++){
for(int j = 0; j < word.length(); j++){
if(alphabet[i] == word.charAt(j)){
count++;
}
if(count == 2){
return "";
}
}
count = 0;
}
return word;
}
Ok, I publish my solution to this:
package main;
import java.util.Arrays;
public class main {
public static void main(String[] args) {
System.out.println(hasDups("abc"));
System.out.println(hasDups("abcb"));
}
public static String hasDups(String arg) {
String[] ar = arg.split("");
Arrays.sort(ar);
boolean noDups = true;
for (int i = 1; i < ar.length && noDups; i++) {
if (ar[i].equals(ar[i-1])) noDups = false;
}
if (noDups) return arg; else return "";
}
}
This might not be the best way of doing what you want, but you can use two for loops to check each character against all the other characters to see if it is repeated.
public static String hasRepeated(String word) {
if (word.isEmpty()) return "<empty>";
char[] charArray = word.toCharArray();
for (int i = 0; i < charArray.length; i++) {
for (int j = 0; j < charArray.length; j++) {
if (i == j) {
} else if (Character.toString(charArray[i]).
equalsIgnoreCase(Character.toString(charArray[j]))) {
return "";
}
}
}
return word;
}
Note: This code assumes that the case of the character doesn't matter, it just checks if it is repeated.
/**
* Returns the index of the first character repeated, or -1 if no repeats
*/
public static int firstRepeated( String s ) {
if ( s != null ) {
int n = s.length();
for (int i = 0; i < (n - 1); i++) {
int indx = s.indexOf( s.charAt( i ), i + 1 );
if ( indx > 0 ) {
return i;
}
}
}
return -1;
}
This works!!
public static String checkDuplicate(String str)
{
int count = 0;
char[] charArray = str.toCharArray();
for(int i=0;i<charArray.length;i++)
{
count = 0;
for(int j=0;j<charArray.length;j++)
{
if(charArray[i]==charArray[j])
{
count++;
if(count==2) break;
}
}
if(count==2) break;
}
if(count==2)
return "";
else
return str;
}
}