My Java project doesn't print out anything [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Here is my code:
public class Code {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
reverse(-123);
}
public static int reverse(int x) {
String str = Integer.toString(x);
char c[] = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
c[i] = str.charAt(str.length() - 1 - i);
}
if (c[str.length()-1] == '-') {
for (int i=c.length-2; i >=0; i--) {
c[i+1] = c[i];
}
c[0] = '-';
}
String n = new String(c);
int re = Integer.parseInt(n);
return re;
}
}
I'm doing a Java exercise which is to change the order of an Integer to reverse with the '-' in it, but when I run the program, it doesn't print out anything, please help me solve this!!

public static void main(String[] args) {
System.out.println(reverse(-123));
}
should work now, you missed print statement.

To print we need to add a print statement i.e,
System.out.println(reverse(-123));

Just add System.out.println where you called the function reverse
public class Code {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(reverse(-123));
}
public static int reverse(int x) {
String str = Integer.toString(x);
char c[] = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
c[i] = str.charAt(str.length() - 1 - i);
}
if (c[str.length()-1] == '-') {
for (int i=c.length-2; i >=0; i--) {
c[i+1] = c[i];
}
c[0] = '-';
}
String n = new String(c);
int re = Integer.parseInt(n);
return re;
}
}

Related

Converting infix to postfix and getting an EmptyStackException

I am working on a project to convert infix notation to postfix notation and then evaluate the equation. I established the precedence for each operator. When I use the ConvertToPostfix method I get the Exception. I understand the concept of the reverse polish notation calculator and I am just struggling with doing it with my code. I am new to stack overflow so if there is something that may seem a little confusing just let me know and ill try to edit it.
import java.util.Stack;
public class RPNCalctest {
public static void main( String[] args) throws InvalidInfixEquationException {
String example= "3+4/3*2"; //postfix notation would be 3 4 3 / 2 * +
System.out.println(ConvertToPostfix(example));
// TODO
}
//establish precedence
static int precedence(String c){
switch(c){
case"+":
case"-":
return 1;
case"*":
case"/":
return 2;
case")":
return 3;
case"(":
return 4;
default:
return -1;
}
}
// Precondition: every operator/operand will be separated by at least one space
public static String ConvertToPostfix(String infix) throws InvalidInfixEquationException {
String[] tokens = infix.split(" ");
String result = "";
Stack<String> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String current = tokens[i];
if (precedence(current) > 0) {
while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(current)) {
result += stack.pop() + " ";
}
stack.push(current);
} else {
result += current + " ";
}
}
for (int i = 0; i <= stack.size(); i++) {
result += stack.pop();
}
return result;
}
}
Exception in thread "main" java.util.EmptyStackException
at java.base/java.util.Stack.peek(Stack.java:101)
at java.base/java.util.Stack.pop(Stack.java:83)
at RPNCalctest.ConvertToPostfix(RPNCalctest.java:50)
at RPNCalctest.main(RPNCalctest.java:7)
Your problem is here. You pop off one more entry than there is.
for (int i = 0; i <= stack.size(); i++) {
result += stack.pop();
}
Consider size=2. You execute the loop for i=0, 1, 2.
I assume that the 'pop' line is line 53 as indicated in the stack trace, so for future reference, that's useful debugging info and you should use it.
It might be clearer if that loop were coded:
while (!stack.isEmpty()) {
result += stack.pop();
}
No need for the extraneous variable 'i'.

check two conditions in if statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am checking for 2 conditions, and I need that both of them would work,
but work only one of them. Where I am making the mistake? I need to print indexes of positions of ch1 and ch2 in String text
import java.util.Scanner;
public class TestIndexOf {
private static String text;
private static char ch1, ch2;
public static void main(String[] args) {
TestIndexOf test = new TestIndexOf();
test.getInput();
System.out.println(test.getIndex(text, ch1, ch2));
}
public static void getInput() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter word and chars: ");
text = scan.nextLine();
ch1 = scan.next().charAt(0);
ch2 = scan.next().charAt(0);
}
public static int getIndex(String text, char ch1, char ch2) {
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ch1) {
return i;
}
if (text.charAt(i) == ch2) {
return i;
}
}
return -1;
}
}
If I understand correctly, you want to know the position of both char1 and char2.
The way you have written your logic, it can only return one value.
You need to remove the return statement and collect the results in some variable.
Then return that variable instead at the end.
or something like this should work:
public class TestIndexOf {
// private static String text;
// private static char ch1, ch2;
public static void printIndex(String text, char ch1, char ch2) {
int count = 0;
boolean isCharAIndexNotPrinted = true;
boolean isCharBIndexNotPrinted = true;
for (int i = 0; i < text.length(); i++) {
if(count==2)
break;
if (text.charAt(i) == ch1 && isCharAIndexNotPrinted) {
count++;
isCharAIndexNotPrinted = false;
System.out.println("char1 is " + i);
}
if (text.charAt(i) == ch2 && isCharBIndexNotPrinted) {
count++;
isCharBIndexNotPrinted = false;
System.out.println("char2 is " + i);
}
}
}
}

Why won the if statement execute? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I wrote a simple program in Java which writes a word backwards. Trying to check if "hello" works. In if-statement I'm checking that string is equal to "olleh". Could anyone see why the if statement won't execute.
public class MyProgram {
public static void main(String[] args) {
String x = "hello";
System.out.println(back(x));
}
public static String back(String str) {
String y = " ";
String temp = " ";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
}
Try this it will work
public class MyProgram
{
public static void main(String[] args)
{
String x = "hello";
System.out.println(back(x));
}
public static String back(String str )
{
String temp = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
temp = temp + lets;
}
if (temp.equals("olleh")) {
System.out.println("nice");
}
return temp;
}
}
If you will initialize y variable to empty string instead of space your if-statement will execute and print "nice". Also you do not need a temp string as you don't use it. You probably want to return you reverted string back (alternatively you can make your method void and remove the return statement).
public static String back(String str) {
String y = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
By the way, it's better to use StringBuilder when you're concatenating strings in a loop.

Sort an array list of pathnames in java without comparator [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
My user input is
\home\me\cs1
\usr\share
\var\log
\usr\local\jdk1.6.0\jre\lib
and I need to sort these pathnames so that the output is in the correct lexographic order. However they are first sorted by length which is the number of slashes in each string. The path names are stored in an arraylist of strings. I attempting to do this without the use of collections,comparator or arrays. Would this be possible with the use of ArrayList?
the output should be:
\usr\share
\var\log
\home\me\cs1
\usr\local\jdk1.6.0\jre\lib
This is my code so far:
import java.util.ArrayList;
import java.util.Scanner;
public class FileName
{
private ArrayList<String> pathNames;
public FileName()
{
pathNames = new ArrayList<String>();
}
public void printPaths()
{
for(int i = 0; i < pathNames.size(); i++)
{
System.out.println(pathNames.get(i));
}
}
public int pathLength(String path)
{
int count = 0;
String slash = "\\";
for(int i = 0; i < path.length(); i++)
{
if(path.substring(i,i + 1).equals(slash))
{
count++;
}
}
return count;
}
public void sort()
{
pathNames = mergeSort(pathNames);
}
public ArrayList<String> mergeSort(ArrayList<String> paths)
{
if(paths.size() == 1)
{
return paths;
}
else
{
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
int middle = paths.size() / 2;
for(int i = 0; i < middle; i++)
{
left.add(paths.get(i));
}
for(int i = middle; i < paths.size(); i++)
{
right.add(paths.get(i));
}
right = mergeSort(left);
left = mergeSort(left);
merge(left, right, paths);
}
return paths;
}
public void merge(ArrayList<String> left, ArrayList<String> right, ArrayList<String> paths)
{
int leftNum = 0;
int rightNum = 0;
int pathsNum = 0;
while (leftNum < left.size() && rightNum < right.size())
{
if ((left.get(leftNum).compareTo(right.get(rightNum)))<0)
{
paths.set(pathsNum, left.get(leftNum));
leftNum++;
}
else
{
paths.set(pathsNum, right.get(rightNum));
rightNum++;
}
pathsNum++;
}
ArrayList<String>rest;
int restNum;
if (leftNum >= left.size())
{
rest = right;
restNum = rightNum;
}
else
{
rest = left;
restNum = leftNum;
}
for (int i = restNum; i < rest.size(); i++)
{
paths.set(pathsNum, rest.get(i));
pathsNum++;
}
}
public void readInput()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a list of path names.(press enter after each path name, and type \"stop\" once you are finished.");
String termination = "stop";
String in = input.nextLine();
boolean reading = true;
while(reading)
{
pathNames.add(in);
if(in.equals(termination))
{
reading = false;
return;
}
in = input.nextLine();
}
}
}
This is my main method.
public class FileNamePrgm
{
public static void main(String [] args)
{
FileName paths = new FileName();
paths.readInput();
paths.sort();
}
}
You have a typo:
right = mergeSort(left);
Should be
right = mergeSort(right);
Also you need to add in = input.nextLine(); once more inside the while loop. Currently you are reading only one line from the input and checking it over and over again.

Syntax Error, Insert } to Complete Block [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
import java.util.*;
public class Programming {
public static void main(String[] args) {
//Scanner scan = new Scanner( System.in );
int l=0;
StringBuilder password = new StringBuilder();
public static boolean matchCharAt(StringBuilder password, int l){
l = password.length();
if (l < 0 || l > 100){
return false;
}
for (int i = 0; i < password.length();i++){
if (!Character.isLetter(password.charAt(l)))
return false;
}
return true;
}
}
It says I have an error on the line with { for (l=0; l < 100; l++); }, but i'm not sure if thats where the Curly brace error is. It might not be a curly brace error, i'm unsure, but I was hoping I could get some help to not have this error.
You never close the main() method block:
public static void main(String[] args) {
//Scanner scan = new Scanner( System.in );
int l=0;
StringBuilder password = new StringBuilder();
{
for (l = 0; l < 100; l++);
}
} //HERE!
Besides this loop:
for (l = 0; l < 100; l++);
is not doing anything except changing the value of l to 100. Also the loop is surrounded with a block that has no practical sense. I can only guess this is what you wanted:
for (l = 0; l < 100; l++) {
matchCharAt(password, l);
//...
}
This is corollary to your main problem, but you are also changing an argument in this method
public static boolean matchCharAt(StringBuilder password, int l){
l = password.length();
if (l < 0 || l > 100){
return false;
}
If you're passing in l, then you're going to be changing its value with l = password.length().
I'm not sure exactly what you want. This should at least compile:
public class SomeClass {
public static void main(String[] args) {
//Scanner scan = new Scanner( System.in );
int l=0;
StringBuilder password = new StringBuilder();
for (l = 0; l < 100; l++) {
; // Does nothing...
}
} // end of "main()"
public static boolean matchCharAt(StringBuilder password, int l){
l = password.length();
if (l < 0 || l > 100){
return false;
}
for (int i = 0; i < password.length();i++){
if (!Character.isLetter(password.charAt(l)))
return false;
}
return true;
} // end of "matchCharAt()"
} // end of class

Categories