Class constant final variable - java

This is my code. I need wordOfTheDay and answer to stay the same. I need a user to input an answer for "What is the word of the day" and "What is the answer to 3*8" and depending on their answer it will either be accepted as the correct answer or rejected and they try again.
I keep getting this compiler error
Error: cannot assign a value to final variable wordOfTheDay
Error: cannot assign a value to final variable answer
//The word of the day is Kitten
import java.util.Scanner;
public class SchmeisserKLE41 {
public static final Scanner input = new Scanner(System.in);
public static final String wordOfTheDay = "Kitten";
public static final int answer = 24;
public static void main(String[] args) {
int attempts = 3;
System.out.printf("Please enter the word of the day:");
wordOfTheDay = input.nextLine();
do{
-- attempts;
if(attempts == 0){
System.out.printf("Sorry! You've exhausted all your attempts!");
break;
}
System.out.printf("Invalid! Try again %d attempt(s) left.", attempts);
wordOfTheDay = input.nextLine();
}
while(!wordOfTheDay.equals("Kitten"));
System.out.printf("\nWhat is the answer to 3 * 8?");
answer = input.nextInt();
System.exit(0);
}
}

You need two different variables. One to store the word of the day, and the other to store the user's guess. So you'll need to have two different names for them. Maybe wordOfTheDay and usersGuess. Then you can compare them after the user guesses, by changing the condition at the end of your loop to while(!wordOfTheDay.equals(usersGuess));

wordOfTheDay = input.nextLine(); You've already set wordOfTheDay. it's final, so you can only set it once....

public static final String wordOfTheDay = "Kitten";
since wordOfTheDay declared as final, it can not be assigned any value after this.
all final variables can not be assigned a value more than once.
so remove final from it as below.
public static String wordOfTheDay = "Kitten";
now you can assign value any number of times.

Related

I try to make a guess game and let user decide under what max number to guess

In oder to check the value entered by the user AND to see what random number has been calculated, I want to let those numbers projected in the console (eclipse). But what sketches my astonishment?? the last two system.out.println's (right above invoermax.close())) do NOT appear in the console screen after I entered the number???? It's like java doesn't even read or notice these code lines, How come???
Here my code:
package Package1;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class test6KOPIE1 {
public static void main(String[] args)
{
Scanner Invoermax = new Scanner(System.in);
System.out.println("Under which number you want to guess");
int Invoer = Invoermax.nextInt();
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
System.out.println("So a guess under max: " + Invoer);
System.out.println("The random number has become " + Hoogte);
Invoermax.close();
}
}
every time you call Scanner.nextInt() it will wait for input from you.
The problem is that you are calling it twice, replace:
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
With the variable you already got:
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoer);
And BTW, usually in java you start field/variable name with lower case letter, so should be hoogte, inoverMax, inover etc.
You can do something like this.
// code
Scanner Invoermax = new Scanner(System.in);
System.out.println("Under which number you want to guess");
int Invoer = Invoermax.nextInt();
Invoermax.nextLine(); // reading empty space left
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
// code
You have two scanner.nextInt() calls, so there are two input readings, two input waitings.
int Invoer = Invoermax.nextInt(); // the first input reading
int Hoogte = ThreadLocalRandom.current().nextInt(1,
Invoermax.nextInt()); // the second input reading
When you enter two int values in a console (any of the kind) you'll see your ending print rows.
If your design was to have a single input, then use cashed value for the second usage
int Invoer = Invoermax.nextInt(); // the first input reading
int Hoogte = ThreadLocalRandom.current().nextInt(1,
Invoer ); // use cashed value

How to get this piece of code into loop, so that it asks a user input each time until the result is "kill"?

I was practicing this piece of code from the book 'Head First Java' and I'm quite confused on the positioning of the loop here.The code is for creating a kind of game that has a random dotcom word(ex: abc.com) occupying some array elements. here I gave that dotcom word the positions from 3 to 5 in the array, and the user tries guessing the position.
import java.util.Scanner;
public class RunTheGame {
public static void main(String[] args) {
MainGameClass sampleObj= new MainGameClass();
int[] location = {3,4,5};
sampleObj.setdotcomLocationCells(location);
Scanner input= new Scanner(System.in);
System.out.println("Enter your guess");
int userGuess=input.nextInt();
String answer = sampleObj.checkForDotcom(userGuess);
System.out.println(answer);
}
}
package simpleDotComGame;
public class MainGameClass {
int[] DotcomLocationCells;
int numOfHits=0;
public void setdotcomLocationCells(int[] location) {
DotcomLocationCells= location;
}
public String checkForDotcom(int userGuess) {
String result="miss";
for(int cell:DotcomLocationCells) {
if(cell == userGuess) {
result ="hit";
numOfHits++;
break;
}
} // end for loop
if(numOfHits == DotcomLocationCells.length) {
result = "kill";
System.out.println("The number of tries= "+numOfHits);
}
}
do {
<insert code where answer result is created>
} while (!answer.equals("kill"))
upd.: but you must override the equals method for correct use, because if you see how method declared in Object.class you find
public boolean equals(Object obj) {
return (this == obj);
You are allowed to declare the variable before initializing it:
String answer;
do {
answer = sampleObj.checkForDotcom(userGuess);
System.out.println(answer);
} while (!answer.equals("kill");
Also beware of the semantics of Scanner.nextInt(): if it can't parse the input as an int (for example, it contains letters), it will throw an exception, but won't jump over the invalid input. You'll have to use Scanner.nextLine() to force-jump over it, otherwise you'll get an infinite loop.
Rachna, the loop will be positioned, around the following code:
Scanner input= new Scanner(System.in);
System.out.println("Enter your guess");
int userGuess=input.nextInt();
String answer=sampleObj.checkForDotcom(userGuess);
System.out.println(answer);
//For string you must use the equals
if ("kill".equals(answer)){
break;
}
The reason why is that the kill command must be evaluated inside the loop to break it, and the input to continuously ask the user input until he hits all targets.
Here's how the loop should be positioned.
String answer = "";
do{
System.out.println("Enter your guess");
int userGuess=input.nextInt();
answer=sampleObj.checkForDotcom(userGuess);
System.out.println(answer);
}
while(!answer.equals("kill"));
NOTE: Never Check for String equality using == in Java unless you know what you're doing (also read as, unless you know the concept of String Constant Pool).

Java Do and While validation

I created this simple program where there is a password, for some reason if I input password the program will carry on executing even though I used do and while.
import java.util.Scanner;
public class PassCheck {
double password;
int UserInp;
public void Validation() {
do{
System.out.println("Please enter the password");
Scanner in = new Scanner(System.in);
int password = in.nextInt();
} while (password == 1111);
System.out.println("Please select whether you would like to workout area or perimeter");
System.out.println("Enter 1 for area and Enter 2 for perimeter");
Scanner in = new Scanner(System.in);
int UserInp = in.nextInt();
switch (UserInp){
case 1:
CircleArea CircleAreaObject = new CircleArea();
CircleAreaObject.area();
case 2:
}
}
}
You have two password variables. The "while" condition is using the method variable. You have another variable declared in the scope inside the while condition-- that one is not the one that the "while" condition is using.
So one solution is to pull out your "int password" declaration into a line immediately before the do/while loop. Then assign it inside the do/while loop scope. And remove the PassCheck password declaration in the class.
Your int password that you actually assign is only valid inside the brackets of your do { ... } block. In the while, you are referencing the double password which is never 1111.
do{
System.out.println("Please enter the password");
Scanner in = new Scanner(System.in);
int password = in.nextInt(); // This "password"...
} while (password == 1111); // is NOT the same variable as this...
In the while(password = 1111) you are referencing the double password (as someone already mentioned, why is this double? ). You cannot reference the local int password here, since it's scope is limited to the insides of the brackets above.
What you have done is to create a new variable password of type int in the scope of your do block, java let you do this because the pacakage-private password field declared at the beginning of your class is of type double rather than int like its's local counterpart. You can correct this problem by making the following changes to your class. Your class also had a lot of style and naming issues which I've cleaned up.
import java.util.Scanner;
public class PassCheck {
int password;
int userInp;
public void validation() {
do {
System.out.println("Please enter the password");
Scanner in = new Scanner(System.in);
password = in.nextInt();
} while (password != 1111);
System.out.println("Please select whether you would like to workout area or perimeter");
System.out.println("Enter 1 for area and Enter 2 for perimeter");
Scanner in = new Scanner(System.in);
int userInp = in.nextInt();
switch (userInp){
case 1:
CircleArea circleAreaObject = new CircleArea();
circleAreaObject.area();
case 2:
}
}
}

How to conver a string value to an integer

I want to convert a string value to an integer but I can't. My statement checked
=Integer.parseInt(input);
has an error, please help and thanks a lot in advance.
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
String input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLine();
if(input.length() < 12)
{
System.out.println("The digit is less than 12.");
}
int one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =Integer.parseInt(input);
System.out.println(checked);
}
}
Use checked =Long.parseLong(input); instead of checked =Integer.parseInt(input);
12 digit numbers are very large and so you can not store it in int.So you need to store in Long
12 digits number is a really big number...Integer can't store it. That is you error - so you need another type to store the number.
I recommend you to use Long : Long.parseLong(input);
That should solve the problem.
Your issue is this line:
input = reader.nextLine();
try this:
checked = Long.parseLong(input);
use
checked= Long.parseLong(input)
instead of
Integer.parseInt
it can't handle a 12 digit long number
You're getting an error because the string value that you are giving as input is more than 2147483647. This is the max int can store (you can sysout Integer.MAX_VALUE to check this). If you intend to input a bigger number, may be you can use long (max value 9223372036854775807)
System.out.println(Integer.MAX_VALUE); // =2147483647 (2^31 - 1)
System.out.println(Long.MAX_VALUE); // =9223372036854775807 (2^63 - 1)
Depending on the input size, you might want to choose the correct data type.
Please see http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for further details.
Here is the corrected program(assuming that your trying to find whether a User-inputted number is less than 12 and displaying the number
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
long input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLong();
if(String.valueOf(input).length() < 12)
{
System.out.println("The digit is less than 12.");
}
int one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =(long)(input);
System.out.println(checked);
}
}

initialization problems?

I am trying to make a program that lets the user enter an unknown value of names and then output the longest name entered. This is my code so far. When i compile I have several errors and they are all the same "cannot find symbol". Do i need to initialize those variables if so where?
import java.util.Scanner;
public class Name
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
longestName(kb);
}
public static void longestName(Scanner sc)
{
String name=kb.nextLine();
biggestName=name;
System.out.println("Type -1 if you want to quit");
int number=kb.nextInt();
While (number !=-1);
{
String name1=kb.nextLine();
if (name1.length() > biggestName)
{
biggestName=name1;
}
System.out.println("Do you want to continue? Type -1 to quit.");
int number1=kb.nextInt();
}
System.out.println("Longest name is "+biggestName);
}
}
Thanks for the help guys fixed the errors, and some other changes and the program gives the correct output.
import java.util.Scanner;
public class Name
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
longestName(kb);
}
public static void longestName(Scanner kb)
{
String biggestName;
System.out.println("Enter the first name");
String name=kb.nextLine();
biggestName=name;
System.out.println("Type -1 if you want to quit");
int number=kb.nextInt();
while (number !=-1)
{
System.out.println("Enter another name");
Scanner kb1 = new Scanner(System.in);
String name1=kb1.nextLine();
int length1=biggestName.length();
int length2=name1.length();
if (length2 > length1)
{
biggestName=name1;
}
System.out.println("Do you want to continue? Type -1 to quit.");
number=kb.nextInt();
}
System.out.println("Longest name is "+biggestName);
}
}
There are quite a few errors in your code. Without explaining every error in detail, here is an example of a modified version which works:
import java.util.Scanner;
public class Name
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
longestName(kb);
}
public static void longestName(Scanner sc)
{
System.out.println("Enter name, or type '-1' if you want to quit");
String name=sc.nextLine();
String biggestName="";
while (!name.equals("-1"))
{
if (name.length() > biggestName.length())
{
biggestName=name;
}
name=sc.nextLine();
}
System.out.println("Longest name is "+biggestName);
}
}
You passed in your Scanner to longestName, but in longestName, you named the parameter sc. Use sc instead of kb in longestName.
Use lowercase while instead of While; remove the semicolon following the while; a semicolon there means that that is the body, instead of the { } block below it.
I assume that at the bottom of the while loop, that you want to assign the next integer to number, not a new variable number1 that immediately goes out of scope.
You didn't declare what biggestName is (or name).
Two errors here :
While (number !=-1);
While should be while, and the ; makes an infinite loop.
And another problem is that you don't change number in the loop anyway.
1-
public static void longestName(Scanner sc)
Either change the name of the scanner to kb, or change every kb within the method to sc.
2- See Scanner issue when using nextLine after nextXXX
3- Use while instead of While, and remove the ;.
I can see the below problems in the code:
longestName() method should be using the reference name sc instead of kb (since kb is having scope only in main method)
The variable biggestName is not declared. It should be either declared as a class variable or a variable in longestName() method and should be of type String
It is not While, it is while with 'w' in smaller case
There should not be a semicolon after the while statement
At the end of the while loop, the number to be compared for the while loop is to be calculated and is currently assigned to wrong variable. kb.nextInt() should be assigned to variable number and not to number1 since the variable number1 is never read/used.
The > operator can not be applied for String types. In the line if (name1.length() > biggestName), we are comparing int with String and will result in compilation error. The line should be modified as if (name1.length() > biggestName.length())
Method nextInt() will cause InputMismatchException to be thrown if you are providing an input which is not a number.
Now I feel I should have written a corrected code like Joe Elleson did. But hope this answer helps.

Categories

Resources