I am trying unsuccessfully to throw an exception TooLongEx if a user input fails. Been stuck on this forever :(
import java.util.Scanner;
public class MessageTooLong extends Exception {
public static void main(String args[])
throws TooLongEx {
Scanner keyboard = new Scanner(System.in);
String line;
char preference;
int length;
boolean go = true;
while (go) {
System.out.println("Enter a line of text.");
System.out.println("Use no more than 20 characters.");
line = keyboard.next();
length = line.length();
if (length <= 20) {
System.out.println("You entered " + length + " characters, which is an acceptable length.");
System.out.println("Would you like to enter another line?");
System.out.println("Enter 'y' to continue or 'n' to quit.");
preference = keyboard.next().charAt(0);
if ((preference == 'y') || (preference == 'Y')) {
go = true;
} else {
go = false;
}
} else {
throw new TooLongEx();
}
}
}
}
Seems to work fine for me.
For
class TooLongEx extends Exception {}
I get (for an input length > 20)
Exception in thread "main" TooLongEx
at
MessageTooLong.main(MessageTooLong.java:26)
Related
I just started learning java a week ago. I am taking a class at my school. I am trying to create a quiz and I can't figure out how to print out the score. The quiz has three possibilities 3/3, 2/3, 1/3. The problem I am having is with the if statements near the end of the program.
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class t1_lesson03_template{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("1. What do you type at the begining of a comment?");
String answer1 = "//";
String userinput1 = scan.nextLine();
if (userinput1.equals(answer1)) {
System.out.println(" Correct!");
}
if (!userinput1.equals(answer1)) {
System.out.println(" Wrong!");
}
String answer2 = ("(int)");
System.out.println("2. What do you type before a double to convert to an int?");
String userinput2 = scan.nextLine();
if (userinput2.equals(answer2)) {
System.out.println(" Correct!");
}
if (!userinput2.equals(answer2)) {
System.out.println(" Wrong!");
}
String answer3 = ("int number = 5;");
System.out.println("3. Create an int called \"number\", and make it equal 5.");
String userinput3 = scan.nextLine();
if (userinput3.equals(answer3)) {
System.out.println(" Correct!");
}
if (!userinput3.equals(answer3)) {
System.out.println(" Wrong!");
}
if (userinput1.equals(answer1) && userinput2.equals(answer2) && userinput3.equals(answer3)) {
System.out.println("3/3 Awesome!");
}
else if (userinput1.equals(answer1) || userinput2.equals(answer2) || userinput3.equals(answer3)) {
System.out.println("2/3 Good job.");
}
else {
System.out.println("1/3 Try again.");
}
}
}
This,
else if (userinput1.equals(answer1) || userinput2.equals(answer2)
|| userinput3.equals(answer3)) {
should be something like
else if ((userinput1.equals(answer1) && userinput2.equals(answer2)) ||
(userinput1.equals(answer1) && userinput3.equals(answer3)) ||
(userinput2.equals(answer2) && userinput3.equals(answer3))) {
but I would prefer a count. And an array to display your different messages. Something like
int count = 0;
if (userinput1.equals(answer1)) {
count++;
}
if (userinput2.equals(answer2)) {
count++;
}
if (userinput3.equals(answer3)) {
count++;
}
String[] result = { "0/3 None", "1/3 Try Again.", "2/3 Good Job.", "3/3 Awesome!" };
System.out.println(result[count]);
Just add braces before each condition in if class and else if such as
if ((userinput1.equals(answer1)) && (userinput2.equals(answer2)) && (userinput3.equals(answer3))) {
System.out.println("3/3 Awesome!");
}
else if ((userinput1.equals(answer1)) || (userinput2.equals(answer2)) || (userinput3.equals(answer3))) {
System.out.println("2/3 Good job.");
}
I really do not know to how explain this but here we go.
I am testing something for a bigger program I have to make. In the program I have to validate input from the user to see if it is being to be accepted as a valid answer.
I have the code to where it will say if the input is invalid but if I attempted to enter another letter the code crashes with this error:
Enter a letter:
f
Your answer is not valid.
A
Enter a letter:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at example.main(example.java:18)
Here is the code:
import java.util.Scanner;
public class example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
user_answer=input.nextLine().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
input.next();
}
}
while (!UserInput);
}
}
either remove input.next() or change it to input.nextLine()
What's happening is that input.next() will catch the A you input. Then you go back to the beginning of the do and start over, and do input.nextLine() but you had already pressed enter to input A and the A was consumed by input.next().
Remove the input.next(); and it will work fine. The reason is because when you use input.next(), it reads the next character the user types, without exiting the line. Then when the input.nextLine() executes, it reads that same line, but immediately after the number. Since nothing is after the number, it reads in nothing "" and the charAt(0); becomes out of bounds.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
// user_answer=input.nextLine().charAt(0);
user_answer=input.next().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
// input.next();
}
}
while(!UserInput);
}
}
I am making basic java program to hold a secret word (mouse) and allow a user to guess letters. The program will end either when the user guesses all the letters in the word, or when they guess 7 wrong letters. Whenever I type any letter into the program, it will run through it without giving the user an option to enter another letter. What should I add so that it will only run the program once per letter entered? Also if it wasnt quite obvious I am new to coding.
import java.util.Scanner;
public class GuessWord
{
String Secretword="mouse";
String letter;
int index;
private int number;
private int counter;
private String guesses;
Scanner scan = new Scanner(System.in);
public GuessWord()
{
String Secretword="";
String letter = "";
String guesses = "";
int number = 0;
int counter = 0;
int index = 0;
}
public String getLetter(){
System.out.println("Please enter a letter");
letter = scan.next();
return letter;
}
public void calc(){
guesses=letter;
while(number <= 7 && counter<5)
{
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
guesses=guesses+" " +letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if(number == 7){
System.out.println("You lose");
}else
{
System.out.println("You win");
}
}
}//class
public class GuessWordR
{
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
g1.getLetter();
g1.calc();
}//class
}//main
You should use a while loop.
So while some condition is not met keep asking the user to enter a new key.
Perhaps add a new method to the GuessWord Class
public void startGuessing() {
while(hasGuesses /* some boolean flag */) {
getLetter()
getCalc()
}
}
And then call that method in your main method instead of getLetter() and getCalc().
You will need to add a boolean variable to your class to indicate when to exit this while loop and the logic to keep count of the number of failed guesses etc.
Use a boolean flag and run it in a loop. but for that you need to restructure your code as well. First fix the calc() method
public boolean calc() {
guesses = letter;
if (number <= 7 && counter < 5) {
if (Secretword.indexOf(letter) != -1) {
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
} else {
System.out.println("You entered an incorrect letter");
number++;
}
guesses = guesses + " " + letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if (number == 7) {
System.out.println("You lose");
return true;
} else if (counter == 5) {
System.out.println("You win");
return true;
} else {
return false;
}
}
Your main method should be update like this
public static void main(String[] args) {
GuessWord g1 = new GuessWord();
boolean completed = false;
while (!completed) {
g1.letter = g1.getLetter();
completed = g1.calc();
}
}
you ask user for input unless condition get satisfied instead of asking and calculating once. And read char by char input instead of reading whole string.
something like:
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
while(number <= 7 && counter<5){
g1.getLetter();
g1.calc();
}
}//class
I want to add a loop to my program so that when a user enters an incorrect name it goes back to the start of the program and asks them to enter their name again. I think I need a do-while loop but I am not sure how to implement it with the if statements and boolean already included. I want the user to be only have three entries and if they get it wrong three times then the program closes.
import java.util.Scanner;
public class Username
{
public static void main(String[] args)
{
{
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++)
{
if (name[i].equals(name1))
{
System.out.println("you are verified you may use the lift");
b = false;
break;// to stop loop checking names
}
}
if (b)
{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
You can use a condition in the while loop. Something along the lines of:
boolean b = false;
while(!b){
System.out.println("Enter your name");
String name1 = kb.nextLine();
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
b = true;
System.out.println("you are verified you may use the lift");
}else{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
}
The loop will quit if the name condition is fulfilled and will loop around if it is not.
You can do it like this:
int count = 0;
point:
do {
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
b = false;
break point;// to stop loop checking names
}
}
if (b) {
count++;
System.out.println("Invalid entry 2 attempts remaining, try again");
}
while(!b || count <=3)
Use the following approach. Good thing is that it is a clean and robust solution.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class AccessPoint
{
private Scanner scanner;
private List<String> usernames;
public AccessPoint()
{
scanner = new Scanner(System.in);
usernames = Arrays.asList("Barry", "Matty", "Olly", "Joey");
if (tryAccessForTimes(3))
{
allowAccess();
}
else
{
denyAccess();
}
scanner.close();
}
public static void main(String[] args)
{
new AccessPoint();
}
private boolean tryAccessForTimes(int times)
{
boolean accessAllowed = false;
for (int tryIndex = 1; tryIndex <= times && !accessAllowed; tryIndex++)
{
String userInput = getUserName();
for (String userName : usernames)
{
if (userName.equals(userInput))
{
accessAllowed = true;
break;
}
}
if (!accessAllowed)
{
printNumberOfTriesLeft(times, tryIndex);
}
}
return accessAllowed;
}
private void printNumberOfTriesLeft(int times, int tryIndex)
{
int triesLeft = times - tryIndex;
if (triesLeft != 0)
{
System.out.println("You have " + triesLeft
+ (triesLeft == 1 ? " try" : " tries") + " left.");
}
}
private String getUserName()
{
System.out.print("Enter Username: ");
return scanner.nextLine();
}
private void allowAccess()
{
System.out.println("Access Granted. Allowed to use lift.");
}
private void denyAccess()
{
System.out.println("Access Denied.");
}
}
package com.loknath.lab;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class User1 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"zerr", "barry", "matty", "olly", "joey" }; // elements
String []temp=name;
Arrays.sort(temp);
while (true) {
System.out.println("Enter your name");
String name1 = kb.nextLine();
if (Arrays.binarySearch(temp,name1)>=0) {
System.out.println("you are verified you may use the lift");
break;
} else {
System.out.println("Not a verified user try again!");
}
}
System.out.println("Done");
}
}
output
Enter your name
loknath
Not a verified user try again!
Enter your name
chiku
Not a verified user try again!
Enter your name
zerr
you are verified you may use the lift
Done
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.