In this method, it prompts the user to enter the value of their insured home. For some reason, it is getting stuck when the user inputs
static double promptHomeInsVal(){
double homeInsVal;
className promptHomeInsVal = new className();
do{
do{
System.out.printf("%nPlease enter the insured value of your home: ");
homeInsVal = promptHomeInsVal.input.nextDouble();
validateNumber(!promptHomeInsVal.input.hasNextDouble());
}while(promptHomeInsVal.repeat == true);
homeInsVal = promptHomeInsVal.input.nextDouble();
if(homeInsVal <= 0){
System.out.println("The insured value of your home cannot be less than or equal to 0. ");
promptHomeInsVal.repeat = true;
}
else{
promptHomeInsVal.repeat = false;
System.out.println("Home insurance value == " + homeInsVal);
}
}while(promptHomeInsVal.repeat == true);
return homeInsVal;
}
Here is validateNumber()
static void validateNumber(boolean repeat){
className validateNumber = new className();
if(repeat == true){
System.out.println("Warning: You entered an invalid integer or floating-point value. ");
}
}
When the prompt comes up "Please enter the insured value of your home: " it is suppose to take the input and move on. Right now, it is getting stuck
I feel that a significant part of the code is missing, and as far as I can see the problem should be in that part of the code. You should include into your question the code of the class className (which seems to be an error by itself).
In addition to that, I see some minor coding style mistakes in your code. You did not ask for such advice, but let me note that anyBooleanVariable == true is just the same as anyBooleanVariable.
Also validateNumber is the name of a method and the same time the name of a local variable inside the same named method. It is possible, but this is confusing and not a recommended practice.
Related
So I'm currently working on a school assignment which is to design a program that allows the user to enter some text, and then the program checks:
The first letter of the first word is a capital letter (it needs to be lowercase)
That there are only letters and numbers in the entire user input
That there are no spaces in the user input
So the program does work but the issue I'm having is with the print statements, I'll post my code below and explain:
public static void main(String[] args) {
try (Scanner stdln = new Scanner(System.in)) {
String userInput;
boolean legal = true;
boolean style = true;
char input; //Checks the userInput variable to be sure that boolean is false if there's no lowercase letter at char0 + if there are no letters
char loop;
System.out.println("The program checks the properness of a proposed Java variable name.");
System.out.println("\nPlease enter a variable name (q to quit): ");
userInput = stdln.nextLine();
input = userInput.charAt(0);
do
{
if (!(Character.isLetter(input)))
{
legal = false;
}
if (userInput.contains(" "))
{
legal = false;
}
if (!(Character.isLowerCase(input)))
{
style = false;
}
for (int i = 1; i < userInput.length() &&legal; i++)
{
loop = userInput.charAt(i);
if (!(Character.isLetterOrDigit(loop)))
{
style = false;
}
}
if (!(legal) && !(style))
{
System.out.println("Illegal.");
}
else if (legal && !(style))
{
System.out.println("Legal, but uses poor style.");
}
else
{
System.out.println("Good.");
}
System.out.println("\nPlease enter a variable name (q to quit): ");
userInput = stdln.nextLine();
input = userInput.charAt(0);
} while (!(userInput.equalsIgnoreCase("q")));
}
}
}
So the code works and the first input I test comes out as it should, however, once I get a response that isn't "Good.", then the same response will print for every entry, here's a sample from a session I just did:
The program checks the properness of a proposed Java variable name.
Please enter a variable name (q to quit):
streetAddress2
Good.
Please enter a variable name (q to quit):
StreetAddress2
Legal, but uses poor style.
Please enter a variable name (q to quit):
streetAddress2
Legal, but uses poor style.
Please enter a variable name (q to quit):
Street Address2
Illegal.
Please enter a variable name (q to quit):
streetAddress2
Illegal.
In that sample session, 3 and 5 should return the statement "Good." but for some reason, it just prints the statement from the previous entry. I'm still fairly new to Java so I'm a little stumped. Any ideas?
You have to reset legal and style to true at the start of each iteration. However, it is not the only problem with your code. The logic is not correct.
Right now in the for loop you check all the characters being letters or digits. If this condition fails you set style to false. However, you should set legal to false instead, because such identifiers are not allowed.
Also, when you print the result you don't check the conditions correctly. For example, if legal is false, but style is true your code will print Good.
You forgot to reset to true your legal and style boolean variables.
At every iteration, the legal and style variables will keep containing the result of the previous input. For example, if on your first input you immediately write a variable name with an illegal syntax and poor style, you'll see that any following name will show the same result. Even though those names are good or they only lack in style, the output will still be the same (wrong) because both variables have been left to false and nothing sets them back to true.
Besides, the logic to print the output messages didn't account for all combinations correctly.
Both variable logic and output printing could be re-written as follows:
do {
//forgotten reset
legal = true;
style = true;
//excat same implementation of yours
if (!(Character.isLetter(input))) {
legal = false;
}
if (userInput.contains(" ")) {
legal = false;
}
if (!(Character.isLowerCase(input))) {
style = false;
}
for (int i = 1; i < userInput.length() && legal; i++) {
loop = userInput.charAt(i);
if (!(Character.isLetterOrDigit(loop))) {
style = false;
}
}
//If it's illegal it does not matter whether the variable name has a poor or good style, it's illegal anyway
if (!legal) {
System.out.println("Illegal.");
//If we're in this else branch then the variable name is legal, but we have to check its style.
//If it has poor style then we print the "poor style" message.
} else if (!style) {
System.out.println("Legal, but uses poor style.");
} else {
//Last case where the variable name is legal and has a good style
System.out.println("Good.");
}
System.out.println("\nPlease enter a variable name (q to quit): ");
userInput = stdln.nextLine();
input = userInput.charAt(0);
} while (!(userInput.equalsIgnoreCase("q")));
Ok, so my computer teacher has asked us to make a simple game that asks the user to guess a radomly generated number, but I want to take it one step further and make it so that it display error messages when the user tries certain things. The problem here is that I am new to booleans and well, I am having a bit of trouble using java.util.Scanner and booleans. So, if anyone could take a quick look at this I would appreciate it.
import java.util.Scanner;
import java.util.Random;
public class MoreGuessing{
//Instantiation
Scanner reader = new Scanner(System.in);
Random number = new Random();
//Variables
int randomnumber = number.nextInt(10) + 1;
int cntr = 1;
static String decimalguessed;
String error1 = "Error001: Decimal found, please enter a whole number between 1-10." + "\n" + "Program terminated......";//Decimal portion error.
String error2 = "Please enter a positive number." + "\n" + "Program terminated......"; //Negative number error.
String error3 = "Unknown character entered." + "\n" + "Program terminated......"; //Unknown character error.
//Verifier
public static boolean verifyLetters() {
if (decimalguessed.matches("[a-zA-Z]+")){
return true;
}else{
return false;
}
}
public static void main(String [] args){
//Input and display
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextLine();
//Process and Errors
while (decimalguessed != randomnumber) {
if (verifyLetters() != false){
System.out.println(error3);
System.exit(1);}
if (decimalguessed % 1 != 0) {
System.out.println(error1);
System.exit(1);}
if (decimalguessed < 0) {
System.out.println(error2);
System.exit(1);}
if (randomnumber != decimalguessed){
System.out.println("You've lost, please make another attempt.");}
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextDouble();
cntr++;
}
if (cntr == 1) {System.out.println("Congratulations! You've guessed the number on your first attempt!");;
}
else {System.out.println("Congratulations! You've guessed the number, it took you " + cntr + " tries");}
}
}
You need to parse your input. decimalguessed is a string, and so you can't do comparisons like decimalguessed % 1.
You can convert it to an integer like this:
int guess = 0;
try {
guess = Integer.parseInt(decimalguessed);
} catch (NumberFormatException e) {
System.out.println("Your guess was not an integer: " + e.getMessage());
System.exit(1);
}
This will handle both cases where decimalguessed contains letters, and where it contains decimal points/fractions. decimalguessed is still a string, but guess now contains the integer version of it, so you can compare it to randomnumber properly. (Your loop would have never exited before, because a string is never == an integer)
Some other notes:
You should never have:
if (condition) {
return true;
} else {
return false;
}
This can always be simply replaced with
return condition;
It feels like you're very new to this. Welcome to programming!
So first, in Java generally you're not going to have all of that instantiation and variables stuff outside of your main function, unless you're going to make everything static. I would move all of that into your main function, un-static the decimalguessed variable and setup your verifyLetters function to take an argument of String decimalguessed. It may also be wise to check if the value is a number, rather than seeing if it is not a letter. There a lot of non-number, non-letter characters.
Once you've figured out that the guess is a number, you need to tell java it is one (cast it) to a decimal, then do you further comparisons against that decimal.
Darth Android also makes some good points, especially about booleans. You should never have the only result of an if/else be to return a boolean, just return the boolean. Also avoid comparisons to true/false, just do the if on the function/variable alone, or negate it with an '!' to check for false.
Good luck!
this i my first attempt at asking a question so hopefully it shows correctly. Basically what I need the program to do is to ask the user for a preset account number and password and only allow them 3 attempts. I then want to call up another method when both requirements are met so i can continue with the program. The first problem i have is that when i enter the correct password its is still showing as incorrect and i don't know why, then i would like to know if i have call the method within the if statement correctly. Thanks.
import java.util.Scanner;
public class Part4 {
public static void main(String[] args)
{
String password = "password", passwordattempt = null;
int accnum = 123456789, acctry = 0, tries = 0;
Scanner input = new Scanner (System.in);
while (acctry != accnum){
System.out.println("\nPlease enter your account number");
acctry = input.nextInt();
if (acctry != accnum)
System.out.print("That number is incorrect. Please try again.");
else
if (acctry == accnum)
{
while (tries < 3)
{
System.out.println("\nPlease enter password");
passwordattempt = input.next();
if (passwordattempt != password){
System.out.print("That password is incorrect");
tries++;
}
else
if (passwordattempt == password){
System.out.print("That is correct");
AccountDetails.Details(args);
}
}
System.out.print("\nYou have exceeded the ammount of tries");
}
}
}
public static class AccountDetails {
private static void Details(String[] args){
System.out.print("it works");
}
}
}
two problems.
1: You're executing your while loop regardless of if it is successful or not.
.
while(tries < 3)
should be
while(tries < 3 && !successfulPassword)
You'll need to add the successfulPassword variable, so that you don't get it right the first time and yet continue to have to enter passwords.
2: Your comparison of strings is grossly, umm, well, wrong. There's two things that catch my eye. The first is you can't use == and != and get the results you expect. You must use .equals(). Secondly, you don't need to repeat the opposite clause like you do with a human. For example, I tell my daughter "If you eat your supper, then you may have cookies. Else, if you do not eat your supper, then you may not have cookies." To a computer, you don't need that last "if you do not eat your supper". It's guaranteed to be true (since you're in the else block anyway) and it just clutters it up. So that just becomes
.
if(passwordAttempt.equals(password) {
successfulPassword = true;
} else {
tries++;
}
In the Java language, Strings are objects, and thus comparing them using '==' is testing by reference, and not by equality.
I believe what you are looking for is
if (passwordattempt.equals(password)) {
Check here for more information:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object)
I have initialized and declared the variable "average." I do not understand why it won't compile. Does it have to do with the fact that it's in an if else? I've already tried
"|| null" and that is not taking either. What to do?
// declare variables
Scanner keyboard = new Scanner (System.in);
String given;
String middle;
String sur;
String truefalse;
boolean bool;
int exam1;
int exam2;
int exam3;
double average;
// get input
System.out.println("*************** Grade Computer *************");
System.out.println("Enter the student's first name: ");
given = keyboard.nextLine();
System.out.println( "Enter the student's middle initial: ");
middle = keyboard.nextLine();
System.out.println( "Enter the student's last name: ");
sur = keyboard.nextLine();
System.out.println( "Enter EXAM 1 Grade: ");
exam1 = keyboard.nextInt();
System.out.println( "Enter EXAM 2 Grade: ");
exam2 = keyboard.nextInt();
System.out.println( "Enter EXAM 3 Grade: ");
exam3 = keyboard.nextInt();
keyboard.nextLine();
System.out.println( "Bonus work completed [true/false]");
truefalse = keyboard.nextLine();
// adjust exam scores if necesssary
if (truefalse == "true")
{
bool = true;
exam1 = keyboard.nextInt();
exam2 = keyboard.nextInt();
exam3 = keyboard.nextInt();
}
else
{
average = ((exam1+exam2+exam3)/3);
}
Why is the compiler saying
"variable average might not have been initialized"?
You declared your variable but did not strictly initialize it. It is only initialized if the logic of your program dictates that the line average = ((exam1+exam2+exam3)/3); is hit. This doesn't happen if truefalse == "true".
In order to have Java compile it, you can do one of two things.
Initialize your variable to some default value when you declare it, eg double average = 0;
Make sure that no logical pathway precludes the possibility that the variable is initialized. That is, no matter what happens, it gets initialized.
The first option is better. It keeps your code cleaner and more logical, thus easier to maintain. The second option is more implicit than explicit. You probably shouldn't have to go walking through the logic yourself to see how it works out.
You can initialize the double variable average to 0 when you are declaring it.
double average=0;
Reason of this particular error is that you are trying to initialize the variable in if-else block. The variable will not be initialized if condition is not true. If you are using the variable further in your program, you will get run time errors. That is why Java compiler is letting you know that there are possibilities that the variable might be uninitialized
Furthermore it is always a good practice to initialize a local variable when you declare it.
You need to initialize average.
The compiler is complaining because your code might or might not ever reach the else block. Yet, if you use average when it hasn't been initialized, you get an error.
double average = null;
Alternatively, you can initialize average in the if block as well, because if the if block runs and the else doesn't you'll still have an initialized average at the end of the day and the compiler is happy :).
if (truefalse == "true")
{
average = //something;
bool = true;
exam1 = keyboard.nextInt();
exam2 = keyboard.nextInt();
exam3 = keyboard.nextInt();
}
else
{
average = ((exam1+exam2+exam3)/3);
}
Also, as a final note, a good rule of thumb is to use .equals() for any String and == for ints, characters, booleans etc.
This is driving me insane! Here's the code:
public static void main(String[] strings) {
int input;
String source;
TextIO.putln("Please enter the shift value (between -25..-1 and 1..25)");
input=TextIO.getInt();
while ((input < 1 || input > 25) && (input <-25 || input >-1) && (input != 999 && input !=-999))
{
TextIO.putln(input + " is not a valid shift value.");
TextIO.putln("Please enter the shift value (between -25..-1 and 1..25)");
input=TextIO.getInt();
}
TextIO.putln("Please enter the source text (empty line to quit)");
//TextIO.putln(source);
source = TextIO.getln();
TextIO.putln("Source :" + source);?");
}
}
However, its telling me that 'source' is never read! It's not allowing me to get input! Can anyone see what the problem may be?
The compiler is correct; the variable source is never read. You're assigning a value to it (source = TextIO.getln();), but you're never reading that value back out.
To do so, you could do something like:
TextIO.putln(source);
You seem to be having trouble reading text from the console with the TextIO class. Here's a more standard approach, introduced in Java 5:
String source;
Scanner in = new Scanner(System.in);
source = in.nextLine();
What exactly do you wish to do with the variable source? As it stands, you're asking the user to enter a string, but you're not doing anything with that string.
You should probably ask one of your friends for help instead of posting our homework online. I feel as though this is subjective to cheating. If you are having trouble already, it is only going to get worse. You should be breezing through your freshman year.