I would like to make the following code faster, without changing the reading/writing from standard console. The first line contains the number of inputs and the subsequent lines contain a set of Integers.
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
try {
java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
int a = Integer.parseInt(r.readLine());
for (int i = 0; i < a; i++) {
StringTokenizer st = new StringTokenizer(r.readLine());
while (st.hasMoreTokens()) {
int first = Integer.parseInt(st.nextToken());
int second = Integer.parseInt(st.nextToken());
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
}
}
} catch (Exception e) {
System.err.print(e.getMessage());
}
}
}
You are performing a lot of redundant autoboxing and outboxing there which could be saved if you define first and second as primitive ints instead of java.lang.Integer wrapper classes. I doubt, however, that for any reasonable size of input you'd even notice the difference.
Here are a few suggestions, I am not sure these will help a lot.
1) This,
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
can be changed to
System.out.println(first < second
? "<"
: first > second
? ">"
: "="
);
2) Since you are using a throws clause and your try-catch does nothing you can remove it.
3) Here,
int first = Integer.parseInt(st.nextToken());
int second = Integer.parseInt(st.nextToken());
You are not checking for hasMoreTokens() the second time.
4) Use split() instead of StringTokenizer. More on that here and here.
You may consider to use the BufferedReader's constructor below:
public BufferedReader(Reader in, int sz)
Giving the sz parameter a reasonable high value, can avoid the buffer to be refilled too often.
As a side note, while readLine() retuns null if the end of the stream has been reached, it's better to check its return value before calling new StringTokenizer(r.readLine()) and Integer.parseInt(r.readLine()).
The edited class follows:
public class Main {
public static void main(String[] args) {
BufferedReader r;
String line;
StringTokenizer st;
int a, first, second;
r = new BufferedReader(new InputStreamReader(System.in), 4096);
try {
line = r.readLine();
if (line != null) {
a = Integer.parseInt(line);
for (int i = 0; i < a; ++i) {
line = r.readLine();
if (line == null)
break;
st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
first = Integer.parseInt(st.nextToken());
second = Integer.parseInt(st.nextToken());
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
}
}
}
r.close();
} catch (Exception e) {
System.err.print(e.getMessage());
}
}
}
Related
Here is a description:
"Write a program that, given an input sentence, alternates the case of every alphabetic character, starting with uppercase. Spaces and non-alphabetical characters should be added to the final output as is, i.e. they should not be taken into account when alternating between upper/lowercase."
Here is what I've tried and does not work (System.out.println in main method should return correct sentence):
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader);
String line;
while ((line = in.readLine()) != null) {
System.out.println(changeToUppercaseOrLowercase(countLettersWithSpaces(line), line));
}
}
private static int countLettersWithSpaces(String sentence) {
int count = 0;
for (int i = 0; i < sentence.length(); i ++)
{
char c = Character.toUpperCase(sentence.charAt(i));
if (c >= 'A' && c <= 'Z' || c == ' ' )
count ++;
}
return count;
}
private static String changeToUppercaseOrLowercase(int countLetters, String sentence) {
StringBuilder stringBuilder = new StringBuilder();
for(int i=0; i<countLetters; i++) {
if (!sentence.substring(i,i+1).equals(" ")) {
if ((i % 2) == 0) {
stringBuilder.append(sentence.substring(i,i+1).toUpperCase());
}
else {
stringBuilder.append(sentence.substring(i,i+1).toLowerCase());
}
}
if (sentence.substring(i,i+1).equals(" ")) {
stringBuilder.append(" ");
i++;
}
}
return stringBuilder.toString();
}
}
But tests says that:
Input data:
We are the world
Expected result:
We ArE tHe WoRlD
Result:
We Re He OrLd
How to solve that? Thank you in advance!
You can use Character.isAlphabetic and keep a counter that is incremented each time a letter is encountered.
public static String alternateCase(String str){
int count = 0;
StringBuilder sb = new StringBuilder(str.length());
for(int i = 0; i < str.length(); i++){
char c = str.charAt(i);
if(Character.isAlphabetic(c))
sb.append(++count % 2 == 1 ? Character.toUpperCase(c) : Character.toLowerCase(c));
else sb.append(c);
}
return sb.toString();
}
use Character.isLetter() function to check if it's a letter or not. half your problem will be solved.
and your problem description and test case doesnt go with each other. Please try to clarify more.
There are many ways to fix this. This one has minimal impact on your existing code.
Use an evenOdd counter to ensure you are not skipping over characters but still maintaining the alternation.
private static String changeToUppercaseOrLowercase(int countLetters, String sentence) {
StringBuilder stringBuilder = new StringBuilder();
int evenOdd = 0; // init ********HERE*******
for(int i=0; i<countLetters; i++) {
if (!sentence.substring(i,i+1).equals(" ")) {
if ((evenOdd % 2) == 0) { // check ********HERE*******
stringBuilder.append(sentence.substring(i,i+1).toUpperCase());
}
else {
stringBuilder.append(sentence.substring(i,i+1).toLowerCase());
}
}
if (sentence.substring(i,i+1).equals(" ")) {
stringBuilder.append(" ");
evenOdd--; // adjust to preserve proper alternation ********HERE*********
}
evenOdd++; // the normal update ********HERE*******
}
return stringBuilder.toString();
}
This is my code. I want to read a file called "write.txt" and then once it reads. Compare it with a word, here I use "target variable(of string type) once the comparison is done inside the method called findTarget it will return 1 after the condition is true. I try to call the method but I keep getting an error. test.java:88: error: cannot find symbol
String testing = findTarget(target1, source1);
^
symbol: variable target1
location: class test
1 error
can someone correct my mistake. I am quite new to programming.
import java.util.*;
import java.io.*;
public class test {
public static int findTarget( String target, String source )
{
int target_len = target.length();
int source_len = source.length();
int add = 0;
for(int i = 0;i < source_len; ++i) // i is an varialbe used to count upto
source_len.
{
int j = 0; // take another variable to count loops
while(add == 0)
{
if( j >= target_len ) // count upto target length
{
break;
}
else if( target.charAt( j ) != source.charAt( i + j ) )
{
break;
}
else
{
++j;
if( j == target_len )
{
add++; // this will return 1: true
}
}
}
}
return add;
//System.out.println(""+add);
}
public static void main ( String ... args )
{
//String target = "for";
// function 1
try
{
// read the file
File file = new File("write.txt"); //establising a file object
BufferedReader br = new BufferedReader(new FileReader(file));
//reading the files from the file object "file"
String target1;
while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
System.out.println(target1);
//target.close();
}
catch (IOException e)
{
System.out.println("file error!");
}
String source1 = "Searching for a string within a string the hard way.";
// function 2
test ob = new test();
String testing = findTarget(target1, source1);
// end
//System.out.println(findTarget(target, source));
System.out.println("the answer is: "+testing);
}
}
The error is because findTarget is a class function.
So, where you have this:
test ob = new test();
String testing = findTarget(target1, source1);
...should be changed to call the function from a static context:
//test ob = new test(); not needed, the function is static
int testing = test.findTarget(target1, source1);
// also changed the testing type from String to int, as int IS findTarget's return type.
I don't have your file contents to give a trial run, but that should at least help get past the error.
=====
UPDATE:
You are close!
Inside main, change the code at your loop so that it looks like this:
String target1;
int testing = 0; // move and initialize testing here
while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
{
//System.out.println(target1);
testing += test.findTarget(target1, source1);
//target1 = br.readLine();
}
System.out.println("answer is: "+testing);
I have finally been able to solve my problem. but extending the functionalities. I want to increment the add by 1. but in my programming, it keeps giving me output as
answer is: 1 answer is: 1
instead I want my program to print not two 1's rather 1+1 = 2
can someone fix this incrementing problem?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class test {
public static int findTarget(String target, String source) {
int target_len = target.length();
int source_len = source.length();
int add = 0;
// this function checks the character whether it is present.
for (int i = 0; i < source_len; ++i) // i is a varialbe used to count upto source_len.
{
int j = 0; // take another variable to count loops
while (add == 0)
{
if (j >= target_len) // count upto target length
{
break;
}
else if (target.charAt(j) != source.charAt(i + j))
{
break;
}
else
{
++j;
if (j == target_len)
{
add++; // this will return 1: true
}
}
}
}
return add;
//System.out.println(""+add);
}
public static void main(String... args) {
//String target = "for";
// function 1
try {
// read the file
Scanner sc = new Scanner(System.in);
System.out.println("Enter your review: ");
String source1 = sc.nextLine();
//String source1 = "Searching for a string within a string the hard way.";
File file = new File("write.txt"); //establising a file object
BufferedReader br = new BufferedReader(new FileReader(file)); //reading the files from the file object "file"
String target1;
while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
{
//System.out.println(target1);
int testing = test.findTarget(target1, source1);
System.out.println("answer is: "+testing);
//target1 = br.readLine();
}
br.close();
}
catch (IOException e)
{
System.out.println("file error!");
}
}
}
I have a java project and i have used comments in many location in various java files in the project. Now i need to remove all type of comments : single line , multiple line comments .
Please provide automation for removing comments. using tools or in eclipse etc.
Currently i am manually trying to remove all commetns
You can remove all single- or multi-line block comments (but not line comments with //) by searching for the following regular expression in your project(s)/file(s) and replacing by $1:
^([^"\r\n]*?(?:(?<=')"[^"\r\n]*?|(?<!')"[^"\r\n]*?"[^"\r\n]*?)*?)(?<!/)/\*[^\*]*(?:\*+[^/][^\*]*)*?\*+/
It's possible that you have to execute it more than once.
This regular expression avoids the following pitfalls:
Code between two comments /* Comment 1 */ foo(); /* Comment 2 */
Line comments starting with an asterisk: //***NOTE***
Comment delimiters inside string literals: stringbuilder.append("/*");; also if there is a double quote inside single quotes before the comment
To remove all single-line comments, search for the following regular expression in your project(s)/file(s) and replace by $1:
^([^"\r\n]*?(?:(?<=')"[^"\r\n]*?|(?<!')"[^"\r\n]*?"[^"\r\n]*?)*?)\s*//[^\r\n]*
This regular expression also avoids comment delimiters inside double quotes, but does NOT check for multi-line comments, so /* // */ will be incorrectly removed.
I had to write somehting to do this a few weeks ago. This should handle all comments, nested or otherwise. It is long, but I haven't seen a regex version that handled nested comments properly. I didn't have to preserve javadoc, but I presume you do, so I added some code that I belive should handle that. I also added code to support the \r\n and \r line separators. The new code is marked as such.
public static String removeComments(String code) {
StringBuilder newCode = new StringBuilder();
try (StringReader sr = new StringReader(code)) {
boolean inBlockComment = false;
boolean inLineComment = false;
boolean out = true;
int prev = sr.read();
int cur;
for(cur = sr.read(); cur != -1; cur = sr.read()) {
if(inBlockComment) {
if (prev == '*' && cur == '/') {
inBlockComment = false;
out = false;
}
} else if (inLineComment) {
if (cur == '\r') { // start untested block
sr.mark(1);
int next = sr.read();
if (next != '\n') {
sr.reset();
}
inLineComment = false;
out = false; // end untested block
} else if (cur == '\n') {
inLineComment = false;
out = false;
}
} else {
if (prev == '/' && cur == '*') {
sr.mark(1); // start untested block
int next = sr.read();
if (next != '*') {
inBlockComment = true; // tested line (without rest of block)
}
sr.reset(); // end untested block
} else if (prev == '/' && cur == '/') {
inLineComment = true;
} else if (out){
newCode.append((char)prev);
} else {
out = true;
}
}
prev = cur;
}
if (prev != -1 && out && !inLineComment) {
newCode.append((char)prev);
}
} catch (IOException e) {
e.printStackTrace();
}
return newCode.toString();
}
you can try it with the java-comment-preprocessor:
java -jar ./jcp-6.0.0.jar --i:/sourceFolder --o:/resultFolder -ef:none --r
source
I made a open source library and uploaded to github, its called CommentRemover you can remove single line and multiple line Java Comments.
It supports remove or NOT remove TODO's.
Also it supports JavaScript , HTML , CSS , Properties , JSP and XML Comments too.
There is a little code snippet how to use it (There is 2 type usage):
First way InternalPath
public static void main(String[] args) throws CommentRemoverException {
// root dir is: /Users/user/Projects/MyProject
// example for startInternalPath
CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
.removeJava(true) // Remove Java file Comments....
.removeJavaScript(true) // Remove JavaScript file Comments....
.removeJSP(true) // etc.. goes like that
.removeTodos(false) // Do Not Touch Todos (leave them alone)
.removeSingleLines(true) // Remove single line type comments
.removeMultiLines(true) // Remove multiple type comments
.startInternalPath("src.main.app") // Starts from {rootDir}/src/main/app , leave it empty string when you want to start from root dir
.setExcludePackages(new String[]{"src.main.java.app.pattern"}) // Refers to {rootDir}/src/main/java/app/pattern and skips this directory
.build();
CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
commentProcessor.start();
}
Second way ExternalPath
public static void main(String[] args) throws CommentRemoverException {
// example for externalInternalPath
CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
.removeJava(true) // Remove Java file Comments....
.removeJavaScript(true) // Remove JavaScript file Comments....
.removeJSP(true) // etc..
.removeTodos(true) // Remove todos
.removeSingleLines(false) // Do not remove single line type comments
.removeMultiLines(true) // Remove multiple type comments
.startExternalPath("/Users/user/Projects/MyOtherProject")// Give it full path for external directories
.setExcludePackages(new String[]{"src.main.java.model"}) // Refers to /Users/user/Projects/MyOtherProject/src/main/java/model and skips this directory.
.build();
CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
commentProcessor.start();
}
This is an old post but this may help someone who enjoys working on command line like myself:
The perl one-liner below will remove all comments:
perl -0pe 's|//.*?\n|\n|g; s#/\*(.|\n)*?\*/##g;' test.java
Example:
cat test.java
this is a test
/**
*This should be removed
*This should be removed
*/
this should not be removed
//this should be removed
this should not be removed
this should not be removed //this should be removed
Output:
perl -0pe 's#/\*\*(.|\n)*?\*/##g; s|//.*?\n|\n|g' test.java
this is a test
this should not be removed
this should not be removed
this should not be removed
If you want get rid of multiple blank lines as well:
perl -0pe 's|//.*?\n|\n|g; s#/\*(.|\n)*?\*/##g; s/\n\n+/\n\n/g' test.java
this is a test
this should not be removed
this should not be removed
this should not be removed
EDIT: Corrected regex
Dealing with source code is hard unless you know more on the writing of comment.
In the more general case, you could have // or /* in text constants. So your really need to parse the file at a syntaxic level, not only lexical. IMHO the only bulletproof solution would be to start for example with the java parser from openjdk.
If you know that your comments are never deeply mixed with the code (in my exemple comments MUST be full lines), a python script could help
multiple = False
for line in text:
stripped = line.strip()
if multiple:
if stripped.endswith('*/'):
multiple = False
continue
elif stripped.startswith('/*'):
multiple = True
elif stripped.startswith('//'):
pass
else:
print(line)
If you are using Eclipse IDE, you could make regex do the work for you.
Open the search window (Ctrl+F), and check 'Regular Expression'.
Provide the expression as
/\*\*(?s:(?!\*/).)*\*/
Prasanth Bhate has explained it in Tool to remove JavaDoc comments?
public class TestForStrings {
/**
* The main method.
*
* #param args
* the arguments
* #throws Exception
* the exception
*/
public static void main(String args[]) throws Exception {
String[] imports = new String[100];
String fileName = "Menu.java";
// This will reference one API at a time
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
int startingOffset = 0;
// This will reference one API at a time
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.forName("ISO-8859-1"));
// remove single line comments
for (int count = 0; count < lines.size(); count++) {
String tempString = lines.get(count);
lines.set(count, removeSingleLineComment(tempString));
}
// remove multiple lines comment
for (int count = 0; count < lines.size(); count++) {
String tempString = lines.get(count);
removeMultipleLineComment(tempString, count, lines);
}
for (int count = 0; count < lines.size(); count++) {
System.out.println(lines.get(count));
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
} catch (Exception e) {
}
}
/**
* Removes the multiple line comment.
*
* #param tempString
* the temp string
* #param count
* the count
* #param lines
* the lines
* #return the string
*/
private static List<String> removeMultipleLineComment(String tempString,
int count, List<String> lines) {
try {
if (tempString.contains("/**") || (tempString.contains("/*"))) {
int StartIndex = count;
while (!(lines.get(count).contains("*/") || lines.get(count)
.contains("**/"))) {
count++;
}
int endIndex = ++count;
if (StartIndex != endIndex) {
while (StartIndex != endIndex) {
lines.set(StartIndex, "");
StartIndex++;
}
}
}
} catch (Exception e) {
// Do Nothing
}
return lines;
}
/**
* Remove single line comments .
*
* #param line
* the line
* #return the string
* #throws Exception
* the exception
*/
private static String removeSingleLineComment(String line) throws Exception {
try {
if (line.contains(("//"))) {
int startIndex = line.indexOf("//");
int endIndex = line.length();
String tempoString = line.substring(startIndex, endIndex);
line = line.replace(tempoString, "");
}
if ((line.contains("/*") || line.contains("/**"))
&& (line.contains("**/") || line.contains("*/"))) {
int startIndex = line.indexOf("/**");
int endIndex = line.length();
String tempoString = line.substring(startIndex, endIndex);
line = line.replace(tempoString, "");
}
} catch (Exception e) {
// Do Nothing
}
return line;
}
}
This is what I came up with yesterday.
This is actually homework I got from school so if anybody reads this and finds a bug before I turn it in, please leave a comment =)
ps. 'FilterState' is a enum class
public static String deleteComments(String javaCode) {
FilterState state = FilterState.IN_CODE;
StringBuilder strB = new StringBuilder();
char prevC=' ';
for(int i = 0; i<javaCode.length(); i++){
char c = javaCode.charAt(i);
switch(state){
case IN_CODE:
if(c=='/')
state = FilterState.CAN_BE_COMMENT_START;
else {
if (c == '"')
state = FilterState.INSIDE_STRING;
strB.append(c);
}
break;
case CAN_BE_COMMENT_START:
if(c=='*'){
state = FilterState.IN_COMMENT_BLOCK;
}
else if(c=='/'){
state = FilterState.ON_COMMENT_LINE;
}
else {
state = FilterState.IN_CODE;
strB.append(prevC+c);
}
break;
case ON_COMMENT_LINE:
if(c=='\n' || c=='\r') {
state = FilterState.IN_CODE;
strB.append(c);
}
break;
case IN_COMMENT_BLOCK:
if(c=='*')
state=FilterState.CAN_BE_COMMENT_END;
break;
case CAN_BE_COMMENT_END:
if(c=='/')
state = FilterState.IN_CODE;
else if(c!='*')
state = FilterState.IN_COMMENT_BLOCK;
break;
case INSIDE_STRING:
if(c == '"' && prevC!='\\')
state = FilterState.IN_CODE;
strB.append(c);
break;
default:
System.out.println("unknown case");
return null;
}
prevC = c;
}
return strB.toString();
}
private static int find(String s, String t, int start) {
int ret = s.indexOf(t, start);
return ret < 0 ? Integer.MAX_VALUE : ret;
}
private static int findSkipEsc(String s, String t, int start) {
while(true) {
int ret = find(s, t, start);
if( ret == Integer.MAX_VALUE) return -1;
int esc = find(s, "\\", start);
if( esc > ret) return ret;
start += 2;
}
}
private static String removeLineCommnt(String s) {
int i, start = 0;
while (0 <= (i = find(s, "//", start))) { //Speed it up
int j = find(s, "'", start);
int k = find(s, "\"", start);
int first = min(i, min(j, k));
if (first == Integer.MAX_VALUE) return s;
if (i == first) return s.substring(0, i);
//skipp quoted string
start = first+1;
if (k == first) { // " asdas\"dasd "
start = findSkipEsc(s,"\"",start);
if (start < 0) return s;
start++;
continue;
}
//if j == first ' asda\'sasd ' --- not in JSON
start = findSkipEsc(s,"'\"'",start);
if (start < 0) return s;
start++;
}
return s;
}
static String removeLineCommnts(String s) {
if (!s.contains("//")) return s; //Speed it up
return Arrays.stream(s.split("[\\n\\r]+")).
map(Common::removeLineCommnt).
collect(Collectors.joining("\n"));
}
My code has to read 50 lines of input and output them in reverse order, then other 50 lines, so output starts from 50th line, goes to the 1st one, then it start from 100th line to 50th I got it to work. But the only thing, that 51 line isn't printed, I can't get what's going wrong.
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
String newString;
LinkedList<String> list = new LinkedList<String>();
int i = 0;
while ((newString = r.readLine()) != null) {
if (i < 50) {
i++;
list.addFirst(newString);
} else {
for (String s : list)
w.println(s);
list.clear();
i = 0;
}
}
for (String s : list)
w.println(s);
}
Change your code as follow:
i++;
list.addFirst(newString);
to
list.addFirst(newString);
i++;
Because the way you are adding newString to list will skip one count
Update:
Sorry but I have to fix my answer rather than deleting this. I checked it twice and as per the right answer add this line :-)
list.addFirst(newString);
You are discarding the line you read when i == 50, here is a fix that makes it work.
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
String newString;
LinkedList<String> list = new LinkedList<String>();
int i = 0;
while ((newString = r.readLine()) != null) {
if (i < 50) {
i++;
list.addFirst(newString);
} else {
for (String s : list)
w.println(s);
list.clear();
list.addFirst(newString); // <---- add this line and you should be fine
i = 0;
}
}
for (String s : list)
w.println(s);
}
I am new here and in programming as well. I am trying to study other topics alone since my instructor isn't enough help when I have a question so here it goes. I want reverse a word with a generic Stack.
My pop,push,isEmpty and peek methods work (I tested them with a simpler program I made before I tried it on this one.) and the output seems to be giving me the reversed word char by char but always giving me a null before each char!
My questions are:
Why is this happening? And even though I have an expandCapacity method to work when the capacity is at 9 but it doesn't apply when the input passes the limit.
Here's my code
package Stack;
import java.util.Scanner;
public class ReverseDriver<T> {
private static String out;
private static String in;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
in = input.nextLine();
int size = in.length();
ArrayStack<Character> revStack = new ArrayStack<>(size);
for (int i = 0; i < in.length(); i++) {
char u = in.charAt(i);
revStack.Push(u);
if (in.length() > 9) {
revStack.expandCapacity();
}
}
while (!revStack.IsEmpty()) {
char u = revStack.Pop();
out = out + u;
System.out.flush();
System.out.print(out);
}
}
}
Here's the Output
run:
Enter a word:
word
nullr
nullro
nullrow
Exception in thread "main" java.lang.NullPointerException
at Stack.ReverseDriver.main(ReverseDriver.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
EDIT: here's the methods that I said that were working.
#Override
public void Push ( T element)
{
if (count == stack.length){
expandCapacity();
}
stack[++count] = element;
//System.out.println(count);
}
#Override
public String toString()
{
String result = "<top of stack>\n";
for (int index=count-1; index >= 0; index--){
result += stack[index] + "\n";
}
return result + "<bottom of stack>";
}
#Override
public boolean IsEmpty()
{ //Checks if array is empty
if(count == 0){
System.out.println("Nothing");
}
return count == 0;
}
public T Pop()
{
T output;
output = (stack[count - 1]);
count--;
return(output);
}
#Override
public T Peek()
{
//looks at the object at the top of this stack without removing it
//from the stack.
if(stack.length == 0){
// {
System.out.println("Cant peek a ghost");
}
return(stack[--count]);
}
// else
// {
// System.out.println( stack[count-1]);
// }
// }
#Override
public int Size()
{
//Sets the size of this vector
if(stack.length == 0){
System.out.println("Nothing inside");
}
System.out.println("The array's size is : " + count);
return count;
}
}
private static String out;
The value in out is null.
out = out + u;
// This is null = null + u;
Hence the null at the beginning of your output.
You simply need to create a new String object to give out an initial value:
private static String out = "";
i'm not sure why you need the ExpandCapacity bit there, this works aswell:
public static void main(String[] args)
{
String word ="reverse please";
Stack<Character> chStack = new Stack<Character>();
for (int i = 0; i < word.length(); i ++)
{
chStack.push(word.charAt(i));
}
String out = "";
while (chStack.size() != 0)
{
out += chStack.pop();
System.out.println(out);
}
}
There are a few notes:
You are not writing a generic class so drop .
Leave the iteration to for as much as possible.
Try using Java standard classes as much as possible, in this case Stack instead of ArrayStack.
You don't need to resize the stack, it will handle its size dynamically as you put more data in.
You should write the string once you are done creating it not once in every step.
Appending strings using + is very inefficient. Use StringBuilder.
Use methods they make your code readable.
Heres the code:
import java.util.Scanner;
import java.util.Stack;
public class ReverseDriver {
public static String reverse(String string) {
Stack<Character> revStack = new Stack<Character>();
for (char c : string.toCharArray()) {
revStack.push(c);
}
StringBuilder builder = new StringBuilder();
while(!revStack.isEmpty()){
builder.append(revStack.pop());
}
return builder.toString();
}
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
String in = input.nextLine();
System.out.println(reverse(in));
}
}