How to make this code decline String other than q - java

I still a little bit new so I'm going to include all of my java code and then explain what I am looking for.
import java.util.Scanner;
public class Part_I{
public static Scanner input = new Scanner(System.in);
public static String strInfo;
public static int number;
public static void main(String[] args){
String presidents[][] = {
{"1 ","George"," ","Washington"," (1789-1797) ","John Adams"},
{"2 ","John"," ","Adams"," (1797-1801) ","Thomas Jefferson"},
{"3 ","Thomas"," ","Jefferson"," (1801-1809) ","Aaron Burr"},
{"4 ","James"," ","Madison"," (1809-1817) ","George Clinton"},
{"5 ","James"," ","Monroe"," (1817-1825) ","Daniel D. Tompkins"},
{"6 ","John"," Quincy ","Adams"," (1825-1829) ","John C. Calhoun"},
{"7 ","Andrew"," ","Jackson"," (1829-1837) ","John C. Calhoun"},
{"8 ","Martin"," Van ","Buren"," (1837-1841) ","Richard M. Johnson"},
{"9 ","William"," Henry ","Harrison"," (1841) ","John Tyler"},
{"10 ","John"," ","Tyler"," (1841-1845) ","None"},
{"11 ","James"," K. ","Polk"," (1845-1849) ","George M. Dallas"},
{"12 ","Zachary"," ","Taylor"," (1849-1850) ","Millard Fillmore"},
{"13 ","Millard"," ","Fillmore"," (1850-1853) ","None"},
{"14 ","Franklin"," ","Pierce"," (1853-1857) ","William King"},
{"15 ","James"," ","Buchanan"," (1857-1861) ","John C. Breckinridge"},
{"16 ","Abraham"," ","Lincoln"," (1861-1865) ","Hannibal Hamlin"},
{"17 ","Andrew"," ","Johnson"," (1865-1869) ","None"},
{"18 ","Ulysses"," S. ","Grant"," (1869-1877) ","Schuyler Colfax"},
{"19 ","Rutherford"," B. ","Hayes"," (1877-1881) ","William Wheeler"},
{"20 ","James"," A. ","Garfield"," (1881) ","Chester Arthur"},
{"21 ","Chester"," ","Arthur"," (1881-1885) ","None"},
{"22 ","Grover"," ","Cleveland"," (1885-1889) ","Thomas Hendricks"},
{"23 ","Benjamin"," ","Harrison"," (1889-1893) ","Levi P. Morton"},
{"24 ","Grover"," ","Cleveland"," (1893-1897) ","Adlai E. Stevenson"},
{"25 ","William"," ","McKinley"," (1897-1901) ","Garret Hobart"},
{"26 ","Theodore"," ","Roosevelt"," (1901-1909) ","None"},
{"27 ","William"," Howard ","Taft"," (1909-1913) ","James S. Sherman"},
{"28 ","Woodrow"," ","Wilson"," (1913-1921) ","Thomas R. Marshall"},
{"29 ","Warren"," G. ","Harding"," (1921-1923) ","Calvin Coolidge"},
{"30 ","Calvin"," ","Coolidge"," (1923-1929) ","None"},
{"31 ","Herbert"," ","Hoover"," (1929-1933) ","Charles Curtis"},
{"32 ","Franklin"," D. ","Roosevelt"," (1933-1945) ","John Nance Garner"},
{"33 ","Harry"," S. ","Truman"," (1945-1953) ","None"},
{"34 ","Dwight"," D. ","Eisenhower"," (1953-1961) ","Richard Nixon"},
{"35 ","John"," F. ","Kennedy"," (1961-1963) ","Lyndon B. Johnson"},
{"36 ","Lyndon"," B. ","Johnson"," (1963-1969) ","None"},
{"37 ","Richard"," ","Nixon"," (1969-1974) ","Spiro Agnew"},
{"38 ","Gerald"," ","Ford"," (1974-1977) ","Nelson Rockefeller"},
{"39 ","Jimmy"," ","Carter"," (1977-1981) ","Walter Mondale"},
{"40 ","Ronald"," ","Reagan"," (1981-1989) ","George Bush"},
{"41 ","George"," ","Bush"," (1989-1993) ","Dan Quayle"},
{"42 ","Bill"," ","Clinton"," (1993-2001) ","Al Gore"},
{"43 ","George"," W. ","Bush"," (2001-2009) ","Dick Cheney"},
{"44 ","Barack"," ","Obama"," (2009-2017) ","Joe Biden"},
};
System.out.println("This will display the President and VP of the United States based on the number you provide.");
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
while(strInfo != "q"){
if(isInteger(strInfo)){
number = Integer.parseInt(strInfo);
if (number >= 1 && number <=44){
System.out.println();
System.out.println(presidents[number-1][0] + "President " + presidents[number-1][1] + presidents[number-1][2] + presidents[number-1][3] + presidents[number-1][4] + "Vice President " + presidents[number-1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
}else{
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}else{
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
}
}
}
public static boolean isInteger(String strInfo){
if (strInfo == null) {
return false;
}
int length = strInfo.length();
if (length == 0) {
return false;
}
int i = 0;
if (strInfo.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = strInfo.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
}
My main concern is with the while loop.
while(strInfo != "q"){
if(isInteger(strInfo)){
number = Integer.parseInt(strInfo);
if (number >= 1 && number <=44){
System.out.println();
System.out.println(presidents[number-1][0] + "President " + presidents[number-1][1] + presidents[number-1][2] + presidents[number-1][3] + presidents[number-1][4] + "Vice President " + presidents[number-1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
}else{
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}else{
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
}
}
}
I want to make it so that it any string other than what is able to be converted to an int or "q" would say wrong input and make you input another string value. Right now, any string will make the program terminate. What should I change in that while loop and how should I change it or what should it look like instead so that if the string input is not q or convertible to an int will make wrong input display and ask for input again?

This will help you in achieving what you want to do
while (!strInfo.equals("q")) {
if (isInteger(strInfo)) {
number = Integer.parseInt(strInfo);
if (number >= 1 && number <= 44) {
System.out.println();
System.out.println(presidents[number - 1][0] + "President " + presidents[number - 1][1] + presidents[number - 1][2] + presidents[number - 1][3] + presidents[number - 1][4] + "Vice President " + presidents[number - 1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
} else {
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
} else {
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);

You shouldn't check string equality using normal operators like "=" and "!=". Use the String .equals() method.
So your first line would be
while(!strInfo.equals("q"))
More info:
http://www.leepoint.net/data/expressions/22compareobjects.html

The reason your code is not working is because you are trying to compare whether the contents of two strings are equal using == operator (which only compares if the two references point to the same object). == Operator does not compare the contents of the two strings.
In order to make your code work, you would need to use equals to compare the contents of the two strings as follows :
while(!strInfo.equals("q"))
Now lets try to delve deep into why your code is not working. For that we need to understand the basic difference between == & equals
== Operator is used to compare if both the references on its either side point to the same object (Basically you can say its similar to
comparing address of the object to which the references point to).
Whereas equals in case of String compares the content of the two Strings. It is the responsibility of the creator of the class to override the default equals method to compare the objects of that class depending on what makes sense for that object. For example in case of String class the creators of the class have overriden the equals method to compare the contents of the Strings.
String a = "test"; // lets say the object guy has address : 24
String b = a; // now b points to the same object that is being referenced by a
System.out.println(a == b); // this will be true as both point to the same reference
System.out.println(a.equals(b)); // this will be true as the contents of both these strings is the same.
// Now lets consider a new strings having same content "test"
String c = "test";
System.out.println(a == c); // this will be false as both point to the different references or memory location
System.out.println(a.equals(c)); // this will be true as the contents of both these strings is the same.

Related

How can I make a loop that keeps going based on user input

for a class I have to make a simple program that allows a user to enter the weight of a package and then it tells the user the shipping price associated with that weight. It's not required for the homework but I am trying to add a do-while loop that asks the user to enter the letter y at the end of the loop if they would like to enter another weight and then the while section tests if the keepGoing variable is equal to y to restart the loop. I don't know why but no matter what the user enters, the loop does not restart. Even if the user enters y the program just ends, can anyone help please.
import java.util.Scanner;
public class HwkChp4 {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
double packageWeight;
double underTwo = 1.10;
double twoToSix = 2.20;
double sixToTen = 3.70;
double overTen = 3.80;
String msg1 = "How much does the package weigh?";
String msg2 = "The shipping cost is ";
String keepGoing = "y";
packageWeight = getDouble(msg1);
do {
if(packageWeight <= 2) {
System.out.println(msg2 + "$" + underTwo);
}
if(packageWeight > 2 && packageWeight <= 6) {
System.out.println(msg2 + "$" + twoToSix);
}
if(packageWeight > 6 && packageWeight <= 10) {
System.out.println(msg2 + "$" + sixToTen);
}
if(packageWeight > 10) {
System.out.println(msg2 + "$" + overTen);
}
System.out.println("Please enter y if you would like to enter another weight");
System.out.println("otherwise please enter n");
keepGoing = keyboard.next();
} while (keepGoing == "y");
}
public static double getDouble(String msg1) {
double decimal;
System.out.println(msg1);
decimal = keyboard.nextFloat();
return decimal;
}
}
In Java, equality can only be tested using the == operator on primitive data types (int, char, boolean, etc., basically data types that start lowercase). Strings and other data types are stored much differently and the == operator calls the variables memory addresses, rather than the data they hold. Therefore, you cannot use the the equality operator as no matter how hard you try, keepGoing will always be stored in a different memory address than "y" or any other variable you would try to set it to. (Unless of course you set them both to the same reference on purpose, but that would always result in true). So what you need to do is use String's builtin equals() function as is written below:
TLDR: Change keepGoing == y to keepGoing.equals(y)

How to alphabetize strings in Java using functions

import java.util.Scanner;
public class alphabetical {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner Alphabet= new Scanner(System.in);
System.out.println("Input First Name");
String UserInput= Alphabet.next();
System.out.println("Input second name");
String UserInput2= Alphabet.next();
System.out.println("Input third name");
String UserInput3= Alphabet.next();
System.out.println(alpha)UserInput,UserInput2,UserInput3));
}
public static void alpha(String fromUser,String fromUser2, String fromUser3)
{
if (fromUser.compareTo(fromUser2)>0)
{
System.out.println(fromUser2);
}
else if(fromUser.compareTo(fromUser3)>0)
{
System.out.println(fromUser3);
}
else if (fromUser2.compareTo(fromUser3)>0)
{
System.out.println(fromUser3);
}
else if (fromUser2.compareTo(fromUser)>0)
{
System.out.println(fromUser);
}
else if (fromUser3.compareTo(fromUser)>0)
{
System.out.println(fromUser);
}
else if (fromUser3.compareTo(fromUser2)>0)
{
System.out.println(fromUser2);
}
}
}
So that's my code but I don't know what I'm doing wrong. I've been working on this for a while and I need a code that will allow the user to input 3 names and then sort the names in alphabetical order
The requirements for this program is to have the user input 3 strings and print them out ordered alphabetically using a function that takes 3 strings-- the return type should be void-- this means that there nothing returned back to main, the function will just print out the three words in alphabetical order there should be 6 cases you need to worry about (think If, elseif...else).
Here is what a sample output might look like in the console (> denotes it's in the console-- you won't actually see this):
input first lowercase string
awesome
input second lowercase string
bogus
input third lowercase string
chillin
(THE FOLLOWING HAPPENS IN THE VOID FUNCTION)
Here are your words in alphabetical order
awesome
bogus
chillin
If you're really not allowed to use arrays or lists, I hope your professor is making you write a long-winded solution, so that he can "reveal" the better, array or list based version later.
For three items, it's true that there are six cases, and you can "just" write an if/else clause for each one:
// case 1 - abc
if(lessThan(a,b) && lessThan(b,c)) {
System.out.println(a + " " + b + " " + c);
}
// case 2 - acb
else if(lessThan(a,c) && lessThan(c,b)) {
System.out.println(a + " " + c + " " + b);
}
// case 3 - bac
else if(lessThan(b,a) && lessThan(a,c)) {
System.out.println(b + " " + a + " " + c);
}
... and so on, for each of abc,acb,bac,bca,cab,cba. For my own sanity I've assumed the existence of a lessThan() method containing a.compareTo(b) < 0 -- but you could use compareTo() directly if your professor also forbids you writing helper methods.
Because of the wording of the question, I guess this is what's expected -- it's not a sensible way to implement a sort, but it could be the basis on which to build something better. It does also allow you to directly count how many comparisons are being made, which could lead to some beginner's insight into the cost of an algorithm.
If you're allowed to use an array, and you're allowed to use a sort routine provided by Java, then just put the values into an array, sort it and print it:
public static void alpha(String a,String b, String c) {
String[] array = new String[] {a,b,c};
Arrays.sort(array);
System.out.println(array[0] + " " + array[1] + " " + array[2]);
}
In java 8 it is simple. You can sort collection of strings with lambda:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner Alphabet = new Scanner(System.in);
System.out.println("Input First Name");
String UserInput = Alphabet.next();
System.out.println("Input second name");
String UserInput2 = Alphabet.next();
System.out.println("Input third name");
String UserInput3 = Alphabet.next();
List<String> list = Arrays.asList(UserInput, UserInput2, UserInput3);
list.sort((String in1, String in2) -> in1.compareTo(in2));
list.forEach(System.out::println);
}
So you can use anything as long as you put it in a method ...
public static void alpha(String fromUser,String fromUser2, String fromUser3){
String[] sArray = {fromUser, fromUser2, fromUser3};
Arrays.sort(sArray);
for (String s : sArray){
System.out.print(s + " ");
}
}
Using java 8 streams you can do it like that:
public static void alpha(String fromUser,String fromUser2, String fromUser3) {
Stream.of(fromUser, fromUser2, fromUser3).sorted().forEach(System.out::println);
}
You're close, but you need to be comparing your String to both other Strings before producing your output. One approach is to create an individual if/else if/else block for each of your three lines of output. For example, here's the middle line given Strings s1, s2, s3.
// First Word
. . .
// Second Word
if ( (s1.compareTo(s2) >= 0) && (s1.compareTo(s3) <= 0) ) {
System.out.println(s1);
} else if ( (s2.compareTo(s1) >= 0) && (s2.compareTo(s3) <= 0) ) {
System.out.println(s2);
} else {
System.out.println(s3);
}
// Third Word
. . .
Another approach is to account for every permutation of how three things can be arranged. {abc, acb, bac, bca, cab, cba }. This is manageable when you have only three things to arrange, but gets quite nasty when you add more.
if ( (s1.compareTo(s2)<=0) && (s1.compareTo(s3)<=0) && (s2.compareTo(s3)<=0) ) {
// abc
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
} else if (s1.compareTo(s2)<=0) && (s1.compareTo(s3)<=0) && (s2.compareTo(s3)>=0) {
// acb
System.out.println(s1);
System.out.println(s3);
System.out.println(s2);
} else if . . .

Using If Statement With Formulas JAVA

I'm working on a workshop for my JAVA. There's one part I'm having difficulty understanding: Apply the following formulas based on gender (must use an if statement(s)):
Hmale_child = ((Hmother * 13/12) + Hfather)/2 OR
Hfemale_child = ((Hfather * 12/13) + Hmother)/2
How do I use an if statement with these formulas? I use the Hmale_child if the user inputs that their child's gender is male. But all the if statements I've seen have to do with numbers. Can anyone point me in the right direction?
Something like: if (gender == male) ??
import java.util.Scanner;
public class WKSP6Trial
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
Scanner inp = new Scanner(System.in);
String Letter;
String input = "";
String exit = "exit";
boolean isStringLetter = true;
System.out.println("Welcome! If at any time you wish to exit the program, type the word exit, and press enter.");
while(true)
{
System.out.println("\nPlease enter letters m or f only as you enter your child's gender: ");
input = inp.nextLine();
if(input.equalsIgnoreCase(exit)){break;}
isStringLetter = input.matches("[m/f/M/F]+");
if(isStringLetter == false)
{
System.out.println("\nYou entered a non letter " + input);
System.out.println("Remove all non letters aside from m or f from your input and try again !");
break;
}
System.out.println("You entered the gender of your child.");
System.out.println("Next enter the height of the child's father in feet followed by ");
System.out.println("the father's height in inches: ");
int n1, n2;
n1 = scannerObject.nextInt();
n2 = scannerObject.nextInt();
System.out.println("You entered " + n1 + " followed by " + n2);
System.out.println("Finally, enter the height of the child's mother followed by ");
System.out.println("the mother's height in inches: ");
int d1, d2;
d1 = scannerObject.nextInt();
d2 = scannerObject.nextInt();
System.out.println("You entered " + d1 + " followed by " + d2);
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
//below is what I'm uncertain of
if(gender == m)
Hmale_child = ((Hmother * 13/12) + Hfather)/2;
}
}
}
You can use the equals or equalsIgnoreCase methods to check your string inputs:
if (gender.equalsIgnoreCase("m")) {
child = ((Hmother * 13.0/12) + Hfather)/2.0;
else { // alternatively - check if the gender is female, just to be sure
child = ((Hfather * 12.0/13) + Hmother)/2.0;
}
EDIT:
If you absolutely cannot use an else block, the same logic can be expressed as two if statements, as a gender can't be both "m" and "f":
if (gender.equalsIgnoreCase("m")) {
child = ((Hmother * 13.0/12) + Hfather)/2.0;
}
if (gender.equalsIgnoreCase("f")) {
child = ((Hfather * 12.0/13) + Hmother)/2.0;
}
As in Java, String is an object. So the appropriate way to check or compare your input string is to use equals() method instead of ==.
For example :
String s = "m"; to check whether String s equals m, you can use s.equals("m").
For int, double and other primitive datatypes (except boolean) you can use ==.
As boolean holds only two values i,e true or false. You can just use them directly in the if conditions.
For example
boolean b = true;
if (b){
// true
}else{
//false
}
You can compare Strings in if statements too.
Bear in mind that Strings are objects, so == won't work as you might expect.
When comparing objects, == checks if the two object references point to the same object, so two different objects with identical data will not be considered the same using ==.
If you want to compare the contents of the object, you should use the equals() method instead.
Most standard Java objects should support a reasonable definition of equality through their equals() method. In the case of Strings, the content of the String will be compared in a case-sensitive manner (use equalsIgnoreCase() if you don't want the comparison to be case sensitive.)
If you make your own classes, you will need to implement a reasonable definition of equals() yourself.
(The == and .equals() rule is slightly more complicated in the case of Strings due to Java's String table, so == often will work in that case - but you still shouldn't rely on it.)
So, to run a different calculation based on the entered gender, you would do something like this:
float height;
if ( gender.equalsIgnoreCase("m") ) {
height = (heightMother * 13f / 12f) + (heightFather / 2f);
else {
height = (heightFather * 12f / 13f) + (heightMother / 2f);
}
Note the names of my variables - Java convention is for variable names to start be in camelCase - variable names should not start with a capital letter.
Also, I've used "f" at the end of my numbers to indicate that they are floating-point numbers - you will lose precision if you perform all the mathematics using integers.

Converting parts of Strings to Character to be used in if/else statements

I'm doing an assignment in school and although I've checked through the entire written material I cannot for the life of me find out how to do this. We are supposed to enter strings like "0123 B" and the B at the end of the string is suppose to represent bronze and then add ++ to the Bronze integer. Then print the number of medals.
My issue here is that I'm trying to take the final character from the string (B, S, or G) and then add to that, but the thing is, it's a String and not a character. So I can't use medal.charAt(5).
Here is my code below:
EDITED, CODE IS SOLUTION
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
Just make gol, sil, and bro into chars instead of Strings.
char gol = 'G';
char sil = 'S';
char bro = 'B';
After that change, you should be able to use
medal.charAt(5) == gol
no problem.
Edit
To make this even more generic, you could use
medal.charAt(medal.length() - 1) == gol
which will always pull the last character, thereby avoiding errors with input that has less than 5 indices.

Having trouble with validation: infinite loop occurs even though the logic seems fine

I am working on this 'restaurant' program, that takes two inputs: the bill amount and a satisfactionlevel from 1 to 3. I have tried to validate each output using the hasNextDouble(), but for some reason when i run the program the else statement in the first if statement runs infinitly. Can someone please take a look at this?
package tips;
import java.util.Scanner;
public class Tips {
public static void main(String[] args) {
/* Ask for the diners’ satisfaction level using these ratings:
1 = Totally satisfied, 2 = Satisfied, 3 = Dissatisfied.
If the diner is totally satisfied, calculate a 20 percent tip.
If the diner is satisfied, calculate a 15 percent tip.
If the diner is dissatisfied, calculate a 10 percent tip.
Report the satisfaction level and tip in dollars and cents.*/
Scanner in = new Scanner(System.in);
boolean isDouble = false;
boolean isInt = false;
TipsCalculator tips = new TipsCalculator();
while (!isDouble && !isInt) {
System.out.print("Please enter the bill amount: ");
//Checks if the input is a double.
if(in.hasNextDouble()) {
tips.setBill(in.nextDouble());
isDouble = true;
} else {
System.out.println("The value entered is not a valid amount.");
continue;
}
System.out.println("Please enter your satisfaction level: \n1 = Totally Satisfied.\n2 = Satisfied.\n3 = Dissatisfied.");
//Checks if the input is an integer.
if(in.hasNextInt()) {
tips.setSatisfactionLevel(in.nextInt());
isInt = true;
//Prints different outputs depending on the satisfaction level.
if (tips.getSatisfactionLevel() == 1) {
System.out.println("You are totally satisfied! :-)" +
". \n" +
"Your tip amount is: " +
tips.calculateTips());
} else if (tips.getSatisfactionLevel() == 2){
System.out.println("You are satisfied! :-)" +
". \n" +
"Your tip amount is: " +
tips.calculateTips());
} else if (tips.getSatisfactionLevel() == 3) {
System.out.println("You are dissatisfied! :-(" +
". \n" +
"Your tip amount is: " +
tips.calculateTips());
} else {
//Error if the level is not from 1 to 3.
System.out.println("The value entered is not between 1 and 3");
}
} else {
System.out.println("The value entered is not between 1 and 3");
continue;
}
} in.close();
}
}
isDoubl & isInt both are false so !isDouble && !isInt will be always true. This is the root cause behind infinite loop
Don't read input as double and int. read it as Strings and then parse it to Double or Integer in your code. Use method valueOf(String) in classes Integer and Double. to parse your Strings
Reason for infinite loop is:
hasNextDouble method in Scanner class calls hasNext method internally.
It has written like this
public boolean hasNext(Pattern pattern) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
hasNextPattern = null;
saveState();
while (true) {
if (getCompleteTokenInBuffer(pattern) != null) {
matchValid = true;
cacheResult();
return revertState(true);
}
if (needInput)
readInput();
else
return revertState(false);
}
}
In the above method, getCompleteTokenInBuffer method call is the real culprit. This getCompleteTokenInBuffer can return following 3 possibilities
/*
* 1. valid string means it was found
* 2. null with needInput=false means we won't ever find it
* 3. null with needInput=true means try again after readInput
*/
In hasNext mthod, whenever we first enter non double value, we will be able to read data and getCompleteTokenInBuffer returns null and will also set needInput=false for the first time. But, for the second time, hasNext method will return with value false as needInput=false condition will be true.
This needInput = false condition will remain true for the subsequent hasNextDouble method call. Because of this we were not able to read any data and this was causing infinite loop.

Categories

Resources