Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Digit Extractor Help
#1
I tried to give the user a choice of which one they would like so I created a new scanner to take the input, and created a new string for it and then i created an if statement that took either "A" or "a" (if (in2 = "A" + "a") ) and then I made another one, an else if with the same method, and then i wrote an else if they wrote something else all together. But whenever I input either A, a or B, b, it will just show the else option.
The code is below in case you didn't understand what I was trying to say:
[code2=java]import java.util.Scanner;
public class DigitExtratorTester {

static Scanner input = new Scanner(System.in);
static Scanner input2 = new Scanner(System.in);

public static void main(String[] args)
{
System.out.println("Welcome to the Digit Extractor. Please enter 5 digits of your choice:");
String in = input.nextLine();
System.out.println("Would you like it done either" + "\n" + "A) Mathematically" + "\n" + "or B)Conceptually?" + " \n" + "*Please choose either A or B*");
String in2 = input2.nextLine();
if (in2 == "A")
{
DigitExtractor demath = new DigitExtractor(Integer.parseInt(in));
demath.ReturnInvertedOrderByMath();
}
else if (in2 == "B")
{
DigitExtractor deconceptual = new DigitExtractor(in);
deconceptual.ReturnInvertedOrderByString();
}
else
{
System.out.println("You done goof my friend!");
}

}

}[/code2]
#2
This problem may be occurring because strings cannot necessarily be compared using "==". The "==" operator is only used when comparing integer values. Thus, you will want to use the String.equals() method in order to compare strings. You also do not need to have multiple scanner objects. The same scanner can be used more than once, so you can also remove the second Scanner object.

So, the new piece of code would look like this:
[code2=java]import java.util.Scanner;
public class DigitExtratorTester {

static Scanner input = new Scanner(System.in);

public static void main(String[] args)
{
System.out.println("Welcome to the Digit Extractor. Please enter 5 digits of your choice:");
String in = input.nextLine();
System.out.println("Would you like it done either" + "\n" + "A) Mathematically" + "\n" + "or B)Conceptually?" + " \n" + "*Please choose either A or B*");
String in2 = input.nextLine();
if (in2.equals("A"))
{
DigitExtractor demath = new DigitExtractor(Integer.parseInt(in));
demath.ReturnInvertedOrderByMath();
}
else if (in2.equals("B"))
{
DigitExtractor deconceptual = new DigitExtractor(in);
deconceptual.ReturnInvertedOrderByString();
}
else
{
System.out.println("You done goof my friend!");
}

}

}[/code2]
My Blog | My Setup | My Videos | Have a wonderful day.


Forum Jump:


Users browsing this thread: 1 Guest(s)