So, I'm a complete novice, and I've been having trouble with this for a while. I have to edit this file so that all the vowels and punctuation are gone, and so that the first and last sentence is capitalized, along with the first letter of every word. I've got the first half done, but the second part is giving me trouble.
Here's what I've got so far:
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
public class SMcatcherInTheIO
{
public static void main (String [] args) throws Exception
{
File catcher= new File ("C:\\Users\\suvra\\Dropbox\\APCompSci 17-18\\AAA SM EXTRA CREDIT\\RyeCh1.txt");
BufferedReader br=new BufferedReader (new FileReader(catcher));
String rye;
while((rye=br.readLine()) !=null)
{
for (int i = 0; i < rye.length(); i++)
{
char c = rye.charAt(i);
if ((c == 'A') || (c == 'a') || (c == 'E') || (c == 'e') || (c == 'I') || (c == 'i') || (c == 'O') || (c == 'o') || (c == 'U') || (c == 'u')
|| (c == ',') || (c == '.') || (c == '?') || ( c == '!'))
{
String front = rye.substring(0, i);
String back = rye.substring(i + 1);
rye = front + "" + back;
}
}
System.out.println(rye);
}
br.close();
}}
Create two String objects :Last and First sentence. Than Loop trought you code and stop at the first point and add value to firstSentence. Do similar for the last sentence just stop at the point-1. After that:
String lastSentence=somethingalreadydoneabove;
String upperCase=lastSentence.toUpperCase();
Hope this would help you.
DK
Related
So what I have is this slightly modified version of a code that's here a hundred times over for Java Stack Balancing.
import java.util.Stack;
public class Main {
public static String testContent = "{(a,b)}";
public static void main(String args[])
{
System.out.println(balancedParentheses(testContent));
}
public static boolean balancedParentheses(String s)
{
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' )
{
stack.push(c);
}else if(c == ']')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '[') return false;
}else if(c == ')')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '(') return false;
}else if(c == '}')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '{') return false;
}
}
return stack.isEmpty();
}
}
What I'd like to do is customize the output such that it would output something like "balanced" or "imbalanced" instead of true/false. Trying to replace return false; with a System.println containing 'balanced' gives me a whole lot of output lines I didn't want. Been searching around here for about an hour and some change and couldn't quite find the answer I was looking for. Any insight?
You could use something like
System.out.println(balancedParentheses(testContent) ? "balanced" : "imbalanced");
OR if you want a method that returns a String wrap the logic in another method
String isBalanced(String expression) {
return balancedParentheses(expression) ? "balanced" : "imbalanced"
}
and in main()
System.out.println(isBalanced(testContent));
Also you could write the code something like this
public static boolean balancedParentheses(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '[' || c == '(' || c == '{') {
stack.push(c);
} else if (c == ']' || c == ')' || c == '}') {
if (stack.isEmpty() || !matches(stack.pop(), c))
return false;
}
}
return stack.isEmpty();
}
private static boolean matches(char opening, char closing) {
return opening == '{' && closing == '}' ||
opening == '(' && closing == ')' ||
opening == '[' && closing == ']';
}
Im working on a token iterator (valid tokens, "true, false, "true", "&", "!", "(", "false", "^", "true", ")".
The code is working, my question is about return values. I often run into this problem, I have return statements, but the final return statement throws off my result by duplicating the last return statement.
I think I know for sure the error lays within my placement of { and } and while i've learned they aren't necessary, since there's so many nested if's i feel they are necessary.
This seems to be a common problem to me and others ive worked with, does anyone have an idea of how to prevent this problem from happening? Thanks!
My code outputs:
line: [ ! BAD (true ^ false) % truelybad]
next token: [!]
next token: [(]
next token: [true]
next token: [^]
next token: [false]
next token: [)]
next token: [)]
and should output
next token: [!]
next token: [(]
next token: [true]
next token: [^]
next token: [false]
next token: [)]
public class TokenIter implements Iterator<String> {
ArrayList<String> token = new ArrayList<String>();
static int count = 0;
// input line to be tokenized
private String line;
// the next Token, null if no next Token
private String nextToken;
// implement
public TokenIter(String line) {
this.line = line;
}
#Override
// implement
public boolean hasNext() {
// System.out.println(count);
return count < line.length();
}
#Override
// implement
public String next() {
while (hasNext()) {
char c = line.charAt(count);
if (c == '!' || c == '!' || c == '^' || c == '(' || c == ')') {
token.add(Character.toString(c));
count++;
nextToken = Character.toString(c);
return nextToken;
} else if (c == 't' || c == 'T') {
count++;
c = line.charAt(count);
if (c == 'r') {
count++;
c = line.charAt(count);
}
if (c == 'u') {
count++;
c = line.charAt(count);
}
if (c == 'e') {
count++;
c = line.charAt(count);
}if (c == ' ' || c == '!' || c == '!' || c == '^' || c == '(' || c == ')'){
token.add("true");
nextToken = "true";
//count++;
return nextToken;
}
} else if (c == 'f' || c == 'F') {
count++;
c = line.charAt(count);
if (c == 'a') {
count++;
c = line.charAt(count);
}
if (c == 'l') {
count++;
c = line.charAt(count);
}
if (c == 's') {
count++;
c = line.charAt(count);
}
if (c == 'e') {
count++;
c = line.charAt(count);
}
if (c == ' ' || c == '!' || c == '!' || c == '^' || c == '(' || c == ')'){
token.add("false");
nextToken = "false";
// count++;
return nextToken;
}
} else if (c == ' ') {
count++;
} else {
count++;
}
}
return nextToken;
}
#Override
// provided, do not change
public void remove() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
// provided
public static void main(String[] args) {
String line;
// you can play with other inputs on the command line
if (args.length > 0)
line = args[0];
// or do the standard test
else
line = " ! BAD (true ^ false) % truelybad";
System.out.println("line: [" + line + "]");
TokenIter tokIt = new TokenIter(line);
while (tokIt.hasNext())
System.out.println("next token: [" + tokIt.next() + "]");
}
}
Problem with your code comes only when last digit is not a token.
Reason - You are checking hasNext() which is true it goes inside your code.You are not setting nextToken for this case so it uses your lask token and display it.
I updated your code to always return a value and check if value return is from token list then display otherwise ignore it.
public class test implements Iterator<String> {
static List<String> tokenList = Arrays.asList( "true", "&", "!", "(", "false", "^", "true", ")");
ArrayList<String> token = new ArrayList<String>();
static int count = 0;
// input line to be tokenized
private String line;
// the next Token, null if no next Token
private String nextToken;
// implement
public test(String line) {
this.line = line;
}
#Override
// implement
public boolean hasNext() {
// System.out.println(count);
return count < line.length();
}
#Override
// implement
public String next() {
while (hasNext()) {
char c = line.charAt(count);
if (c == '!' || c == '!' || c == '^' || c == '(' || c == ')') {
token.add(Character.toString(c));
count++;
nextToken = Character.toString(c);
return nextToken;
} else if (c == 't' || c == 'T') {
count++;
c = line.charAt(count);
if (c == 'r') {
count++;
c = line.charAt(count);
}
if (c == 'u') {
count++;
c = line.charAt(count);
}
if (c == 'e') {
count++;
c = line.charAt(count);
}if (c == ' ' || c == '!' || c == '!' || c == '^' || c == '(' || c == ')'){
token.add("true");
nextToken = "true";
//count++;
return nextToken;
}
} else if (c == 'f' || c == 'F') {
count++;
c = line.charAt(count);
if (c == 'a') {
count++;
c = line.charAt(count);
}
if (c == 'l') {
count++;
c = line.charAt(count);
}
if (c == 's') {
count++;
c = line.charAt(count);
}
if (c == 'e') {
count++;
c = line.charAt(count);
}
if (c == ' ' || c == '!' || c == '!' || c == '^' || c == '(' || c == ')'){
token.add("false");
nextToken = "false";
// count++;
return nextToken;
}
} else if (c == ' ') {
count++;
nextToken = null;
} else {
count++;
nextToken = null;
}
}
return nextToken;
}
#Override
// provided, do not change
public void remove() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
// provided
public static void main(String[] args) {
String line;
// you can play with other inputs on the command line
if (args.length > 0)
line = args[0];
// or do the standard test
else
line = " ! BAD (true ^ false) % truelybad ";
System.out.println("line: [" + line + "]");
test tokIt = new test(line);
while (tokIt.hasNext()) {
String s = tokIt.next();
if (s != null && tokenList.contains(s))
System.out.println("next token: [" + s + "]");
}
}
}
The underlying problem here is that your hasNext() method returns true not if there is another token in the String, but if it hasn't finished parsing the String yet.
So what happens is if you put in the String " ! ! true lotsofcrap ", then calling next() will return "!", then "!", then "true", then after that has been returned, there are no more tokens in the String, yet hasNext() still returns true.
What you might consider doing is having hasNext() parse through the string, but instead of returning the next String, return true only if it finds another token ahead of the current position. Keep in mind that in hasNext(), you do not want to directly increment count. Instead, make a local variable int something = count; at the beginning of hasNext() and use that. If you fix that, then the rest of your code SHOULD work just fine.
When the user enters their ID I want it to be in a specific format, they are mostly explained within the comments. I was wondering if their was an easier more efficient way of doing this. Also whether or not there is a way to change the entered letters to capital the way I've done the code, or any other method.
private boolean setCustomerID(String id) {
//Validates the customerID contains 3 letters a hypthen then 4 numbers
if ((id.charAt(0) < 'A' || id.charAt(0) > 'Z')
|| (id.charAt(1) < 'A' || id.charAt(1) > 'Z')
|| (id.charAt(2) < 'A' || id.charAt(2) > 'Z')
|| (id.charAt(3) != '-')
|| !isDigit(id.charAt(4))
|| !isDigit(id.charAt(5))
|| !isDigit(id.charAt(6))
|| !isDigit(id.charAt(7))) {
return false;
//Checks the user enters P, B or C for first letter
} else if ((id.charAt(0) == 'P' || id.charAt(0) == 'B' || id.charAt(0) == 'E')
//Checks the second and third letter are in the correct region
&& ((id.charAt(1) == 'S' && id.charAt(2) == 'C')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'C')
|| (id.charAt(1) == 'W' && id.charAt(2) == 'A')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'I')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'E')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'W')
|| (id.charAt(1) == 'M' && id.charAt(2) == 'I')
|| (id.charAt(1) == 'E' && id.charAt(2) == 'A')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'E')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'W'))){
// SC (Scotland), WA (Wales), NI (Northern Ireland), NE (North-East), NW (North-West),
//MI (Midlands), EA (East Anglia), SE (South-East), SW (South-West).
return true;
}
return false;
}
Use regex.
private boolean matchCustomerID(String id) {
return id.matches("^[PBE](?:SC|WA|NI|NE|NW|MI|EA|SE|SW)-\\d{4}\\b");
}
Regular expressions are one way of solving the problem. You can compose the pattern in a way that makes maintenance easier. Building on rcorreia's pattern, you can do something like:
private boolean setCustomerID(String id) {
char[] validFirstLetters = { 'P', 'B', 'E' };
String[] validRegions = { "SC", "WA", "NI", "NE", "NW", "MI", "EA", "SE", "SW" };
String pattern =
String.format("^[%s](?:%s)-\\d{4}$", new String(validFirstLetters),
String.join("|", validRegions));
return id.matches(pattern);
}
Note that this uses String.join() from Java 8. If you don't use Java 8 yet, consider using StringUtils from Apache Commons Lang.
Regexp is a great feature, but not easy to write and understand..
In this case, I would follow your way, but I would define some testing method. In this manner the code will be readable and easy to write Unit tests for it.
If you need some change later, you will understand the code.
Example:
testForLength();
testForLetters();
testForFirstTwoLetters();
This program is supposed to compare "DNA" strings.
Input:
3
ATGC
TACG
ATGC
CGTA
AGQ
TCF
First line represents how many times the program will be run. Each time it runs, it compares the two strings. A matches with T and vice versa. G matches with C and vise versa. So if the first letter of string 1 is A, the first letter of string 2 should be T. If the next one is T, the next one on the other string should be A and etc. If a letter other than A, T, G, or C appear, it is a bad sample. If its bad, print out bad, if its good, print out good. I tried many different combinations to this and they all worked fine but according the the judge's test data (they have different input), it failed. Does anyone see anything wrong with this? I know it might not be the most efficient way of getting the job done but it did, at least to my understanding.
Output:
GOOD
BAD
BAD
public class DNA
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner (new File ("dna.dat"));
int T = scan.nextInt();
scan.nextLine();
boolean valid = true;
for (int i = 0; i < T; i++)
{
String strand1 = scan.nextLine();
strand1 = strand1.toUpperCase();
String strand2 = scan.nextLine();
strand2 = strand2.toUpperCase();
for (int p = 0; p < strand1.length(); p++)
{
if (strand1.charAt(p) != 'A' && strand1.charAt(p) != 'T' && strand1.charAt(p) != 'G' && strand1.charAt(p) != 'C'
&& strand2.charAt(p) != 'A' && strand2.charAt(p) != 'T' && strand2.charAt(p) != 'G' && strand2.charAt(p) != 'C')
{
valid = false;
break;
}
if (strand1.length() != strand2.length())
{
valid = false;
break;
}
}
if (valid)
{
for (int p = 0; p < strand1.length(); p++)
{
if ((strand1.charAt(p) == 'A' && strand2.charAt(p) == 'T') || (strand1.charAt(p) == 'T' && strand2.charAt(p) == 'A')
|| (strand1.charAt(p) == 'G' && strand2.charAt(p) == 'C') || (strand1.charAt(p) == 'C' && strand2.charAt(p) == 'G'))
valid = true;
else
valid = false;
}
}
if (valid)
out.println("GOOD");
else
out.println("BAD");
valid = true;
}
}
}
I added the toUpperCase and compared the strings for equal length just as a last attempt to see if their data maybe had some lowercase letters or different length strings though they SHOULD all be the same length and uppercase. Nevertheless, the program was still rejected for "failing the judges test data."
You need a break in the second for loop when valid = false. For example if characters 1,2,3 are wrong but #4 is a match you will still end up with valid.
I would convert the strings to arrays to make things easier:
for (int i = 0; i < T; i++)
{
boolean valid = true;
String strand1 = scan.nextLine();
strand1 = strand1.toUpperCase();
String strand2 = scan.nextLine();
strand2 = strand2.toUpperCase();
if ( strand1.length() != strand2.length())
{
valid = false;
}
if (valid) {
char[] c1 = strand1.toCharArray();
char[] c2 = strand2.toCharArray();
for (int p = 0; p < c1.length; p++)
{
if (-1 == "ACTG".indexOf(c1[p]) || -1 == "ACTG".indexOf(c2[p]))
{
valid = false;
break;
}
}
if (valid)
{
for (int p = 0; p < c1.length; p++)
{
if (('A' == c1[p] && 'T' != c2[p]) ||
('T' == c1[p] && 'A' != c2[p]) ||
('C' == c1[p] && 'G' != c2[p]) ||
('G' == c1[p] && 'C' != c2[p])) {
valid = false;
break;
}
}
}
}
if (valid)
System.out.println("GOOD");
else
System.out.println("BAD");
}
Change all
&&
in
if (strand1.charAt(p) != 'A' && strand1.charAt(p) != 'T' && strand1.charAt(p) != 'G' && strand1.charAt(p) != 'C' && strand2.charAt(p) != 'A' && strand2.charAt(p) != 'T' && strand2.charAt(p) != 'G' && strand2.charAt(p) != 'C')
to
||
if ANY, not ALL character is other than A, T, G, or C, then we exit the loop.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Hello again Stackoverflow,
I am in the process of creating an infix to postfix calculator. the calculator must read input from a file and then use stacks and queues to create postfix notation. i have all of my code to read the file and create the postfix notation in a queue. the file that i am reading from contains:
(4>3)+(3=4)+2
here is my code to put into postfix notation in a queue:
import java.io.*;
import java.util.ArrayList;
public class Proj1Main {
public static void main(String[] args) {
readMathFile();
q.printQueue();
}
public static void readMath(char c, myStack s, myQueue q) {
if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
System.out.println("NUMBER"); // <--for testing.
int o = (int)c;
q.enqueue(o);
} else if(c == '+' || c=='-') {
System.out.println("+ or -");
Object x = s.pop();
while( !s.isEmpty() ) {
q.enqueue(x);
x = s.pop();
}
} else if(c == '(' || c == ')' || c == '!' || c == '<' || c == '>' || c == '&' || c == '|' || c == '=') {
System.out.println("other operator"); // <--for testing.
Object x = s.pop();
char y = x.toString().charAt(0);
while( !s.isEmpty() && (y != '\\' || y != '*') ) {
q.enqueue(y);
y = (Character)s.pop();
if(y != '\\' || y != '*') {
q.enqueue(y);
s.push(x);
}
}
} else if(c=='\\' || c == '*') {
System.out.println("divide or multiply"); // <--for testing.
Object x = s.pop();
while( !s.isEmpty() ) {
q.enqueue(x);
x = s.pop();
}
} else if(c == ')') {
System.out.println("close paren"); // <--for testing.
Object x = s.pop();
while( !s.isEmpty() && x != "(" ) {
q.enqueue(x);
x = s.pop();
}
}
}
public static myStack s;
public static myQueue q;
// the file reading code was borrowed from:
// http://www.java2s.com/Code/Java/File-Input-Output/Readfilecharacterbycharacter.htm
public static void readMathFile() {
s = new myStack();
q = new myQueue();
File file = new File("test.txt");
if (!file.exists()) {
System.out.println(file + " does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
char current;
// in this while loop is where all of the reading happens
while (fis.available() > 0) {
current = (char) fis.read();
readMath(current, s, q);
}
if(fis.available() == 0) {
Object x = s.pop();
while(!x.equals("empty stack"))
q.enqueue(s.pop());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
after i run the code, i print the output which turns out to be:
QUEUE:
52
51
51
52
50
I have no idea where 52, 51, etc are coming from. it should read "4>33=4+2+" (i think) i was wondering if anybody could identify my problem? or give me some tips on how to fix it?
52 51 51 52 50... are ASCII code for the characters '4', '3', '3', '4', '2' respectively.
When you are doing:
current = (char) fis.read();
you are getting the characters themselves.
Later in readMath():
int o = (int)c;
You are converting in an integer and putting it in a queue. Probably when you print the queue, it is still an integer and it comes out as the ascii code.
You can convert a digit char to the integer it represents by doing this:
Character.getNumericValue(c);