I'm trying to give the user an infinite amount of inputs until they enter q. I'm using a while statement to run the program, but when the user tries to quit I get an error because the program would try and parse q as an integer. Any ideas on how I should change the structuring of this to prevent the error from occurring?
Scanner in = new Scanner(System.in);
System.out.println("What would you like your Fibonacci number to be?(enter q to quit)");
String value = in.next();
int trueValue;
while(!value.equalsIgnoreCase("q")) {
trueValue = Integer.parseInt(value);
Fibonacci userCase = new Fibonacci(trueValue);
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
System.out.println("Please enter another number.");
value = in.next();
trueValue = Integer.parseInt(value);
}
If it matters, here are the methods being called within the loop.
public int calculateFibonacci(int caseValue) {
if(caseValue == 0)
return 0;
else if(caseValue == 1)
return 1;
else
return calculateFibonacci(caseValue-1) + calculateFibonacci(caseValue-2);
}
public int getCaseValue()
{
return caseValue;
}
You can remove the last
trueValue = Integer.parseInt(value);
since you are already doing that at the start of the loop.
do{ getting the user value before checking } while(checking if it's ok);
/* https://stackoverflow.com/questions/40519580/trying-to-determine-if-a-string-is-an-integer */
private boolean isInteger(String str) {
if(str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static String check(Scanner in) {
String value;
do {
System.out.println("Please enter a number or q to quit.");
value = in.next();
} while(!value.equalsIgnoreCase("q") && !isInteger(value));
return value;
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
String value = check(in);
while(!value.equalsIgnoreCase("q")) {
Fibonacci userCase = new Fibonacci(Integer.parseInt(value));
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
value = check(in);
}
in.close();
}
Related
I want to check whether a password has at least 8 characters and consist of numbers and letters only.
The problem here is even though I entered a valid password it says 'Invalid' all the time. Here's the code. Thanks.
public static void main(String[] args)
{
String pw;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a password: ");
pw = sc.next();
if(isValid(pw)==true)
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
public static boolean isValid(String pw)
{
if(pw.length()<8)
{
return false;
}
else
{
for(int x=0; x<pw.length(); x++)
{
return Character.isLetterOrDigit(pw.charAt(x));
}
}
return true;
}
}
Logic of your code is correct except return statement in 'for' loop in isValid method. Here is edited code:
public static void main(String[] args)
{
String pw;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a password: ");
pw = sc.next();
if(isValid(pw))
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
public static boolean isValid(String pw)
{
if(pw.length()<8)
{
return false;
}
else
{
for(int x=0; x<pw.length(); x++)
{
if(!Character.isLetterOrDigit(pw.charAt(x)))
return false;
}
}
return true;
}
Note that your code does not print 'invalid' if your password is valid but could print 'valid' for some invalid passwords such as a########
You're returning the result within the first iteration of the loop, rather you should make a flag variable and return the result at the end of the loop or you could invert the if condition within the loop and return false if that evaluates to true and if it does not then return true at the end of the loop.
public static boolean isValid(String password){
if(password.length() < 8)
return false;
for(int x = 0; x < password.length(); x++)
if(!Character.isLetterOrDigit(password.charAt(x)))
return false;
return true;
}
Inside my code, I am trying to compare the last element of an array list to a random number, but I keep getting the error "incompatible types: Object cannot be converted to int". I cannot seem to find a solution. The problem in question occurs at the boolean class 'checkLastGuess'.
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
public class GuessingGame
{
int numToGuess = new Random().nextInt(10);
ArrayList guesses = new ArrayList();
void getGuess()
{
Scanner keyboard = new Scanner(System.in);
boolean valid = false;
int userGuess = 0;
while (valid == false)
{
System.out.print("What is your guess: ");
String num = keyboard.next();
char new_num = num.charAt(0);
if (Character.isDigit(new_num))
{
userGuess = Integer.parseInt(num);
if (userGuess >= 0 && userGuess < 10)
{
guesses.add(userGuess);
valid = true;
}
else
{
System.out.println("Invalid guess, please enter a number between 0 and 9.");
}
}
else
{
System.out.println("Invalid guess, please enter digit.");
}
}
}
void printGuesses() {
int list_length = guesses.size();
System.out.print("Your guesses: ");
for (int counter = 0; counter < list_length; counter++)
{
System.out.print(guesses.get(counter) + " ");
}
System.out.println();
}
boolean checkLastGuess()
{
int numToTest = guesses.get(guesses.size()-1);
if (numToTest == numToGuess)
{
return true;
}
else
{
return false;
}
}
}
The code is then ran through the following test program
public class GuessingGameTest {
public static void main(String[] args) {
GuessingGame game = new GuessingGame();
System.out.println("Number to guess: " + game.numToGuess);
boolean guessedNumber = false;
while (!guessedNumber) {
game.getGuess();
guessedNumber = game.checkLastGuess();
}
}
}
You're not initializing the arraylist correctly. Change
ArrayList guesses = new ArrayList();
to
ArrayList<Integer> guesses = new ArrayList<Integer>();
Arraylists are generic (ArrayList<E>) in that they require an object to be specified in their construction so that you know what is in the arraylist.
I am writing a program that translates from Roman numerals to decimal numbers.
For some reason it does not return the value when it checks the user's input. However it already fixed,
what I'm facing right now is: The code does not respond me the number (it's keep show a blank screen after the input).
How can I fix this? Is there an issue in my code? I am just a starter so what I have learned is just basic stuff.
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()<=0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
return i;
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int numb = 0;
int n=0;
int ch=0;
while (n<numeral.length()) {
char l= numeral.charAt(n);
numb=convertCharacterToNumber(l);
if (numb<0) {
System.out.println("Cannot be define");
n++;
}
else if (n==numeral.length()) {
ch+=numb;
}
else {
int nnumb=convertCharacterToNumber(numeral.charAt(n));
if (nnumb>numb) {
ch+=nnumb-numb;
n++;
}
else {
ch+=numb;
}
}
}
if (ch>3999) {
System.out.println("Input number must be less than 3999");
numb=ch;
}
return numb;
}
private static int convertCharacterToNumber(char numeral) {
// Fill in the body
int n=0;
if (numeral=='m' || numeral =='M') {
return 1000;
}
else if (numeral=='d' || numeral=='D') {
return 500;
}
else if (numeral=='c' || numeral=='C') {
return 100;
}
else if (numeral=='l' || numeral=='L') {
return 50;
}
else if (numeral=='x' || numeral=='X') {
return 10;
}
else if (numeral=='v' || numeral=='V') {
return 5;
}
else if (numeral=='i' || numeral=='I') {
return 1;
}
else {
return -1;
}
}
}
public class stringTest {
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
else return i; // in your program the while is never ending, so it does not return any value.
}
return "";
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int preNumber = 0;
int curNumber = 0;
int n=0;
int ch=0;
while (n<numeral.length()) {
char l= numeral.charAt(n);
curNumber=convertCharacterToNumber(l);
if (curNumber<0) {
System.out.println("Cannot be define");
System.exit(0);
}
else {
// I have changed the logic to evaluated decimal Number equivalent to Roman Literal
if(preNumber < curNumber && n != 0) ch = curNumber - ch;
else ch += curNumber;
preNumber = curNumber;
}
n++;
}
return ch;
}
private static int convertCharacterToNumber(char numeral) {
// Fill in the body
if (numeral=='m' || numeral =='M') {
return 1000;
}
else if (numeral=='d' || numeral=='D') {
return 500;
}
else if (numeral=='c' || numeral=='C') {
return 100;
}
else if (numeral=='l' || numeral=='L') {
return 50;
}
else if (numeral=='x' || numeral=='X') {
return 10;
}
else if (numeral=='v' || numeral=='V') {
return 5;
}
else if (numeral=='i' || numeral=='I') {
return 1;
}
else {
return -1;
}
}
}
You can probably look into promptUserForNumeral method, I think it is not necessary. You can include that in the main while loop to look for user errors.
Check this
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
}
return i;
This won't quit or return anything while i.length() > 0. That return is dead code if user didn't enterq.
Solution: Specify a else with break; then it will work.
else
break;
I would rewrite your while loop :
while (i.length()<=0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
return i;
You have lots of redundant conditions. The problem lies within this loop:
while (i.length() >= 0) {
if (i.length() == 0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
} else if (i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
}
Take any value for i like "V".
It's length is greater than zero, hence it enters the loop.
It's length is again not zero in the first if condition, hence it proceeds to the elseIf
Since the value isn't a "q", the else part doesn't execute either.
So it goes back to the loop's start & again checks the condition if length is greater than zero.
So, you have an infinite loop. Work through your logic again & remove any unnecessary conditions. You can also use the break; statement to terminate the loop.
First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.
here is the Menu class
import java.util.Scanner;
public class Menu {
private String[] menu_options;
public Menu(String[] menu_options) {
this.menu_options = menu_options;
}
public int getUserInput() {
int i = 1;
for (String s : this.menu_options) {
System.out.println(i + ". " + s);
i++;
}
int selection = getint_input(menu_options.length);
return (selection);
}
private int getint_input(int max) {
boolean run = true;
int selection = 0;
while (run) {
System.out.print("Select an option: ");
Scanner in = new Scanner(System.in);
if (in.hasNextInt()) {
int value = in.nextInt();
if(value>=1 || value<=max){
selection = value; //fixed this now working
run = false;
}
} else {
System.out
.print("Invalid input. Please enter a integer between 1 and "
+ max + ": ");
}
}
return selection;
}
}
and here is the menudriver i was using
public class Menutester {
public static void main(String[] args) {
String[] menuitems = new String[2];
menuitems[0] = "option one";
menuitems[1] = "option two";
Menu tm = new Menu(menuitems);
int choice = tm.getUserInput();
System.out.println("Got input");
}
}
the first time i input something it dosn't regester at all and when i try to debug it in eclipse it gives me the error FileNotFoundException(Throwable).(String) line: 195 on the first input.
this is what it returns
option one
option two
Select an option: 1(i entered this and pressed enter)
1(same here only it regestered the input)
Got input
nextInt reads the input and removes it from the buffer. You can't call it like that without storing the value.
Call it once, store the value, and then do all the checks needed.
Change this:
if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) {
selection = in.nextInt();
//...
for this:
if(in.hasNextInt()) {
int selection = in.nextInt();
if(selection >= 1 || selection <= max) {
run = false;
}
}
replace:
if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) {
selection = in.nextInt();
run = false;
System.out.println(run);
}
as:
int input = in.nextInt();
if (input >= 1 || input <= max) {
selection = in.nextInt();
run = false;
System.out.println(run);
}
and try it again.