System.out.print() not printing to terminal - java

This may be a very stupid question but I am trying to modify provided code from Sedgewick's "Algorithms" textbook for a class project. For debugging purposes I just want to print out some information to terminal at various points. Not matter where I insert System.out.println("testing") for example, I recieve no errors and the program runs to completion but nothing was ever printed out. Is it possible that the target destination for printing is not terminal for some reason?
public class LZW {
private static final int R = 256; // number of input chars
private static final int L = 4096; // number of codewords = 2^W
private static final int W = 12; // codeword width
public static void compress() {
String input = BinaryStdIn.readString();
TST<Integer> st = new TST<Integer>();
for (int i = 0; i < R; i++)
st.put("" + (char) i, i);
int code = R+1; // R is codeword for EOF
while (input.length() > 0) {
String s = st.longestPrefixOf(input); // Find max prefix match s.
BinaryStdOut.write(st.get(s), W); // Print s's encoding.
int t = s.length();
if (t < input.length() && code < L) // Add s to symbol table.
st.put(input.substring(0, t + 1), code++);
input = input.substring(t); // Scan past s in input.
}
BinaryStdOut.write(R, W);
BinaryStdOut.close();
}
public static void expand() {
String[] st = new String[L];
int i; // next available codeword value
// initialize symbol table with all 1-character strings
for (i = 0; i < R; i++)
st[i] = "" + (char) i;
st[i++] = ""; // (unused) lookahead for EOF
int codeword = BinaryStdIn.readInt(W);
if (codeword == R) return; // expanded message is empty string
String val = st[codeword];
while (true) {
BinaryStdOut.write(val);
codeword = BinaryStdIn.readInt(W);
if (codeword == R) break;
String s = st[codeword];
if (i == codeword) s = val + val.charAt(0); // special case hack
if (i < L) st[i++] = val + s.charAt(0);
val = s;
}
BinaryStdOut.close();
}
public static void main(String[] args) {
System.out.println("Testing123");
if (args[0].equals("-")) compress();
else if (args[0].equals("+")) expand();
else throw new IllegalArgumentException("Illegal command line argument");
}
}

Related

Trying to determine how to read input from console that could be over 10,000 characters in length

I'm currently trying determine how to use bufferedreader to read from a console program. I know the correct syntax to read from the console and I know the program is working for smaller text. However, any text greater than 5118 characters will be truncated. The console itself will also not print out any text greater than 5118 characters. The goal is to create a java program that will read from the console independent of the size of data being read.
The following is the code I have created.
package countAnagrams;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class TestClass {
public static int check_For_Missing_Characters(String a1, String b1){
int first_String_Length = a1.length();
int missing_Characters = 0;
for( int y = 0; y < first_String_Length; y++ ){
final char character_To_Check_String = a1.charAt(y);
if ( b1.chars().filter(ch -> ch ==
character_To_Check_String).count() == 0 ){
missing_Characters+=1;
}
}
return missing_Characters;
}
public static int check_For_Duplicate_Characters(String a1, String
b1){
int first_String_Length = a1.length();
int duplicat_Characters = 0;
String found_Characters = "";
for( int y = 0; y < first_String_Length; y++ ){
final char current_Character_To_Check = a1.charAt(y);
long first_String_Count = b1.chars().filter(ch -> ch ==
current_Character_To_Check).count();
long second_String_Count = a1.chars().filter(ch -> ch ==
current_Character_To_Check).count();
long found_String_Count = found_Characters.chars().filter(ch -> ch == current_Character_To_Check).count();
if ( first_String_Count > 0 && second_String_Count > 0 && found_String_Count == 0 ){
duplicat_Characters+=Math.abs(first_String_Count - second_String_Count);
found_Characters = found_Characters +
current_Character_To_Check;
}
}
return duplicat_Characters;
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test_Case_Count = Integer.parseInt(br.readLine()); //
Reading input from STDIN
for(int x = 0; x < test_Case_Count; x++ ){
int total_Count_Of_Diff_Chars = 0;
StringBuilder first_StringBuilder = new StringBuilder();
int first_String = '0';
while(( first_String = br.read()) != -1 ) {
first_StringBuilder.append((char) first_String );
}
StringBuilder second_StringBuilder = new StringBuilder();
String second_String = "";
while((( second_String = br.readLine()) != null )){
second_StringBuilder.append(second_String);
}
total_Count_Of_Diff_Chars = total_Count_Of_Diff_Chars +
check_For_Missing_Characters(first_StringBuilder.toString(),
second_StringBuilder.toString());
total_Count_Of_Diff_Chars = total_Count_Of_Diff_Chars +
check_For_Missing_Characters(second_StringBuilder.toString(),
first_StringBuilder.toString());
total_Count_Of_Diff_Chars = total_Count_Of_Diff_Chars +
check_For_Duplicate_Characters(second_StringBuilder.toString(),
first_StringBuilder.toString());
System.out.println(total_Count_Of_Diff_Chars);
}
br.close();
}
}
The above code will work for input that is less than 5118 characters. I would like to understand what is need to make it read beyond the 5118 limit. I'm not sure if the page, I using is causing the limit or there is something that I'm missing. Remember this is also written in java code.

Replace while loop with lambda

I'm learning lambdas and I have an exercise to rewrite the while loop in this code using lambdas. This method gets encoded user input and returns decoded. I faced this problem and can't understand what I'm supposed to do. (I know that it's not hard, but I just can't get the concept.) I didn't find any similar questions here.
p.s. Also, one more qustion - can this while loop( or maybe whole method) be reworked with method reference?
public String decode(String input) {
StringBuilder letters = new StringBuilder();
input = input.toUpperCase();
int i = 0, j = 0;
while (i < input.length()) {
char symbol = input.charAt(i);
char keySymbol = KEY.charAt(j);
int newIndex = (ALPHABET.indexOf(symbol) - ALPHABET.indexOf(keySymbol)) % ALPHABET.length();
char newSymbol = ALPHABET.charAt(newIndex);
letters.append(newSymbol);
j = ++j % KEY.length();
i++;
}
return letters.toString().toLowerCase();
}
The code sample below includes the original decode method, and a new decodeLamda method.
The decodeLambda method replaces the iteration over 'input'. Running the sample will show they both have the same output. It is possible to change the loop to a method reference.
public class Main {
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.decode("SECRET MESSAGE"));
System.out.println(main.decodeLambda("SECRET MESSAGE"));
}
public static String KEY = "HOPSCOTCH";
public static String ALPHABET = "ABCDEFGHIJKLMONOPQRSTUVWXYZ";
public String decode(String input) {
StringBuilder letters = new StringBuilder();
input = input.toUpperCase();
int i = 0, j = 0;
while (i < input.length()) {
char symbol = input.charAt(i);
char keySymbol = KEY.charAt(j);
int newIndex = Math.abs(ALPHABET.indexOf(symbol) - ALPHABET.indexOf(keySymbol)) % ALPHABET.length();
char newSymbol = ALPHABET.charAt(newIndex);
letters.append(newSymbol);
j = ++j % KEY.length();
i++;
}
return letters.toString().toLowerCase();
}
public String decodeLambda(String input) {
StringBuilder letters = new StringBuilder();
input = input.toUpperCase();
var ref = new Object() {
int j = 0;
};
input.chars()
.forEach( symbol -> {
char keySymbol = KEY.charAt(ref.j);
int newIndex = Math.abs(ALPHABET.indexOf(symbol) - ALPHABET.indexOf(keySymbol)) % ALPHABET.length();
char newSymbol = ALPHABET.charAt(newIndex);
letters.append(newSymbol);
ref.j = ++ref.j % KEY.length();
});
return letters.toString().toLowerCase();
}
}

Make parenthesis the first priority on an arithmetic expression on TAC

So I have here my code implementing Three Address Code in arithmetic expression.
class ThreeAddressCode {
private static final char[][] precedence = {
{'/', '1'},
{'*', '1'},
{'+', '2'},
{'-', '2'}
};
private static int precedenceOf(String t)
{
char token = t.charAt(0);
for (int i=0; i < precedence.length; i++)
{
if (token == precedence[i][0])
{
return Integer.parseInt(precedence[i][1]+"");
}
}
return -1;
}
public static void main(String[] args) throws Exception
{
int i, j, opc=0;
char token;
boolean processed[];
String[][] operators = new String[10][2];
String expr="", temp;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter an expression: ");
expr = in.readLine();
processed = new boolean[expr.length()];
for (i=0; i < processed.length; i++)
{
processed[i] = false;
}
for (i=0; i < expr.length(); i++)
{
token = expr.charAt(i);
for (j=0; j < precedence.length; j++)
{
if (token==precedence[j][0])
{
operators[opc][0] = token+"";
operators[opc][1] = i+"";
opc++;
break;
}
}
}
System.out.println("\nOperators:\nOperator\tLocation");
for (i=0; i < opc; i++)
{
System.out.println(operators[i][0] + "\t\t" + operators[i][1]);
}
//sort
for (i=opc-1; i >= 0; i--)
{
for (j=0; j < i; j++)
{
if (precedenceOf(operators[j][0]) > precedenceOf(operators[j+1][0]))
{
temp = operators[j][0];
operators[j][0] = operators[j+1][0];
operators[j+1][0] = temp;
temp = operators[j][1];
operators[j][1] = operators[j+1][1];
operators[j+1][1] = temp;
}
}
}
System.out.println("\nOperators sorted in their precedence:\nOperator\tLocation");
for (i=0; i < opc; i++)
{
System.out.println(operators[i][0] + "\t\t" + operators[i][1]);
}
System.out.println();
for (i=0; i < opc; i++)
{
j = Integer.parseInt(operators[i][1]+"");
String op1="", op2="";
if (processed[j-1]==true)
{
if (precedenceOf(operators[i-1][0]) == precedenceOf(operators[i][0]))
{
op1 = "t"+i;
}
else
{
for (int x=0; x < opc; x++)
{
if ((j-2) == Integer.parseInt(operators[x][1]))
{
op1 = "t"+(x+1)+"";
}
}
}
}
else
{
op1 = expr.charAt(j-1)+"";
}
if (processed[j+1]==true)
{
for (int x=0; x < opc; x++)
{
if ((j+2) == Integer.parseInt(operators[x][1]))
{
op2 = "t"+(x+1)+"";
}
}
}
else
{
op2 = expr.charAt(j+1)+"";
}
System.out.println("t"+(i+1)+" = "+op1+operators[i][0]+op2);
processed[j] = processed[j-1] = processed[j+1] = true;
}
}
}
Sample Output
Input : a * b / c
t1 = a * b
t2 = t1 / c
What the program does is evaluate the arithmetic expression and shows them step by step by operators.
Can you help me to include parenthesis in the priorities? and achieve an output like this
Sample Output
Input : a * ( b + c )
t1 = b + c
t2 = a * t2
Right now, the parenthesis is treated like an operand.
I did not use any of your code. Sorry.
This was a fun one to think about. I have never considered how you would do something like this. It does not follow all of the best practices to a "T", but the question inspired me to consider how you would do this in a rudimentary way.
You could make much of this code smaller by using more Java Frameworks, but it was enjoyable to strictly try to work this out logically.
This code is missing most validation (i.e. The user inputs an erroneous expression)
It does however check if there are an equal number of open and close parenthesis.
Lastly, I had to wrap things up so I did not extend into expressions with nested parenthesis.
Example a * ( b * ( c / d ) - e ) >> this code does not handle this scenario, and would have to be enhanced to accommodate for this.
Otherwise, it should give a pretty good idea as to one way you could go about building a program to work through parenthesis.
I hope it helps
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MathPriority {
public static void main(String[] args) {
String expression = "a * (b * c) + (d / e)"; //You can work out how you want input to com in
List<String> priorityList = getPriorityList(expression);//Find parenthesis and sets priority.
expression = expression.replace(" ", "").replace("(", "").replace(")", "");//Take out any spaces and parenthesis
for (int i = 0; i < priorityList.size(); i++) {//Replaces the piece in parenthesis with var and outputs var
expression = expression.replace(priorityList.get(i), "t" + (i + 1));
System.out.println("t" + (i + 1) + " = " + priorityList.get(i));
}
System.out.println("t" + (priorityList.size() + 1) + " = " + expression);//pushes final variable set
}
//You can use this to build a List of indexes of a character within a String
public static List<Integer> getAllOccurencesOfChar(List<String> expression, String indexO) {
List<Integer> parIndexList = new ArrayList<>();
for (int i = 0; i < expression.size(); i++) {
if (expression.get(i).contains(indexO)) {
if (!parIndexList.contains(i) && i > 0) {
parIndexList.add(i);
}
}
}
return parIndexList;
}
//Outputs a list of substrings. They can later be used to parse through the inital string
public static List<String> getPriorityList(String expression) {
List<String> priorityList = new ArrayList<>();
expression = expression.replace(" ", "");
String[] eParts = expression.split("");
List<String> expressionParts = new ArrayList<>();//Get expression into single chars
for (String e : eParts) {//If you change this to an Array.List, it will not work. This type of list is fixed in size
expressionParts.add(e);
}
List<Integer> parIndexList = getAllOccurencesOfChar(expressionParts, "(");//find all open paranthesis
List<Integer> rParIndexList = getAllOccurencesOfChar(expressionParts, ")");//find all close paranthesis
if (parIndexList.size() != rParIndexList.size()) {
System.out.println("Your Equation does not have an equal number of open and close parenthesis");
System.exit(0);
}
//Work out the parenthesis
int loopIterator = parIndexList.size();//This will change as we iterate
for (int pars = loopIterator - 1; pars >= 0; pars--) {
int start = parIndexList.get(pars); //Define a start
int end = 0; //and End
//int end = rParIndexList.get(pars);
for (int contemplate = 0; contemplate < loopIterator; contemplate++) {//contemplate where given parenthesis starts and where its closing tag is
if (parIndexList.get(pars) < rParIndexList.get(contemplate)) {
end = rParIndexList.get(contemplate);//find first occurence and set true end
break;//then stop
}
}
String expre = "";
for (int concat = start + 1; concat < end; concat++) {
expre += expressionParts.get(concat);//put the priorityList's subExpression together
}
priorityList.add(expre);//add that subExpression to the list
expressionParts.subList(start, end + 1).clear();//remove these expressionParts
/*Re-establish where the parenthesis are, since we removed parts of the expression in the list*/
parIndexList = getAllOccurencesOfChar(expressionParts, "(");//find all open paranthesis
rParIndexList = getAllOccurencesOfChar(expressionParts, ")");//find all close paranthesis
loopIterator = parIndexList.size();//resize the forLoop
}
return priorityList;
}
public static List<Integer> getStartEndPosition(String fullExpression, String subExpression) {
List<Integer> sAndE = new ArrayList<>();
String[] eParts = subExpression.split("");
List<String> wordParts = new ArrayList<>();
wordParts.addAll(Arrays.asList(eParts));
/*Find multiples of same operand*/
List<Integer> add = getAllOccurencesOfChar(wordParts, "+");
List<Integer> subtract = getAllOccurencesOfChar(wordParts, "-");
List<Integer> divide = getAllOccurencesOfChar(wordParts, "/");
List<Integer> multiply = getAllOccurencesOfChar(wordParts, "*");
/*Find single Operands*/
int plus = subExpression.indexOf("+");
int minus = subExpression.indexOf("-");
int div = subExpression.indexOf("/");
int mult = subExpression.indexOf("*");
int multiOperands = plus + minus + div + mult;//See if multiples exist
int startingPosition = 0;
if (add.size() > 1 || subtract.size() > 1 || divide.size() > 1 || multiply.size() > 1
|| multiOperands > 0) {
//expression has multiple opreands of different types
String findStart = wordParts.get(0) + wordParts.get(1);
String findEnd = wordParts.get(wordParts.size() - 2) + wordParts.get(wordParts.size() - 1);
startingPosition = fullExpression.indexOf(findStart);
sAndE.add(startingPosition);
int endPosition = fullExpression.indexOf(findEnd);
sAndE.add(endPosition);
} else {
startingPosition = fullExpression.indexOf(subExpression);
sAndE.add(startingPosition);
sAndE.add(startingPosition + subExpression.length());
}
return sAndE;
}
}
String expression = "a * (b * c) + (d / e)"
Outputs:
t1 = d/e
t2 = b*c
t3 = a*t2+t1

LZW Compression/ Expansion in Java

I am trying to use the LZW code provided by Princeton and modify it to vary the size of codeword from 9 to 16 bits. I am unsure of how to do this, but was thinking of maybe using a loop since the size needs to be increased when all codewords of the size before were used. I am just looking for a useful direction to go in, since this is an assignment that I am having trouble starting.
public class LZW {
private static final int R = 256; // number of input chars
private static final int L = 4096; // number of codewords = 2^W
private static final int W = 12; // codeword width
public static void compress() {
String input = BinaryStdIn.readString();
TST<Integer> st = new TST<Integer>();
for (int i = 0; i < R; i++)
st.put("" + (char) i, i);
int code = R+1; // R is codeword for EOF
while (input.length() > 0) {
String s = st.longestPrefixOf(input); // Find max prefix match s.
BinaryStdOut.write(st.get(s), W); // Print s's encoding.
int t = s.length();
if (t < input.length() && code < L) // Add s to symbol table.
st.put(input.substring(0, t + 1), code++);
input = input.substring(t); // Scan past s in input.
}
BinaryStdOut.write(R, W);
BinaryStdOut.close();
}
public static void expand() {
String[] st = new String[L];
int i; // next available codeword value
// initialize symbol table with all 1-character strings
for (i = 0; i < R; i++)
st[i] = "" + (char) i;
st[i++] = ""; // (unused) lookahead for EOF
int codeword = BinaryStdIn.readInt(W);
if (codeword == R) return; // expanded message is empty string
String val = st[codeword];
while (true) {
BinaryStdOut.write(val);
codeword = BinaryStdIn.readInt(W);
if (codeword == R) break;
String s = st[codeword];
if (i == codeword) s = val + val.charAt(0); // special case hack
if (i < L) st[i++] = val + s.charAt(0);
val = s;
}
BinaryStdOut.close();
}
public static void main(String[] args) {
if (args[0].equals("-")) compress();
else if (args[0].equals("+")) expand();
else throw new IllegalArgumentException("Illegal command line argument");
}
}

Find non-repeated character in a string

I have to create a program for returning the next non-repeated character..
ex I give ... tweet
and it should return output as w...
public class str_next {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string");
String s = br.readLine();
revString(s);
}
static char revString(String str) {
int i = 0;
int j;
int n = str.length();
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
char c = str.charAt(i);
char d = str.charAt(j);
if (c != d) {
System.out.print(d);
}
}
}
}
}
I am getting error as .. missing return statement..
Can anyone please tell me.. How do I solve such a problem.. Where am I wrong..?
To solve your problem simply add,
return d;
in your function. But it's better to understand how this actually works:
Functions/Methods are written as
accessor_type return_type function_name(parameter_list)
{
//stuff to do in your code
}
For e.g.
public char returnChar(int a)
| | | |
| | | |
^ ^ ^ ^
accessor return name parameter
this means that this function will return a character.
In the sense, you need to a char like this in your function
return char;
Try reading up on methods and their return types. :)
References:
Defining Methods
Return a value from a method
you have not written the return statement.Use return ;
You have written the return type for revString(String str) as char and you are not returning any character.
Change that return type to void
or add line return d; to the method
You have missing the return statement in your code.
here is the code which returns what you want
CODE
public static Character findFirstNonRepeated(String input) {
// create a new hashtable:
Hashtable<Character, Object> hashChar = new Hashtable<Character, Object>();
int j, strLength;
Character chr;
Object oneTime = new Object();
Object twoTimes = new Object();
strLength = input.length();
for (j = 0; j < strLength; j++) {
chr = new Character(input.charAt(j));
Object o = hashChar.get(chr);
/*
* if there is no entry for that particular character, then insert
* the oneTime flag:
*/
if (o == null) {
hashChar.put(chr, oneTime);
}
/*
*/
else if (o == oneTime) {
hashChar.put(chr, twoTimes);
}
}
/*
* go through hashtable and search for the first nonrepeated char:
*/
int length = strLength;
for (j = 0; j < length; j++) {
chr = new Character(input.charAt(j));
Object c = null;
if (hashChar.get(chr) == oneTime)
return chr;
}
/*
* this only returns null if the loop above doesn't find a nonrepeated
* character in the hashtable
*/
return null;
}
Use like this
char my = findFirstNonRepeated("twwwweety");
System.out.println(my);
This will return y.
Add each character to a HashSet and check whether hashset.add() returns true, if it returns false ,then remove the character from hashset. Then getting the first value of the hashset will give you the first non repeated character.
Algorithm:
for(i=0;i<str.length;i++)
{
HashSet hashSet=new HashSet<>()
if(!hashSet.add(str[i))
hashSet.remove(str[i])
}
hashset.get(0) will give the non repeated character.
Try this,
// Split the string into characters
// Check if entry exists in the HashMap, if yes- return the character, if No- inert the element with value 1
public static void main(String[] args) {
String s = "rep e atit";
char c = nonRepeat(s);
System.out.println("The first non repeated character is:" + c);
}
private static char nonRepeat(String ss) {
char c;
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for (int i = 0; i < ss.length(); i++) {
c = ss.charAt(i); // get each chaar from string
if (hm.containsKey(c)) {// char is already in map, increase count
hm.put(c, hm.get(c) + 1);
return c;
} else {
hm.put(c, 1);
}
}
return '0';
}
IN JAVA
using for loop only.....
it is very easy....you can do it without collection in java..
just try it.....
public class FirstNonRepeatedString{
public static void main(String args[]) {
String input = "tweet";
char process[] = input.toCharArray();
boolean status = false;
int index = 0;
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process.length; j++) {
if (i == j) {
continue;
} else {
if (process[i] == process[j]) {
status = false;
break;
} else {
status = true;
index = i;
}
}
}
if (status) {
System.out.println("First non-repeated string is : " + process[index] + " INDEX " + index);
break;
}
}
}
}
public class JavaPractice {
public static void main(String args[])
{
System.out.println("Enter input String");
Scanner s= new Scanner(System.in);
String input= s.nextLine();
int length=input.length();
for(int i=0;i<length;i++)
{
int temp=0;
for(int j=0;j<length;j++)
{
if(input.charAt(i)==input.charAt(j))
{temp++;}
}
if(temp==1)
{System.out.println(input.charAt(i));}
}
}
}
your program should be like this:
import java.io.*;
public class str_next {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string");
String s = br.readLine();
revString(s);
}
static char revString(String str) {
int i = 0;
int j;
int n = str.length();
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
char c = str.charAt(i);
char d = str.charAt(j);
if (c != d) {
System.out.print(d);
}
}
}
return 0;
}
}

Categories

Resources