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.
Related
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.
I have truly searched for the answer all over the Internet before coming here and I think that the answer will have something to do with the try/catch statements, but even after watching a couple tutorials on the topic I am not sure on how to implement that.
Anyways, I am trying to do a simple thing in my newbie reminders app that I am making (I am learning Java as my first language for about 3 months now).
I want the program to check the user's input and if it is a certain letter ("R") I want the program to do a certain stuff. If it is an integer from 0 to 100 then I want to do other stuff. And if its neither of them, then I want the "else" statement to work.
The issue that I can't get the "else" statement to work as I get the NumberFormatException error. For example if I enter some other letter i.e. "d" - I get this error message:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "d" at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580) at
java.lang.Integer.parseInt(Integer.java:615) at
mash.Dialogue.startDialogue(Dialogue.java:51) at
mash.Dialogue.newRem(Dialogue.java:27) at
mash.Dialogue.startDialogue(Dialogue.java:38) at
mash.Dialogue.start(Dialogue.java:13) at mash.Main.main(Main.java:9)
Here is the code (I am sorry for any readability issues, this is the first time ever I am showing my code to somebody). You don't have to read the else if statement, as the issue seems to not depend on the text inside of that statement.
I would really appreciate if anybody could point me what is wrong with the code and how I would get to do what I intended. Some newcomer-friendly solution will be much appreciated.
Thank you in advance!
String secondLetter = mash.nextLine();
if(secondLetter.equals("r") || secondLetter.equals("R")) { //if the user enters R - create a new Reminder
newRem();
}
else if((Integer.parseInt(secondLetter) >= 0) && (Integer.parseInt(secondLetter) < maximum)) { //if the user enters number - check task list
tasks.remText(Integer.parseInt(secondLetter));
System.out.println("Enter 'D' to set the reminder as Done. Or enter 'T' to return to the list");
String v = mash.nextLine();
System.out.println(v);
if(v.equals("d")|| v.equals("D")) { //if user enters D - set the reminder as done
tasks.setDone(Integer.parseInt(secondLetter));
System.out.println("The reminder is now added to 'Done' list");
}
else if(v.equals("t")|| v.equals("T")) { //if user enters T - return to the list of reminders
tasks.display();
}
else {
System.out.println("Please enter the correct symbol");
}
}
else {
System.out.println("Enter the correct symbol");
}
You can check your input if it's a valid number before attempting to convert it. For example:
if(!secondLetter.matches("[0-9]+")) {
//it's not a number, so dont attempt to parse it to an int
}
place it in your if/else like this:
if(secondLetter.equals("r") || secondLetter.equals("R")) {
newRem();
} else if(!secondLetter.matches("[0-9]+")){
System.out.println("please type r or R or a number");
} else if((Integer.parseInt(secondLetter) >= 0) && ...
Short answer: docs.oracle.
Complete answer:
You can use Integer.parsInt (String s) only on a string that can be parserized into an integer. The letter "R" can not be a number, so it generates an exception.
if(Character.isLetter(secondLetter) && "R".equalsIgnoreCase(secondLetter)){
do code with "R"
}else if(Integer.parseInt(secondLetter) > 0 && Integer.parseInt(secondLetter) < 100){
do code with 0 < number < 100
}else{
do something else
}
I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}
I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}
I've been trying different methods for converting a user string input into an int I could compare and build an "if-then" statement. Every time I tried testing it, it just threw exception. Can anyone look at my Java code and help me find the way? I'm clueless about it (also a noob in programming). If I'm breaking any rules please let me know I'm new here. Thank you.
Anyway, here is the code:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mistyped the answer.");
e.getMessage();
}
It seems like you are trying to convert the string (which should be a single character, Y or N) into its character value, and then retrieve the numerical representation of the character.
If you want to turn Y or N into their decimal representation, you have to perform a cast to int:
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.charAt(0);
int integerChar = (int) i; //The important part
System.out.println(integerChar);
This will return the integer representation of the character that the user input. It may also be useful to call the String.toUpperCase() method in order to ensure that different inputs of Y/N or y/n do not give different values.
However, you could also do an if-else based upon the character itself, rather than converting it to an integer.
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.toUpperCase().charAt(0);
if (i == 'Y') {
//Handle yes
} else if (i == 'N') {
//Handle no
} else {
System.out.println("You've mistyped the answer.");
}
I think you meant to ask them to Enter 0 for yes and 1 for No ? Maybe?
You're asking the user to type Y or N and then you're trying to parse that to an integer. That will always throw an exception.
EDIT -- As others have pointed out, if you want to continue to use Y or N, you should do something along the lines of
String addNewUser = answer.readLine();
if ( addNewUser.toLowerCase().startsWith("y") ) {
// Create new profile
}
parseInt is just for converting text numbers into integers: everything else gets a NumberFormatException.
If you want the decimal ASCII value of a character, just cast it to an int.
Use if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) { instead.
Or (as Mark pointed) if (addNewUser.toLowerCase().startsWith("y")) {.
BTW maybe look at Apache Commons CLI?
You cannot convert String to int, unless you know the String contains a valid integer.
Firstly, using the Scanner class for input is better, since its faster
and you don't need to get into the hassle of using streams, if you're
a beginner. This is how Scanner will be used to take input:
import java.util.Scanner; // this is where the Scanner class resides
...
Scanner sc = new Scanner(System.in); // "System.in" is the stream, you could also pass a String, or a File object to take input from
System.out.println("Would you like to ... Enter 'Y' or 'N':");
String input = sc.next();
input = input.toUpperCase();
char choice = sc.charAt(0);
if(choice == 'Y')
{ } // do something
else if(choice == 'N')
{ } // do something
else
System.err.println("Wrong choice!");
This code could also be shortened to one line (however you won't be
able to check a third "wrong choice" condition):
if ( new Scanner(System.in).next().toUpperCase().charAt(0) == 'Y')
{ } // do something
else // for 'N'
{ } // do something
Secondly, char to int conversion just requires an explicit type
cast:
char ch = 'A';
int i = (int)ch; // explicit type casting, 'i' is now 65 (ascii code of 'A')
Thirdly, even if you take input from a buffered input stream, you
will take input in a String. So extracting the first character from
the string and checking it, simply requires a call to the charAt()
function with 0 as a parameter. It returns a character, which can
then be compared to a single character in single quotes like this:
String s = in.readLine();
if(s.charAt(0) == 'Y') { } // do something
Fourthly, its a very bad idea to put the whole program in a try
block and catch Exception at the end. An IOException can be
thrown by the readline() function, and parseInt() could throw a
NumberFormatException, so you won't be able to handle the 2
exceptions separately. In this question, the code is small enough for
this to be ignored, but in practice, there will be many functions
that can throw exceptions, hence it becomes easy to lose track of exactly which function threw what exception and proper exception handling becomes quite difficult.