so basically I am trying to create a program where when the user is prompted to ask their name, if he gives a name that appears in the file "badWords.txt" the user will not be able to continue. The program will only loop if the user enters a name not found in the document. I am trying to do this below but am failing miserably, can I get any help? I know I did the second part correct with the catch statement, just need help with the first. Thank you!
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class NameExperiment
/**
* Prompts user ith 5 quick-fire addition problems, and times
* the user for the response provided.
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.print("Please enter your name: ");
String name = in.nextLine();
try
{
Scanner badWords = new Scanner(new File("badWords.txt"));
}
while (badWords.hasNext())
catch{
{
if (name.equalsIgnoreCase(badWords.next()))
{
throw (new BadWordException("Watch your tongue"));
}
}
}
System.out.println("Hello " + name +
". Please Answer the questions as fast as you can.");
for (int i = 0; i < 5; i++)
{
System.out.println("Hit <ENTER> when ready for a question.");
in.nextLine();
int a = rand.nextInt(100);
int b = rand.nextInt(100);
long startTime = System.currentTimeMillis();
System.out.print(a + " + " + b + " = ");
String response = in.nextLine();
try
{
int number = Integer.parseInt(response);
long endTime = System.currentTimeMillis();
String outcome = (number == a +
b) ? "Correct!" : "Incorrect.";
System.out.println(outcome);
System.out.println("That took " + (endTime -
startTime) + " milliseconds");
}
catch (NumberFormatException exception)
{
System.out.print("Inappropriate Input: please enter a number.");
}
}
System.out.println("Thank you "+ name + ", goodbye.");
}
}
}
edit first part and tested now its work
public class NameExperiment{
/**
* Prompts user ith 5 quick-fire addition problems, and times
* the user for the response provided.
*/
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
Random rand = new Random();
Scanner badWords = new Scanner(new File("src", "badWords.txt"));;
System.out.print("Please enter your name: ");
String name = in.nextLine();
while (badWords.hasNext())
if (name.equalsIgnoreCase(badWords.next()))
{
throw new NumberFormatException("Watch your tongue");
}
System.out.println("Hello " + name +". Please Answer the questions as fast as you can.");
for (int i = 0; i < 5; i++)
{
System.out.println("Hit <ENTER> when ready for a question.");
in.nextLine();
int a = rand.nextInt(100);
int b = rand.nextInt(100);
long startTime = System.currentTimeMillis();
System.out.print(a + " + " + b + " = ");
String response = in.nextLine();
try
{
int number = Integer.parseInt(response);
long endTime = System.currentTimeMillis();
String outcome = (number == a +
b) ? "Correct!" : "Incorrect.";
System.out.println(outcome);
System.out.println("That took " + (endTime -
startTime) + " milliseconds");
}
catch (NumberFormatException exception)
{
System.out.print("Inappropriate Input: please enter a number.");
}
}
System.out.println("Thank you "+ name + ", goodbye.");
}
}
Related
Query by loan ID
// Method that allows the user to query by loan ID
public static void QuerybyloanID(List<Loan> data) {
try (Scanner entry = new Scanner(System.in)) {
System.out.print("Please, enter the loan ID: ");
String userentry = entry.next();
// For loop is used to locate the loan ID within the list of loans
for (int i = 0; i < data.size(); i++) {
String loanID = data.get(i).getLoanID();
if (loanID.equals(userentry)) {
boolean pass = true;
String loanPassword = data.get(i).getPasscode();
// Three possible character from the loan password
int one;
int two;
int three;
int [] randomCharacters = randomUniqueGenerator(3, loanPassword.length());
one = randomCharacters[0];
two = randomCharacters[1];
three = randomCharacters[2];
// Check to see if the random numbers are the same or different. -> Implement a Hash Map.
char entry_one = loanPassword.charAt(one);
char entry_two = loanPassword.charAt(two);
char entry_three = loanPassword.charAt(three);
String entry_one_modify = Character.toString(entry_one);
String entry_two_modify = Character.toString(entry_two);
String entry_three_modify = Character.toString(entry_three);
String [] entriesmain = {entry_one_modify, entry_two_modify, entry_three_modify};
try (Scanner entrytwo = new Scanner(System.in)) {
for (int k = 0; k < 3; k ++) {
System.out.print("Enter character " + randomCharacters[k] + " of the loan pass code: ");
String userentrytwo = entrytwo.next();
entrytwo.nextLine();
if (userentrytwo.equals(entriesmain[k])) {
continue;
} else {
pass = false;
continue;
}
}
}
// Check to see if pass is true or false then take the appropriate action
if (pass) {
System.out.println("Customer Name: " + data.get(i).getFirstName() + " " + data.get(i).getLastName());
System.out.println("Branch Code: " + data.get(i).getBrachCode());
System.out.println("Gender: " + data.get(i).getGender());
System.out.println("Date of Birth: " + data.get(i).getDOB());
System.out.println("Loan Amount: " + data.get(i).getLoanAmount());
System.out.println("Customer Phone Number: " + data.get(i).getPhoneNumber());
MainMenu.options();
} else {
System.out.println("Wrong Passcode !");
MainMenu.options();
}
}
Firstly, thanks for reading my post and helping me out.
I'm trying to program where I define a random number, the program guesses this random number, and then, depending on whether I say the guess is too high or low, the program guesses again.
When the program guesses a number which is too high, the user is to type "lower" and then the program to only guess numbers which are lower.
Ideally, the program would consider the results of all previous choice. So if guess #1 was too high, this should remain the upper-bound for all iterations afterwards. We don't want only the upper or lower bound changing with every iteration.
What I've tried to do with my code is reset the min and max values used to compute the random number ( ThreadLocalRandom ).
The main issue is that I cannot get the oMin and oMax values to reset. I don't understand how to get around this, sorry if this is a totally silly question.
Thanks again!
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class J4AB_S11_C3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int oMin = 0;
int oMax = 101;
int randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
String userReply;
System.out.println("What's the lucky number, kiddo?");
int correctAnswer = scanner.nextInt();
System.out.println("Is " + randomNumber + " the right answer?");
userReply = scanner.next();
while ("Higher".equalsIgnoreCase(userReply)) {
oMin = randomNumber;
}
while ("Lower".equalsIgnoreCase(userReply)) {
oMax = randomNumber;
}
if (userReply.equalsIgnoreCase("Correct")) {
System.out.println("We finally did it! " + correctAnswer + " was the correct answer.");
}
}
}
Use do-while for this, if-condition to check higher and lower. And close scanner after the do-while
Scanner scanner = new Scanner(System.in);
int oMin = 0;
int oMax = 101;
String userReply;
int correctAnswer;
do {
int randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
System.out.println("What's the lucky number, kiddo?");
correctAnswer = scanner.nextInt();
System.out.println("Is " + randomNumber + " the right answer?");
userReply = scanner.next();
if ("Higher".equalsIgnoreCase(userReply)) {
oMin = randomNumber;
}else if ("Lower".equalsIgnoreCase(userReply)) {
oMax = randomNumber;
}
} while (!userReply.equalsIgnoreCase("Correct"));
System.out.println("We finally did it! " + correctAnswer + " was the correct answer.");
scanner.close();
I made a few edits and added a while loop, check it out. I tested it and it seems to be working.
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class J4AB_S11_C3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int oMin = 0;
int oMax = 101;
int randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
String userReply;
System.out.println("What's the lucky number, kiddo?");
int correctAnswer = scanner.nextInt();
System.out.println("Is " + randomNumber + " the right answer?");
userReply = scanner.next();
while (!"Correct".equalsIgnoreCase(userReply)){
if ("Higher".equalsIgnoreCase(userReply)) {
oMin = randomNumber;
}
if ("Lower".equalsIgnoreCase(userReply)) {
oMax = randomNumber;
}
randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
System.out.println("Is " + randomNumber + " the right answer?");
userReply = scanner.next();
}
if (userReply.equalsIgnoreCase("Correct")) {
System.out.println("We finally did it! " + correctAnswer + " was the correct answer.");
}
}
}
I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).
This is for personal knowledge of how this works, is not for school
Program requirements - Enter 2 Names. Have the program find the assigned values with the names and print the average between the two people.
I an not sure how to get the Scanner to take the input and go to the class to make it start processing. For example, in the main method if I sysout print a, it should display the string inside the method getName.
import java.util.Scanner;
public class RainFallApp {
public static void main(String[] args) {
rainfall a = new rainfall();
rainfall b = new rainfall();
System.out.println(a);
// System.out.print("Please enter month one: ");
// Scanner = new Scanner(System.in);
// rain1 = aRain;
// System.out.print("Please enter month two: ");
// Scanner = new Scanner(System.in);
//
// int average = (rain1 + rain2) / 2;
// System.out.println("The average rainfall for " + var +
"and " + var2 +"is: " + average);
}
}
class rainfall {
String rainamt;
String Rain_Amount;
Scanner input = new Scanner(System.in);
String rainMonth = input.nextLine();
String rainAmount(String rainMonth) {
Rain_Amount = getName(rainMonth);
return Rain_Amount;
}
private String getName(String rainMonth) {
if (rainMonth.equals("Jan")) {
rainamt = "3.3";
}
else if (rainMonth.equals("Feb")) {
rainamt = "2.2";
}
else {
System.out.println("Not a valid month name");
}
return rainamt;
}
}
You only need to say Scanner scanner = new Scanner(System.in); once. Then you can use the scanner's nextLine() method to input data. It returns a string, so be sure to store the result in a variable.
I completed my program
import java.util.Scanner;
public class RainFallApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the first month: ");
String aMonth = input.nextLine();
System.out.print("Please enter the second month: ");
String bMonth = input.nextLine();
rainfall aRainfall = new rainfall();
String aName = aRainfall.rainAmount(aMonth);
Double aAmount = Double.parseDouble(aName);
rainfall bRainfall = new rainfall();
String bName = bRainfall.rainAmount(bMonth);
Double bAmount = Double.parseDouble(bName);
double Avg = (aAmount + bAmount) / 2;
System.out.println("\nIn the month of " + aMonth + " it had "
+ aAmount + " inches of rain.");
System.out.println("In the month of " + bMonth + " it had "
+ bAmount + " inches of rain.");
System.out.println("The average rainfall between the two months is: " + Avg);
}
}
class rainfall {
private String Rain_Amount;
String rainAmount(String rainMonth) {
Rain_Amount = getAmount(rainMonth);
return Rain_Amount;
}
private String getAmount(String rainMonth) {
if (rainMonth.equals("Jan")) {
Rain_Amount = "3.3";
}
else if (rainMonth.equals("Feb")) {
Rain_Amount = "2.3";
}
else {
System.out.println("Not a valid month name");
}
return Rain_Amount;
}
}
i'll get straight to the chase. If a user wants to read another file they must type r in the menu, then they are thrown with a return readFile(); method which takes them to the top of the program and asks them the same question it did at the beggining when they first ran this program. Only issue is when you type R or Default it throws an OutOFBoundsException. BTW It is Reading a CSV file
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at studentrecs.StudentRecs.in(StudentRecs.java:71)
at studentrecs.StudentRecs.readFile(StudentRecs.java:55)
at studentrecs.StudentRecs.menu(StudentRecs.java:97)
at studentrecs.StudentRecs.main(StudentRecs.java:33)
Java Result: 1
/
public static Boolean readFile(String filename) throws IOException { //Constructor for filename
try {
Scanner userInput = new Scanner(System.in);
System.out.println("Type R To Read a File or Type Default for the default file");
user = userInput.nextLine();
if (user.equalsIgnoreCase("r")) {
user = userInput.nextLine();
}
filename = user;
if (user.equalsIgnoreCase("default")) {
filename = "newreg2.csv";
}
Scanner input = new Scanner(new FileReader(filename));
while (input.hasNext()) {
in(input.nextLine());
numstu++;
}
input.close();
return true;
} catch (IOException e) {
System.err.println(e.getMessage());
}
return false;
}
public static void in(String reader) {
String splitter[];
splitter = reader.split(",");
stu[numstu] = new StuRec();
stu[numstu].studentID = splitter[0];
stu[numstu].lastName = splitter[1];
stu[numstu].firstName = splitter[2];
stu[numstu].phoneNumber = splitter[3];
stu[numstu].courseCode = splitter[4];
stu[numstu].periodNumber = Integer.parseInt(splitter[5]); // parseInt turns a string of digits into an integer
stu[numstu].mark = Integer.parseInt(splitter[6]);
}
public static boolean menu() throws IOException {
String choice;
Scanner userInput = new Scanner(System.in);
System.out.println("=============================================");
System.out.println("Type R To Read Another File");
System.out.println("Type L To Print all File Records");
System.out.println("Type AA To Print The Average Of All The Marks");
System.out.println("Type X To Exit The Program");
choice = userInput.nextLine();
double average = 0.0; // declare average
if (choice.equalsIgnoreCase("L")) {
for (int i = 0; i < numstu; i++) {
System.out.println(stu[i].lastName + ", " + stu[i].firstName + ", " + stu[i].studentID + ", " + stu[i].phoneNumber + ", " + stu[i].courseCode + ", " + stu[i].periodNumber + ", " + stu[i].mark);
}
}else if (choice.equalsIgnoreCase("R")){
return readFile(filename);
} else if (choice.equalsIgnoreCase("AA")) {
for (int i = 0; i < numstu; i++) {
average += stu[i].mark; // keep adding to average
}
}else if (choice.equalsIgnoreCase("X")) {
for (int i = 0; i < numstu; i++) {
System.exit(i);
}
}else if (choice.equalsIgnoreCase("AC")) {
} else {System.err.println("Unknown Key Try Again...");
}
// divide by zero protection
if ( choice.equalsIgnoreCase("AA") && numstu > 0 ) {
average = average/numstu; // compute the average. Always use the size in terms of a variable whenever possible.
System.out.println(average); // as noted below, if this is an integer value, < #of students computations will eval to 0.
}
else if (!choice.equalsIgnoreCase("AA") && numstu < 0) {
System.out.println("Oops! No Marks To Calculate! :(");
}
return menu();
}
}
It looks like EITHER you have initialised numstu to start at 1, OR you have more than 1000 lines in your file.
The effect of either of these errors would be that you eventually attempt to write data to entry 1000 of stu. But since you've initialised stu with 1000 entries, numbered from 0 to 999, this gives your error.
You should make sure that numstu is initially 0, not 1.
And next time you post a question, post ALL of your code, not just the parts where you think the error might be. It's very difficult for most people to find bugs in code that they can't see.