Java Eclipse console terminates program before comparing values of user input and string value - string

So I'm making this program for my younger brother and I ran into a problem. The program is suppose to ask for the user's input and then compare it to multiple string values through a series of "if" statements. What happens instead is the user provides their input and then the program instantly terminates. I've been at this for hours and am starting to get pretty ticked about it. Here's the code that I've typed so far:
package package1;
import java.util.Scanner;
public class Psychic_Calculator {
#SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello user, please type your name below:");
String a = scan.nextLine();
System.out.println("Welcome " + a + ", think of a number. Once you have your number, type 'okay' below!");
String b = scan.nextLine();
if (b == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
}
else if (b == "Okay"){
System.out.println("Please don't capitalize 'okay', try typing it again!");
String c = scan.nextLine();
if (c == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
String d = scan.nextLine();
if (d == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String e = scan.nextLine();
if (e == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String f = scan.nextLine();
if (f == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
if (c == "Okay"){
System.out.println("I already told you not to capitalize 'okay', try typing it again, you idiot!");
String g = scan.nextLine();
if (g == "okay"){
System.out.println("Now, add '11' to your number and type 'okay' below.");
String h = scan.nextLine();
if (h == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String i = scan.nextLine();
if (i == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String j = scan.nextLine();
if (j == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
}
if (c != "okay") {
while (c != "okay") {
System.out.println("Do you even know how to spell 'okay'?" + "'" + c + "' does not spell 'okay', you moron! Try typing 'okay' again.");
String n = scan.nextLine();
if (n == "okay"){
System.out.println("Finally, you learned how to spell 'okay'. Your vocabulary is now one word larger, you're welcome. Now, please add '11' to your number and then type 'okay'(correctly this time).");
String k = scan.nextLine();
if (k == "okay"){
System.out.println("Now, add '2' to your new number, then type 'okay' below.");
String l = scan.nextLine();
if (l == "okay"){
System.out.println("Now, subtract your original number from your new number, then type 'okay' below.");
String m = scan.nextLine();
if (m == "okay"){
System.out.println("Your new number is '13'. Don't even try denying it.");
}
}
}
}
else {
System.out.println(a + ", " + "you have failed to type 'okay' too many times! You have no idea how to spell 'okay' you electricutin' motherboarder! Go shove your face in a pile of computer chips and grow a pair!");
System.out.println("(of RAM cartriges...I meant to say RAM cartriges).");
}
}
}
}
}
}

The problem is how you're comparing the strings. Change b == "okay" to b.equals("okay")
Change all the == comparisons to .equals() or .equalsIgnoreCase().
For negations, use (!(c.equals("okay"))
In Java, == will compare primitive types by value but will compare objects by memory address. In other words, when you say b == "okay" its not doing a value comparison, its checking to see whether or not those two objects point to the same memory address, which of course is false.
Update: Just a few things about the way you're going about writing this program.
1) You're creating a lot of string objects needlessly. You're better off re-using one string object until you absolutely need another one. This applies to any object you're using. Try not allocate objects needlessly.
2) Instead of all the if-statements, you can define an array of instructions, like such and condense your code:
String [] instr = {"Add 2", "Add 11", "Subtract Original"};//array of directions
String [] invalidResp = {"Wrong", "You can't spell", "Try Again", "No"};//array of responses to print if user doesnt type 'okay' properly
int instrCounter = 0;//you don't really need this but it helps with readability
String userInput = "";//only string object you'll need =)
while (instrCounter < instr.length){//I couldve just as easily used a for loop instead.
userInput = scan.nextLine();
while (!userInput.equals("okay")){
userInput = scan.nextLine();
System.out.println(invalidResp[(int) (Math.random()*invalidResp.length)]);
//will print a random invalid response from the invalidResp array
System.out.println(userInput + " is not how you spell okay");
}//end while
System.out.println("Great, now, " + instr[instrCounter]);
instrCounter++;
}//end outer while
Remember, when you write code, you want it to be fairly generic and flexible. The way I wrote my code, I can add to the instr array or add more invalid responses and im not needlessly creating objects.
Like I said in the inline comment, I could've just as easily used a for loop for the outer loop but for the sake of readability and making sure you understood what I was doing, I used a while loop as I believe they're more intuitive to read.

GAME:
while(running) {
System.out.println("---------------------------");
continue GAME;
//Name the while loop and then you can break; out.

Related

Program to find if a string is a palindrome keeps on failing. Even after using toLowerCase() command for both strings, output doesn't come

import java.util.Scanner;
class Palindrome_string
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String a = sc.nextLine();
int b = a.length();
String rev = "";
for (int i = b - 1; i >= 0; i--)
{
char c = a.charAt(i);
rev = rev + c;
}
System.out.println("Original word "+a);
System.out.println("Reversed word "+rev);
a = a.toLowerCase();
rev = rev.toLowerCase();
if (a == rev)
{
System.out.println("It is a palindrome");
}
else
{
System.out.println("It is not a palindrome");
}
sc.close();
}
}
The program compiles properly. Still, when running the program, the message which tells if it is a palindrome prints incorrectly. What changes do I make? Here is a picture of the output. Even though the word 'level' (which is a palindrome) has been inputted, it shows that it isn't a palindrome. What changes should I make? output pic
You should not use == to compare two strings because it compares the reference of the string, i.e. whether they are the same object or not.
Use .equals() instead. It tests for value equality. So in your case:
if (a.equals(rev))
{
System.out.println("It is a palindrome");
}
Also try not to use single-letter variable names except for index variables when iterating over a list etc. It's bad practice.

how to ask user input for list of strings

I wanna know how to ask user input for a string. For example:
when user input is asked "lruud" is entered
Enter letters: lruud
and I want it the return should be:
Left
right
up
up
down
left = l, right = r, etc.
So basically it should return the result in the order the letters are entered.
The code below is what I have tried where al() is move left, ar() is move right etc
def move(s: String) {
if(s == "l"){
al()
}else if(s == "r"){
ar()
}else if(s == "u"){
au()
}else if(s == "d"){
ad()
}
}
You can read in a string from standard input using
val s = scala.io.StdIn.readLine()
Scala implicitly considers String to be a Scala collection, in particular an IndexedSeq which means you can call standard collections methods on it such as map to transform it. For example
def move(s: Char): String = {
if (s == 'l') "left"
else if (s == 'r') "right"
else if (s == 'u') "up"
else if (s == 'd') "down"
else throw new RuntimeException("Bad input")
}
"lruud".map(move)
// res4: IndexedSeq[String] = ArraySeq(left, right, up, up, down)
Mapping over a String reads each Char in the string and passes it to the move method for transformation.
Here's one way to go about this.
val action :Map[Char,String] =
Map('d'->"down",'l'->"left",'r'->"right",'u'->"up")
.withDefault(c => s"$c?")
val moves :Seq[String] =
io.StdIn.readLine("Enter letters: ").map(c =>action(c.toLower))
println("\ndirections:\n" + moves.mkString(" ","\n ",""))
testing:
Enter letters: lLdRbu
directions:
left
left
down
right
b?
up

Inverse the input Expression using stacks

I had a coding challenge as one of the process for recruitment into a company. In that coding challenge, one of the question was to inverse an expression.
For Example,
Input : 14-3*2/5
Output : 5/2*3-14
I used stack to put each number say 14 or 3 and expressions and then popped it out again to form the output.
Input format is : num op num op num op num
So we need not worry about input being -2.
num can be between -10^16 to 10^16. I was dealing with strings completely, so even if the number exceeds the 10^16 limit, my algorithm wouldn't have any problem.
My algorithm passed 7 test cases and failed in 2 of them.
I couldn't figure it out what the corner case would be. I couldn't see the test cases as well. Any idea what that might be. I know there isn't enough information, but unfortunately I too don't have them.
// Complete the reverse function below.
static String reverse(String expression) {
expression = expression.trim();
if(expression == ""){
return "";
}
Stack<String> stack = new Stack<String>();
String num = "";
for(int i=0; i<expression.length(); i++){
char c = expression.charAt(i);
if(c==' '){
continue;
}
if(c == '+' || c == '-' || c == '*' || c == '/'){
if(num != "") {
stack.push(num);
}
num = "";
stack.push(Character.toString(c));
} else{
num += c;
}
}
if(num != "") {
stack.push(num);
}
String revExp = "";
while(! stack.empty()){
revExp = revExp + stack.pop();
}
return revExp;
}

String Matching: Matching words with or without spaces

I want to find a way by which I can map "b m w" to "bmw" and "ali baba" to "alibaba" in both the following examples.
"b m w shops" and "bmw"
I need to determine whether I can write "b m w" as "bmw"
I thought of this approach:
remove spaces from the original string. This gives "bmwshops". And now find the Largest common substring in "bmwshop" and "bmw".
Second example:
"ali baba and 40 thieves" and "alibaba and 40 thieves"
The above approach does not work in this case.
Is there any standard algorithm that could be used?
It sounds like you're asking this question: "How do I determine if string A can be made equal to string B by removing (some) spaces?".
What you can do is iterate over both strings, advancing within both whenever they have the same character, otherwise advancing along the first when it has a space, and returning false otherwise. Like this:
static bool IsEqualToAfterRemovingSpacesFromOne(this string a, string b) {
return a.IsEqualToAfterRemovingSpacesFromFirst(b)
|| b.IsEqualToAfterRemovingSpacesFromFirst(a);
}
static bool IsEqualToAfterRemovingSpacesFromFirst(this string a, string b) {
var i = 0;
var j = 0;
while (i < a.Length && j < b.Length) {
if (a[i] == b[j]) {
i += 1
j += 1
} else if (a[i] == ' ') {
i += 1;
} else {
return false;
}
}
return i == a.Length && j == b.Length;
}
The above is just an ever-so-slightly modified string comparison. If you want to extend this to 'largest common substring', then take a largest common substring algorithm and do the same sort of thing: whenever you would have failed due to a space in the first string, just skip past it.
Did you look at Suffix Array - http://en.wikipedia.org/wiki/Suffix_array
or Here from Jon Bentley - Programming Pearl
Note : you have to write code to handle spaces.

exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range: 6

so i am trying to wright a program to Print a word with all of the vowels replaced with $.
in java.
i keep getting this error exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range: 6 when i run it, it compiles fine.
here's the code.
import java.util.*;
public class SummerFour
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int cnt = 0;
String word;
String output = "";
char letter = 'x';
System.out.print("enter word to test: ");
word = keyboard.nextLine();
do {
cnt++;
letter = word.charAt(cnt - 1);
if (letter == 'a' || letter == 'i' || letter == 'e' || letter == 'u' || letter == 'o')
{
letter = '$';
}
}
while (cnt <= word.length());
System.out.println(word);
}
}
Your do...while loop has an off-by-one error. You check to see if cnt is less than or equal to the size of the string, then increment it by one and take that value - 1 to use as the index for String.charAt(). This is problematic because Strings are indexed starting at 0, so at the end of a String, you'll always go one too far.
Think about this example:
tacos
This is a five-letter word. When cnt = 5, you'll go back through the loop one more time (since 5 is less than or equal to 5) and increment cnt to 6. Then you call String.charAt() with a value of 5 (6 -1), but the range of tacos is only 0-4 (0 = t, 1 = a, 2 = c, 3 = o, 4 = s) and thus 5 is out of range. You can make your do...while loop work properly and look less confusing by doing something like this:
do
{
letter = word.charAt(cnt);
if (letter=='a'||letter=='i'||letter=='e'||letter=='u'||letter=='o')
{
letter='$';
}
cnt++;
} while(cnt<word.length());
Of course, the code still doesn't do what you want it to, but you no longer get the original error. Since this looks like it might be homework, I'll let you continue to work through it.

Resources