String comparison not showing all matching results - java

I am working on a piece of code that is supposed to move elements of a class array (users) to a new array (ordered) if the user's "ordered" parameter is set as Y. The code will work for a few users, but for most it just skips over them. Why is this? Am I comparing the strings wrong or is there something else that I am not aware of?
System.out.println("List of ordered phones:");
for(int i = 0; i < users.length; i++) {
if(users[i].ordered.equals("Y")) {
ordered[i] = users[i];
System.out.println(ordered[i].name);
}
}
This is the loop in question. There isn't much to it other than the string comparison but even that is pretty straight forward.
Here is the entire program:
class User{
String name;
String phoneNum;
String current;
String type;
String requested;
String location;
String ordered;
User(String name, String phoneNum, String current, String type, String requested, String location, String ordered){
this.name = name;
this.phoneNum = phoneNum;
this.current = current;
this.type = type;
this.requested = requested;
this.location = location;
this.ordered = ordered;
}
public User() {
}
}
public class readWrite {
#SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) throws FileNotFoundException {
User[] users = new User[149];
User[] ordered = new User[149];
User[] received = new User[149];
User[] trade = new User[149];
int count = 0;
File file = new File("I don't like showing my file path but it's correct");
Scanner scan = new Scanner(file);
while(scan.hasNextLine()) {
User user = new User(scan.nextLine(), scan.nextLine(), scan.nextLine(), scan.nextLine(), scan.nextLine(), scan.nextLine(), scan.nextLine());
users[count] = user;
count++;
}
User temp;
for(int i = 0; i < users.length; i++) {
for(int j = 0; j < users.length; j++) {
if(users[i].name.charAt(0) < users[j].name.charAt(0)) {
temp = users[i];
users[i] = users[j];
users[j] = temp;
}
}
}
for(int i = 0; i < users.length; i++) {
System.out.println(i + "." + " Name: " + users[i].name + "\n" + "Phone Number: " + users[i].phoneNum + "\n" + "Current Phone: " + users[i].current + "\n" + "Phone Type: " + users[i].type + "\n" + "Requested Phone: " + users[i].requested + "\n" + "Location: " + users[i].location + "\n" + "Ordered?: " + users[i].ordered + "\n\n");
}
System.out.println("List of ordered phones:");
for(int i = 0; i < users.length; i++) {
if(users[i].ordered.equals("Y")) {
ordered[i] = users[i];
System.out.println(ordered[i].name);
}
}

Is it possible that they're skipped because they do not meet the following condition?
if(users[i].ordered.equals("Y"))

I figured it out. In the 3 for loops, instead of i, I needed to use "ord","rec", and "traded" so that no null entries go into the filtered arrays. When I was using i as the index it was inserting null values because i always grows even if the condition isn't met.

Related

How to convert string of the form {a=2 ,b=5} to JSON of the form {"a":2 , "b":5} in java?

I am getting result in the form {a=2 ,b=5} after spel expression evaluation.
I want to convert it to json.
How do I do it?
Please help!
here is your solution:
public static void main(String[] args) {
String something = "{a=2 ,b=5}";
something = something.replace("{", "");
something = something.replace("}", "");
String[] pairs = something.split(",");
ArrayList<String> list = new ArrayList<String>();
for (String pair : pairs) {
list.add(pair);
}
for (int i = 0; i < list.size(); i++) {
String[] temp = list.get(i).split("=");
temp[0] = "\"" + temp[0] + "\"";
list.set(i, temp[0] + ":" + temp[1]);
}
String contents = "";
for (int i = 0; i < list.size(); i++) {
contents = contents + ", " + list.get(i);
}
contents = contents.replaceFirst(", ", "");
contents = "{" + contents + "}";
System.out.println("Contents: " + contents);
}
And here is your result:
Contents: {"a":2 , "b":5}

Removing statics from project

Is their an easy way to pass the variables and arrays between these methods without having a super long method signature? Currently I am using these statics but I know that's not the "correct" way of doing it but if I pass them in the signature it starts to make everything look ugly. So what would be the "correct" way to pass the variables like lastName, firstName, and role?
// Program wide variables
//static String firstName; // First name from the file
static String lastName; // Last name from the file
static String username; // Username
static String password;
static String role;
static String email;
static String answersFile; // Answers file in use with path and ext
static String[] answeredQ = new String[questAsks]; // Recording the question asked
static Boolean[] answeredA = new Boolean[questAsks]; //Recording users answer
static Boolean[] answeredC = new Boolean[questAsks]; //Recording the correct answer
public static void main(String Args[]) throws FileNotFoundException, IOException {
// Main method that contains major control functions; a quick summary of the program; magic
}
public static void quiz(String testType) throws HeadlessException, IOException {
String testBankFile = path + testType + ".txt";
Random rand = new Random();
int questionCount = 0, right = 0, wrong = 0;
long startTime = System.currentTimeMillis(); // Setting the start time in milliseconds
while (questionCount < questAsks) { // Loop that will ask all the questions
int r = rand.nextInt(getLines(testBankFile));
boolean ans = promptQuestion(read(r, testBankFile), questionCount + 1); // For some reason this makes it work
answeredQ[questionCount] = read(r, testBankFile);
answeredA[questionCount] = ans;
answeredC[questionCount] = parseA(read(r, answersFile));
if (ans != parseA(read(r, answersFile))) {
wrong++;
} else if (ans == parseA(read(r, answersFile))) {
right++;
}
questionCount++;
}
JOptionPane.showMessageDialog(null, "You got " + wrong + " wrong and " + right + " correct.");
long endDiff = (System.currentTimeMillis() - startTime);
makeReport(firstName, lastName, username, printTime(endDiff), testType, right);
}
// Generates a report report(first, last, score, time, array of answers)
public static void makeReport(String first, String last, String user, String time, String testType, int score) throws IOException {
DateFormat dateF = new SimpleDateFormat(dateFormat);
Date date = new Date();
String fileName = user + "_COSC236_Quiz_" + dateF.format(date) + ".txt";
File file = new File(fileName);
file.createNewFile();
FileWriter out = new FileWriter(fileName);
double percent = (((double) score) / ((double) questAsks) * 100);
out.write("Name: " + first + " " + last + "\n");
out.write("Score: " + percent + "%\n");
out.write("Elapsed time: " + time + "\n");
out.write("Test type: " + testType + "\n");
out.write("---------------------------------------------------------------------\n");
out.write(" Users\tCorrect\tQuestion\n");
for (int i = 0; i < answeredQ.length; i++) {
out.write(i + 1 + ".) ");
out.write(answeredA[i].toString() + "\t");
out.write(answeredC[i].toString() + "\t");
out.write(answeredQ[i] + "\n");
}
out.close();
}
// Boolean login method | login(tries allowed, source file)
public static void login(int tries, String source) throws FileNotFoundException, IOException {
String[] loginInfo;
boolean invalid = false;
for (int x = 0; x < tries; x++) {
invalid = false;
loginInfo = promptLogin();
if (loginInfo[0].toLowerCase().equals("done")) {
System.exit(0);
}
for (int i = 0; i < getLines(source); i++) {
StringTokenizer st = null;
st = new StringTokenizer(read(i, source));
String user = st.nextToken();
String pass = st.nextToken();
if (user.equals(loginInfo[0])) {
if (pass.equals(loginInfo[1])) {
username = loginInfo[0];
password = loginInfo[1];
firstName = st.nextToken();
lastName = st.nextToken();
email = st.nextToken();
role = st.nextToken();
if (role.toLowerCase().equals("instructor")) {
promptInstructor();
JOptionPane.showMessageDialog(null, exitedInstructorMode);
break;
} else {
run();
}
} else {
invalid = true;
}
} else {
invalid = true;
}
}
if(invalid) {
JOptionPane.showMessageDialog(null, invalidLogin);
}
}
JOptionPane.showMessageDialog(null, tooManyAttempts);
}
}
Why not just make a class that holds the values that you need to pass around
Use OOP. Create clss to you object
example:
class User{
String lastName;
String username;
String password;
String role;
String email;
...
public static User login(int tries, String source) throws FileNotFoundException, IOException {
//this you read User param and add new User
return user;
}
}
And now, where you need lastName, username, password, role or email, you can
pass User instance

Replace characters with substring using a loop Java

I am trying to replace each instance of what is between two brackets using a loop and an array. array1a and array1b are the indices of where the brackets open and close. I want to get the number between the two brackets and increment it by one and replace the value currently there, but as the string text is currently a list (such as "list item (0) list item (10) list item (1023)" I want to use a loop to increment the value of each rather than to set all the values within brackets to the same value. I hope this makes sense!
String text = myString.getText();
for (int x = 0; x < 10; x++) {
array2[x] = text.substring(array1a[x], array1b[x]);
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
String text2 = text.replaceAll("\\(.*\\)", array3[x]);
myString.setText(text2);
}
Full Code:
public class CreateVideoList extends JFrame implements ActionListener {
JButton play = new JButton("Play Playlist");
JButton addVideo = new JButton("Add Video");
TextArea playlist = new TextArea(6, 50);
JTextField videoNo = new JTextField(2);
private int x = 0;
#Override
public void actionPerformed(ActionEvent e) {
String key = videoNo.getText();
String name = VideoData.getName(key);
String director = VideoData.getDirector(key);
Integer playCount = VideoData.getPlayCount(key);
String text = playlist.getText();
String rating = CheckVideos.stars(VideoData.getRating(key));
String output = name + " - " + director + "\nRating: "
+ rating
+ "\nPlay Count: " + playCount;
String newItem = key + " " + name + " - " + director + " ("
+ playCount + ") " + "\n";
String addToList = "";
String[] array3 = new String[100];
if ("Add Video".equals(e.getActionCommand())) {
if (Character.isDigit(text.charAt(0)) == false) {
playlist.setText("");
}
if (addToList.indexOf(key) == -1) {
addToList += addToList + newItem;
playlist.append(addToList);
array3[x] = key;
x++;
} else if (addToList.indexOf(key) != -1) {
JOptionPane.showMessageDialog(CreateVideoList.this,
"This video is already in the playlist. Please select a"
+ " different video.", "Add to playlist error", JOptionPane.INFORMATION_MESSAGE);
}
}
if ("Play Playlist".equals(e.getActionCommand())) {
Integer length = (text.length());
int counta = 0;
Integer[] array1a = new Integer[100];
Integer[] array1b = new Integer[100];
String strPlayCount = "";
for (x = 0; x < length; x++) {
if (text.charAt(x) == '(') {
counta++;
array1a[counta - 1] = x;
array1a[counta - 1] = array1a[counta - 1] + 1;
}
if (text.charAt(x) == ')') {
array1b[counta - 1] = x;
array1b[counta - 1] = array1b[counta - 1];
}
}
String[] array2 = new String[counta];
String[] array4 = new String[100];
for (int y = 0; y < counta; y++) {
array2[y] = text.substring(array1a[y], array1b[y]);
array2[y] = array2[y] + 1;
playCount = Integer.parseInt(array2[y]);
array4[y] = "(" + array2[y] + ")";
String text2 = text.replaceAll("\\(.*\\)", array4[y]);
playlist.setText(text2);
}
}
}
Replace
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
with
Integer n = Integer.parseInt(array2[x]) + 1;
array3[x] = "(" + n.toString() + ")";

Error message for StorageResource type

I've been trying to work on this problem for a while now but to no avail. When I run the code I get this error message: incompatible types: edu.duke.StorageResource cannot be converted to java.lang.String on line String geneList = FMG.storeAll(dna);. Does this mean I'm trying to make edu.duke object work with a java.lang.String type object? What would we go about resolving this issue?
Here's my code so far:
package coursera_java_duke;
import java.io.*;
import edu.duke.FileResource;
import edu.duke.StorageResource;
import edu.duke.DirectoryResource;
public class FindMultiGenes5 {
public int findStopIndex(String dna, int index) {
int stop1 = dna.indexOf("TGA", index);
if (stop1 == -1 || (stop1 - index) % 3 != 0) {
stop1 = dna.length();
}
int stop2 = dna.indexOf("TAA", index);
if (stop2 == -1 || (stop2 - index) % 3 != 0) {
stop2 = dna.length();
}
int stop3 = dna.indexOf("TAG", index);
if (stop3 == -1 || (stop3 - index) % 3 != 0) {
stop3 = dna.length();
}
return Math.min(stop1, Math.min(stop2, stop3));
}
public StorageResource storeAll(String dna) {
//CATGTAATAGATGAATGACTGATAGATATGCTTGTATGCTATGAAAATGTGAAATGACCCAdna = "CATGTAATAGATGAATGACTGATAGATATGCTTGTATGCTATGAAAATGTGAAATGACCCA";
String geneAL = new String();
String sequence = dna.toUpperCase();
StorageResource store = new StorageResource();
int index = 0;
while (true) {
index = sequence.indexOf("ATG", index);
if (index == -1)
break;
int stop = findStopIndex(sequence, index + 3);
if (stop != sequence.length()) {
String gene = dna.substring(index, stop + 3);
store.add(gene);
//index = sequence.substring(index, stop + 3).length();
index = stop + 3; // start at the end of the stop codon
}else{ index = index + 3;
}
}
return store;//System.out.println(sequence);
}
public void testStorageFinder() {
DirectoryResource dr = new DirectoryResource();
StorageResource dnaStore = new StorageResource();
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
String s = fr.asString();
dnaStore = storeAll(s);
printGenes(dnaStore);
}
System.out.println("size = " + dnaStore.size());
}
public String readStrFromFile(){
FileResource readFile = new FileResource();
String DNA = readFile.asString();
//System.out.println("DNA: " + DNA);
return DNA;
}//end readStrFromFile() method;
public float calCGRatio(String gene){
gene = gene.toUpperCase();
int len = gene.length();
int CGCount = 0;
for(int i=0; i<len; i++){
if(gene.charAt(i) == 'C' || gene.charAt(i) == 'G')
CGCount++;
}//end for loop
System.out.println("CGCount " + CGCount + " Length: " + len + " Ratio: " + (float)CGCount/len);
return (float)CGCount/len;
}//end of calCGRatio() method;
public void printGenes(StorageResource sr){
//create a FindMultiGenesFile object FMG
FindMultiGenes5 FMG = new FindMultiGenes5();
//read a DNA sequence from file
String dna = FMG.readStrFromFile();
String geneList = FMG.storeAll(dna);
//store all genes into a document
StorageResource dnaStore = new StorageResource();
System.out.println("\n There are " + geneList.size() + " genes. ");
int longerthan60 = 0;
int CGGreaterthan35 = 0;
for(int i=0; i<geneList.size(); i++){
if(!dnaStore.contains(geneList.get(i)))
dnaStore.add(geneList.get(i));
if(geneList.get(i).length() > 60) longerthan60++;
if(FMG.calCGRatio(geneList.get(i)) > 0.35) CGGreaterthan35++;
}
System.out.println("dnaStore.size: " + dnaStore.size());
System.out.println("\n There are " + dnaStore.size() + " genes. ");
System.out.println("There are " + longerthan60 + " genes longer than 60.");
System.out.println("There are " + CGGreaterthan35 + " genes with CG ratio greater than 0.35.");
}//end main();
}
I found your post as I am also doing a similar course at Duke using those edu.duke libraries.
When I get that error message it is because I'm using the wrong method to access it.
Try FMD.data() to get an iterable of all of the gene strings.

The program throws NullPointerException [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Not sure why it gives me the NullPointerException. Please help.
I am pretty sure all the arrays are full, and i restricted all the loops not to go passed empty spaces.
import java.util.;
import java.io.;
public class TextAnalysis {
public static void main (String [] args) throws IOException {
String fileName = args[0];
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int MAX_WORDS = 10000;
String[] words = new String[MAX_WORDS];
int unique = 0;
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
read(words, fileName);
System.out.println("Number of words in file wordlist: " + wordList(words));
System.out.println("Number of words in file: " + countWords(fileName) + "\n");
System.out.println("Word-frequency statistics");
lengthFrequency(words);
System.out.println();
System.out.println("Wordlist dump:");
wordFrequency(words,fileName);
}
public static void wordFrequency(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
int [] array = new int [words.length];
while(s.hasNext()) {
String w = s.next();
if(w!=null){
for(int i = 0; i < words.length; i++){
if(w.equals(words[i])){
array[i]++;
}
}
for(int i = 0; i < words.length; i++){
System.out.println(words[i] + ":" + array[i]);
}
}
}
}
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int[10];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(w!=null){
if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}
}
for(int j = 0; j < 10; j++) {
System.out.println("Word-length " + (j+1) + ": " + lengthTimes[j]);
}
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static int countWords (String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int count = 0;
while(fileScanner.hasNext()) {
String word = fileScanner.next();
count++;
}
return count;
}
public static void read(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
while (s.hasNext()) {
String word = s.next();
int i;
for ( i=0; i < words.length && words[i] != null; i++ ) {
words[i]=words[i].toLowerCase();
if (words[i].equals(word)) {
break;
}
}
words[i] = word;
}
}
public static int wordList(String[] words) {
int count = 0;
while (words[count] != null) {
count++;
}
return count;
}
}
There are two problems with this code
1.You didn't do null check,although the array contains null values
2.Your array index from 0-8,if you wan't to get element at 9th index it will throw ArrayIndexOutOfBound Exception.
Your code should be like that
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int [9];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w) //This one added for null check
{
/* if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}*/
//Don't need to check like that ...u can do like below
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w)
{
lengthTimes[i] =w.length();
}
}
}
//here we should traverse upto length of the array.
for(int i = 0; i < lengthTimes.length; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]);
}
}
Your String Array String[] words = new String[MAX_WORDS]; is not initialized,you are just declaring it.All its content is null,calling length method in line 31 will give you null pointer exception.
`
Simple mistake. When you declare an array, it is from size 0 to n-1. This array only has indexes from 0 to 8.
int [] lengthTimes = new int [9];
//some code here
lengthTimes[9]++; // <- this is an error (this is line 29)
for(int i = 0; i < 10; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]); // <- same error when i is 9. This is line 37
When you declare:
String[] words = new String[MAX_WORDS];
You're creating an array with MAX_WORDS of nulls, if your input file don't fill them all, you'll get a NullPointerException at what I think is line 37 in your original file:
if(w.length() >= 10) { // if w is null this would throw Npe
To fix it you may use a List instead:
List<String> words = new ArrayList<String>();
...
words.add( aWord );
Or perhaps you can use a Set if you don't want to have repeated words.

Categories

Resources