I have a problem about the last part of the code. I want to assign numbers to specific words but i always get 0 value, even though I get those strings from the first System.out.println correctly, i cannot get the numerical equivalents of those strings at the second System.out.println.Any ideas how to solve this problem?
public static double number;
protected void myMethod(HttpServletRequest request, HttpServletResponse response) {
String speech= request.getParameter("speech");
System.out.println("The recognized speech is : "+ speech);
// There is no problem till here.
if(speech == "Hi")
number = 1 ;
if(speech== "Thanks")
number = 2 ;
if(speech== "Bye")
number = 0 ;
System.out.println("The number for the speech is : " + number);
}
However here i dont get the correct numbers but only 0 for each word!
The == will only be true if the Strings are the same object. Use:
if(speech.equals("Hi"))
or to match without case:
if(speech.equalsIgnoreCase("hi"))
You can't use the == operator to check if two Strings have the same value in Java, you need to use the .equals() or equalsIgnoreCase() methods instead:
if("Hi".equalsIgnoreCase(speech)) {
number = 1;
}
else if("Thanks".equalsIgnoreCase(speech)) {
number = 2;
}
else if("Bye".equalsIgnoreCase(speech)) {
number = 0;
}
else {
number = -1;
}
The reason for this is that the == operator compares references; that is it will return true if and only if the instance stored in variable speech is the same instance as the literal String you've created between double quotes ("Hi", "Thanks", or "Bye").
Note also that I use the equalsIgnoreCase() call on the literal String I'm declaring, rather than the variable that is assigned from the parameter. This way, if a speech == null, the method call is still valid ("Hi" will always be a String), and so you won't get a NullPointerException, and the flow will continue until the else branch.
Try the following snippet:
Main.java
public class Main {
public static void main(String[] args) {
List<StringWithValue> stringList = new ArrayList<StringWithValue>();
stringList.add(new StringWithValue("Hi", 1));
stringList.add(new StringWithValue("Thanks", 2));
stringList.add(new StringWithValue("Bye", 3));
String speech = "Hi";
int number = 0;
for(StringWithValue swv : stringList){
if(swv.getString().equals(speech)){
number = swv.getValue();
break;
} else {
number = -1;
}
System.out.println("The number for the speech is : " + number);
}
}
StringWithValue.java
public class StringWithValue {
private String string;
private int value;
public StringWithValue(String string, int value) {
this.string = string;
this.value = value;
}
public String getString() {
return string;
}
public int getValue() {
return value;
}
}
public static double number;
if(speech=="hi")
{
number=1;
}
else if(speech=="thanks")
{
number=2;
}
else if(speech=="Bye")
{
number=0;
}
else
{
System.out.println("Word Not Found");
}
Related
There's three pieces of the code I was given in my BigInteger homework that requires us to store, as the name suggests, integers of extreme size into linked lists, given a String input.
If given a string "0054321" the resulting linked list will store 1->2->3->4->5 in positional order, disregarding insignificant digits.
But as I try to traverse through the string, I am trying to increment numDigits by 1 each time I find a significant digit.
BigInteger.java (The code I'm working on right now)
package bigint;
import sun.security.x509.InvalidityDateExtension;
public class BigInteger {
boolean negative;
int numDigits;
DigitNode front;
public BigInteger() {
negative = false;
numDigits = 0;
front = null;
}
public static BigInteger parse(String integer)
throws IllegalArgumentException {
int a = 0;
int b = 0;
this.front = new DigitNode(1, null);
int length = integer.length();
while (length > 0 && a <= length) {
if (integer.charAt(a) == '-') {
this.negative = true;
a++;
}
if (integer.charAt(a) == ' ' && this.numDigits == 0) {
a++;
}
if (integer.charAt(a) == ' ' && this.numDigits == 0) {
a++;
continue;
}
if (Character.isDigit(integer.charAt(a))) {
if(integer.charAt(a) == ' ' && this.numDigits == 0) {
a++;
continue;
}
this.numDigits = this.numDigits + 1;
}
/* IMPLEMENT THIS METHOD */
}
// following line is a placeholder for compilation
return null;
}
DigitNode.java (The class that encapsulates the linked list, NOT ALLOWED TO EDIT THIS)
package bigint;
public class DigitNode {
int digit;
DigitNode next;
DigitNode(int digit, DigitNode next) {
this.digit = digit;
this.next = next;
}
public String toString() {
return digit + "";
}
}
BigTest.java (The tester class that tests whether the parse/add/multiply methods word, NOT ALLOWED TO EDIT THIS)
package bigint;
import java.io.IOException;
import java.util.Scanner;
public class BigTest {
static Scanner sc;
public static void parse()
throws IOException {
System.out.print("\tEnter integer => ");
String integer = sc.nextLine();
try {
BigInteger bigInteger = BigInteger.parse(integer);
System.out.println("\t\tValue = " + bigInteger);
} catch (IllegalArgumentException e) {
System.out.println("\t\tIncorrect Format");
}
}
public static void add()
throws IOException {
System.out.print("\tEnter first integer => ");
String integer = sc.nextLine();
BigInteger firstBigInteger = BigInteger.parse(integer);
System.out.print("\tEnter second integer => ");
integer = sc.nextLine();
BigInteger secondBigInteger = BigInteger.parse(integer);
BigInteger result = BigInteger.add(firstBigInteger,secondBigInteger);
System.out.println("\t\tSum: " + result);
}
public static void multiply()
throws IOException {
System.out.print("\tEnter first integer => ");
String integer = sc.nextLine();
BigInteger firstBigInteger = BigInteger.parse(integer);
System.out.print("\tEnter second integer => ");
integer = sc.nextLine();
BigInteger secondBigInteger = BigInteger.parse(integer);
BigInteger result = BigInteger.multiply(firstBigInteger,secondBigInteger);
System.out.println("\t\tProduct: " + result);
}
public static void main(String[] args)
throws IOException {
// TODO Auto-generated method stub
sc = new Scanner(System.in);
char choice;
while ((choice = getChoice()) != 'q') {
switch (choice) {
case 'p' : parse(); break;
case 'a' : add(); break;
case 'm' : multiply(); break;
default: System.out.println("Incorrect choice");
}
}
}
private static char getChoice() {
System.out.print("\n(p)arse, (a)dd, (m)ultiply, or (q)uit? => ");
String in = sc.nextLine();
char choice;
if (in == null || in.length() == 0) {
choice = ' ';
} else {
choice = in.toLowerCase().charAt(0);
}
return choice;
}
}
However, I get the errors of:
java: non-static variable this cannot be referenced from a static context,
For any this.numDigits or this.front or this.negative.
Whenever I try to increase numDigits, or change the value of the integer to positive, it happens. Somebody please help, Data Structures is really kicking my butt right now.
this refers to the instance that is calling a method. Static methods do not have an associated instance (generally shouldn't be called from an instance at all), and therefore there is no this instance.
However, you can create an instance inside of your static method and affect its fields, for example:
public static BigInteger parse(String integer)
throws IllegalArgumentException {
BigInteger parsedBI = new BigInteger();
//...
parsedBI.front = new DigitNode(1, null);
//...
parsedBI.numDigits = parsedBI.numDigits + 1;
//...
}
Also (I'm one to talk as an SO noob myself), avoid giving more code in your questions than is needed (minimal reproducible example).
public static BigInteger parse(String integer)
The parse method is defined as a static function, so it doesn't have access to any BigInteger instance. "this" is meaningless. No instance has been created yet.
You could create a new BigInteger instance inside of parse method. That object would then have access to its instance variables like numDigits.
bi = new BigInteger()
Then you can access bi.numDigits rather than this.numDigits which doesn't make sense. Here bi points to an object instance of BigInteger whereas this doesn't point to anything because we're not inside an instance, we're in a static method.
Think of the static parse method as just a helper function that in theory could've resided somewhere outside the class definition, but is inside the class definition for convenience and clarity. Its job is to create a BigInteger instance by parsing text.
I am working on program and I am struck at this point /
public static int numOutput( Integer.toString(int number))
{
String outputNumber="";
if (outputNumber.length()<=10)
{
outputNumber.concat(number);
}
else
{
return outputNumber;
}
}
How can I fix this??
Integer.toString(int number) should be in the body of the method, not in the argument declaration.
Are you trying to concat the number passed to an empty String? Just use take Integer.toString(number) or number + ""
You must return an integer as you have declared that. Either change the return type to String or change the values returned to an int.
You check the length of an empty string. It will always be less than 10.
public static int numOutput(int number) {
String outputNumber = "";
if (outputNumber.length()<=10) {
outputNumber = number + "";
} else {
return number;
}
return -1;
}
I'm attempting to return the index of where an object appears in an array of objects.
public static int search(WordCount[] list,WordCount word, int n)
{
int result = -1;
int i=0;
while (result < 0 && i < n)
{
if (word.equals(list[i]))
{
result = i;
break;
}
i++;
}
return result;
}
WordCount[] is the array of objects.
word is an instance of WordCount.
n is the number of objects in WordCount[]
It runs, but isn't returning the index correctly. Any and all help is appreciated. Thanks for your time.
CLASS
class WordCount
{
String word;
int count;
static boolean compareByWord;
public WordCount(String aWord)
{
setWord(aWord);
count = 1;
}
private void setWord(String theWord)
{
word=theWord;
}
public void increment()
{
count=+1;
}
public static void sortByWord()
{
compareByWord = true;
}
public static void sortByCount()
{
compareByWord = false;
}
public String toString()
{
String result = String.format("%s (%d)",word, count);
return result;
}
}
How I'm calling it...
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].length()>0)
{
WordCount word = new WordCount(tokens[i]);
int foundAt = search(wordList, word, n);
if (foundAt >= 0)
{
wordList[foundAt].increment();
}
else
{
wordList[n]=word;
n++;
}
}
}
}
By default, Object#equals just returns whether or not the two references refer to the same object (same as the == operator). Looking at what you are doing, what you need to do is create a method in your WordCount to return word, e.g.:
public String getWord() {
return word;
}
Then change your comparison in search from:
if (word.equals(list[i]))
to:
if (word.getWord().equals(list[i].getWord()))
Or change the signature of the method to accept a String so you don't create a new object if you don't have to.
I wouldn't recommend overriding equals in WordCount so that it uses only word to determine object equality because you have other fields. (For example, one would also expect that two counters were equal only if their counts were the same.)
The other way you can do this is to use a Map which is an associative container. An example is like this:
public static Map<String, WordCount> getCounts(String[] tokens) {
Map<String, WordCount> map = new TreeMap<String, WordCount>();
for(String t : tokens) {
WordCount count = map.get(t);
if(count == null) {
count = new WordCount(t);
map.put(t, count);
}
count.increment();
}
return map;
}
This method is probably not working because the implementation of .equals() you are using is not correctly checking if the two objects are equal.
You need to either override the equals() and hashCode() methods for your WordCount object, or have it return something you want to compare, i.e:word.getWord().equals(list[i].getWord())
It seems easier to use:
public static int search(WordCount[] list, WordCount word)
{
for(int i = 0; i < list.length; i++){
if(list[i] == word){
return i;
}
}
return -1;
}
This checks each value in the array and compares it against the word that you specified.
The odd thing in the current approach is that you have to create a new WordCount object in order to look for the count of a particular word. You could add a method like
public boolean hasEqualWord(WordCount other)
{
return word.equals(other.word);
}
in your WordCount class, and use it instead of the equals method:
....
while (result < 0 && i < n)
{
if (word.hasEqualWord(list[i])) // <--- Use it here!
{
....
}
}
But I'd recommend you to rethink what you are going to model there - and how. While it is not technically "wrong" to create a class that summarizes a word and its "count", there may be more elgant solutions. For example, when this is only about counting words, you could consider a map:
Map<String, Integer> counts = new LinkedHashMap<String, Integer>();
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].length()>0)
{
Integer count = counts.get(tokens[i]);
if (count == null)
{
count = 0;
}
counts.put(tokens[i], count+1);
}
}
Afterwards, you can look up the number of occurrences of each word in this map:
String word = "SomeWord";
Integer count = counts.get(word);
System.out.println(word+" occurred "+count+" times);
I can't seem to get the "The numbers match" result if my input is a number that is in my array list in another class called SomeNumbers. If you run it, it will give you the result for it not being a number in the array at the speed of light though.
I am also having a hard time pin pointing where the actual problem is because I can use my debugging tools for whatever reason in jGrasp.
This is the main application that the user would input the number to see if there is a match.
import java.util.Scanner;
public class SomeNumbersClient {
public static void main(String[] args) {
SomeNumbers testNumbers = new SomeNumbers();
Scanner userInput = new Scanner(System.in);
System.out.print("Enter Integer Value: ");
int input = userInput.nextInt();
testNumbers.setNumber(input);
if (testNumbers.getTest()) {
System.out.println("The numbers match");
} else {
System.out.println("The numbers don't match");
}
}
}
Now this is the class where I call on the getTest method to see if the boolean result is true or false. I then have the if statement in the client see if it's true then it will display that there is a match, if not, there is no match.
public class SomeNumbers {
private int[] numbers = { 5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 120255, 1005231, 6545231, 3852082, 7576651,7881200, 4581002};
private int number;
private int index = 0;
private boolean test = true;
public void setNumber(int input) {
number = input;
}
public boolean getTest(){
while (index < numbers.length){
if (number != numbers[index]){
test = false;
index++;
} else {
test = true;
}
}
return test;
}
}
Sorry the code kind of got chopped up, any help is appreciated.
here is proper version of getTest function, your problem was because you find match (and set variable test to true), but then you continue search and next number converts "test" to false
public boolean getTest()
{
index = 0;
while (index < numbers.length)
if (number != numbers[index])
index++;
else
return true;
return false;
}
I have a string like a>5 and b<6 or c>=7 in java
When I check whether string contains > then output is true for both > and >=
How can I restrict my check only to specific character?
How can I use matches function?
Your mistake is, you think of a lexical entity, >=, as of a "character." That will bite you more than once, as there actually are two characters, > and =, and > is indeed here. So depending on what you need, the answer may be different.
Why don't you want to see >= found?
What usage of > is of interest for you? Will e.g. <tag>some text</tag> be a proper string which you'd prefer to allow?
You want to discriminate between greater than and greater than or equal to. Why not write a method that returns the operator?
enum Operator {
...
}
public Operator getOperator(String s) {
if(s.contains(">=")) {
return Operator.GREATER_THAN_OR_EQUAL_TO;
} else if (s.contains(">") {
return Operator.GREATER_THAN;
}
}
If the input can be a complex expression that contains multiple operators, instead of contains, try using indexOf(...) and look ahead one character for the '='.
I just threw this together based on the updated specifications. Basically a real simple parser rather mechanically created: (And I'm not good with naming at 7 in the morning oh well)
public class Main {
public static void main(String[] args) {
String test = "a > b >= c > x";
Main m = new Main(test);
System.out.println(m.getTokenNumber());
test = "aasdfasdf asdfdasf";
m = new Main(test);
System.out.println(m.getTokenNumber());
}
private String input;
private int pos;
public Main(String input) {
this.input = input;
pos = 0;
}
public TokenNumber getTokenNumber() {
TokenNumber tokenNumber = new TokenNumber();
Token t = nextToken();
while (t != Token.NONE) {
tokenNumber.addToken(t);
t = nextToken();
}
return tokenNumber;
}
private Token nextToken() {
while (pos < input.length() && input.charAt(pos) != '>') pos++;
if (pos == input.length()) return Token.NONE;
pos++;
if (pos == input.length() || input.charAt(pos) != '=') return Token.GREATER;
return Token.GREATER_EQUAL;
}
enum Token {
GREATER, GREATER_EQUAL, NONE;
}
static class TokenNumber {
public int greater;
public int greater_than;
public void addToken(Token t) {
if (t == Token.GREATER) greater++;
else greater_than++;
assert t != Token.NONE;
}
public String toString() {
return String.format("Greater: %d%nGreater Than: %d", greater, greater_than);
}
}
}
"your string >".contains(">");// returns true
boolean value = Pattern.compile(">").matcher("a>5").find(); // returns true