A lot of this code is already written but the code that I have added was to include ^ and %. It is the code to evaluate an expression in the right order using stacks. What I'm having trouble with this is the main method and adding a way to take user input and print out the result of the problem. I'm just including that part of the code
16 import java.util.Stack;
17 import java.util.Scanner;
18
19 public class EvaluateExpression {
20 public static void main(String[] args) {
21
22 Scanner input = new Scanner(System.in);
23 System.out.println("Enter the expression to be evaluated: ");
24 String expression = input.nextLine();
25
26 //Check number of arguments passed
27 if (args.length != 1) {
28 System.out.println("Usage: java EvaluateExpression \"expression\"");
29 System.exit(1);
30 }
31 try {
32 System.out.println(expression + " = " +
33 evaluateExpression(expression));
34 }
35 catch (Exception ex) {
36 ex.printStackTrace();
37 System.out.println("Wrong expression: " + expression);
38 }
39
40 }
Expected results: it is printing the expression to be evaluated along with the results.
But here is what I am getting with this when I try to enter a random expression:
Enter the expression to be evaluated:
6+9*8-7
Usage: java EvaluateExpression "expression"
It simply means that args.length is different than 1.
Your program is reading from standard input. Don't need to check args count. Args is program arguments that direct input of your program. Like
ls *.txt
or
java -cp . EvaluateExpression <myvalue>
Hope this helps.
Related
I'm trying to find two specific numbers (25,55) in a input list by converting them to tokens. e.g. below - string list = (52 98 55 86 42 25 87 566 56 843).
Just for context, the numbers are prices for books bought in a week for a library.
If they are both in a line only then I want to know (print "both"). If only one of them is in the line or something like 5562 or 3259 (part of another number), i want a return of "no". I guess that's why I'm converting them to tokens.
This code below is not working unless i remove the else statement and even when i do remove it, it prints out "both" no matter what I numbers i put in, even if there's no 25 or 55. Sorry if this seems like a dumb question, pretty new to coding.
package part;
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
public class Part {
public static void main(String[] args) throws Exception {
String list = "52 98 55 86 42 25 87 566 56 843";
StringTokenizer tokenizer = new StringTokenizer(list);
String rp = tokenizer.nextToken();
if (rp.equals("25") && rp.equals ("55")){
System.out.println("both");
} else {
System.out.println("no");
}
}
StringTokenizer works like ResultSet when fetching queries in DB side. Considering it, you should do something like this:
public static void main(String[] args) throws Exception {
String list = "52 98 55 86 42 25 87 566 56 843";
List<String> tokenList = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(list);
while(tokenizer.hasMoreTokens()){
tokenList.add(tokenizer.nextToken());
}
if(tokenList.contains("25") && tokenList.contains("55")){
System.out.println("both");
} else {
System.out.println("no");
}
}
StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).
Try using below code if you want to check that the contains both of them.
String list = "52 98 55 86 42 25 87 566 56 843";
String[] strarr = list.split("\\s+");
boolean first;
boolean second;
for(String str:strarr){
if(str.equals("25")) first=true;
if(str.equals("55")) second=true;
if(first && second) break;
}
if(first && second) System.out.println("both");
else System.out.println("no");
I have been running through this array of objects trying to figure out what I am doing wrong and I can't see the error. This program runs through the first iteration bringing in Austria and all its subsequent information but will not move onto the second part of the array. I thought it might be that it's somehow taking each variable from the countries class and making it its own spot in the array but that can't be it because I have increased the array size to 64 and it still stops at the end of Austria. I have been able to get it to go a bit further by placing print statements after each item is added and it seems to be adding an unaccounted for blank line in it for some reason and I'm not sure why. any help that could be given would be greatly appreciated.
This is my test code with the data list:
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main (String [] args) throws IOException {
final String INPUT_FILE = "CountriesInfo2.txt";
FileReader inputDataFile = new FileReader (INPUT_FILE);
Scanner read = new Scanner (inputDataFile);
Countries[] c = new Countries[8];
for (int i = 0; i < c.length; i++) {
c[i] = new Countries();
c[i].countryName = read.nextLine();
c[i].latitude = read.nextLine();
c[i].longitude = read.nextLine();
c[i].countryArea = read.nextInt();
c[i].countryPopulation = read.nextInt();
c[i].countryGDP = read.nextDouble();
c[i].countryYear = read.nextInt();
sop ("" + c[i].countryName + "\n" + c[i].latitude+"\n"+c[i].longitude+"\n"+c[i].countryArea+"\n"+
c[i].countryPopulation+"\n"+c[i].countryGDP+"\n"+c[i].countryYear);
}// end for
} // End Main
public static void sop (String s) {
System.out.println(s);
} // End sop
} // end class
Austria
47 20 N
13 20 E
83871 8754513 417.2 2016
Belgium
50 50 N
04 00 E
30528 11491346 509.5 2016
Czech Republic
49 45 N
15 30 E
7886
10674723
350.7
2016
France
46 00 N
02 00 E
643801
67106161
2734.0
2016
This list is supposed to be one line for each bit of information with lat-long having 2 sets of double digits and a letter each.
nextLine() automatically moves the scanner down after returning the current line. Rather I would advise you do as following
read each line using String data = scanner.nextLine();
split the data using space separator String[] pieces =
data.split("\\s+");
set the pieces to Country attributes by converting them in to
their appropriate type.
eg. c[i].countryName = pieces[0];
`c[i].latitude = piece[1];`
I have a code in my android phone to find duplicate numbers via collections.frequency. This code works fine in a java program only on android. But not as an app on android. Here is what I have as a code in android.
ArrayList<String> ll = new ArrayList<String>();
String item = inputText.getText().toString();
ll.add(item);
HashSet<String> set = new HashSet<>(ll);
for (String temp : set)
{
answertext.setText(temp + "shows that many times: " + Collections.frequency(ll, temp));
}
The output is as follows:
33 44 33 44 shows that many times: 1
It does not find any duplicates if the numbers are input by user via textbox.
However, if a take the userinput away in the code and replace it with this input:
ll.add("33");
ll.add("44");
ll.add("33");
ll.add("44");
ll.add("24");
ll.add("24");
the output will be like so:
44 shows that many times: 2
So here with this input the collections.frequency is working to find a duplicate number. But why only one number? And why 44 and not 33? And why is it not outputting all duplicate numbers like it does as a java program only on the phone. Without Android involved?
I'd like to make it work with userinput from a textbox.
On the Java side where it works fine I got this code:
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the amount of numbers you want to input: Input numbers separated by a space.");
int n = stdin.nextInt();
for (int i = 0; i < n; i++)
{
list.add(stdin.next());
}
System.out.println("\nCount all with frequency");
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet)
{
System.out.println(temp + " shows that many times : " + Collections.frequency(list, temp));
}
//Enter the amount of numbers you want to input
12 //hit the return key
22 33 44 22 33 44 22 33 44 22 33 44
//the output is like so:
Count all with frequency
33 shows that many times: 4
44 shows that many times: 4
22 shows that many times: 4
Why is this code working in Java but not on android?
String item = inputText.getText().toString();
ll.add(item);
This adds one item to the list. I'm guessing you wanted to add each word separately, which you can do like this:
// split the input apart at the spaces
String[] items = inputText.getText().toString().split(" ");
// then add each part separately to the list
for(String item : items)
ll.add(item);
Your second problem is that setText... sets the text. It doesn't add to the end of the text, it replaces what's already there. I don't know how you intended to display multiple strings, but you could do something like this:
// clear answertext
answertext.setText("");
for (String temp : set)
{
// set the text to <whatever was already there> followed by this item
answertext.setText(answertext.getText() + temp + "shows that many times: " + Collections.frequency(ll, temp) + "\n");
}
I was trying this code snippet-
import java.io.*;
class demo
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int c;
do
{
c= (char)br.read();
System.out.println(c);
}while(c!='q');
}
}
Now when I give input-22
output is- 50
50
13
10
I understand the output 50, 50 but why the the compiler is printing 13 and 10 ?
Kindly help.
Thanks!
I think 13 and 10 are CR/LF: the end of the line.
your input is
22<enter>
so your ascii for 2 is 50 hence 22 50 50
Pressing Enter causes Windows to store a carriage return code (ASCII 13) followed by a new-line code (ASCII 10) in the key buffer and hence you see 13 and 10 in the output.
You could also refer a good blog here http://www.javaworld.com/article/2075069/core-java/the-ins-and-outs-of-standard-input-output.html
I am trying to make a calculator that adds and subtracts numbers entered from the user that are in parenthesis.
Here is a sample run:
Welcome to the Expression Program
Enter a line of expressions:
( 2 + 3 + -4 + 5 ) (6+7+8+-9)( 3 + -2 +7+0)
The value of “( 2 + 3 + -4 + 5 )” is 6
The value of “(6+7+8+-9)” is 12
The value of “( 3 + -2 +7+0)” is 8
Goodbye!
Welcome to the Expression Program
Enter a line of expressions:
(6) () (hello + friend ) ( 1 * 2 + 4 ) 7+8+9)
The value of “(6)” is 6
ERROR: “” is not an integer
ERROR: “hello” is not an integer
ERROR: “*” is not a valid operator
ERROR: Illegal start character ‘7’Goodbye!
This is what I have so far but it is not working:
import java.util.Scanner;
public class ExprParser
{
public static void main(String args[])
{
Scanner g=new Scanner(System.in);
System.out.println("Welcome to the Expression Program!");
System.out.println("Enter a line of expressions(between parenthesis):");
String exp=g.next();
String[] arr=exp.split("\\)");
for (int i = 0; i < arr.length; ++i)
{ System.out.println(arr[i]+")");
int result=calculate(arr[i]);
System.out.println(calculate(Integer.toString(result)));
}
}
public static int calculate(String a)
{
int sum=0;
for (int i=0;i<a.length();++i)
{
char sign='+';
a.indexOf(sign);
sum+=Integer.parseInt(a.substring(0,sign))+Integer.parseInt(a.substring(sign+1,sign));
}
return sum;
}
}
I think what you are looking for is Reverse Polish Notation which allows you to evaluate expressions. There is a video here that explains how it works: http://www.youtube.com/watch?v=QzVVjboyb0s
In this code:
char sign='+';
a.indexOf(sign);
sum+=Integer.parseInt(a.substring(0,sign))+Integer.parseInt(a.substring(sign+1,sign));
sign is a character, and characters are actually integer values. The character '+' has the value 43 (that's where the plus sign is on the ASCII chart). So you're trying to compute a.substring(0,43), which will get you an out-of-bounds error if a is shorter than 43 characters.
You used indexOf to find out where the '+' sign is, but you threw away the result. Store the result of indexOf in a variable, then use that variable, not sign, in the substring calls. Also make sure you handle the case when indexOf returns -1 (it can't find a plus sign); if you just pass that to a.substring, you'll get another out of bounds error.