Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I've got a strange issue (or at least strange to me). I've got a couple if-else-if statements that are causing strange behavior. For context, I'm essentially taking a char input using the Scanner class and using Scanner.nextInt().charAt(0). This appears to work fine if I check for the required characters and input a totally random character (it returns text to the terminal, breaks out, and exits). However, if I just hit enter at the char prompt, it creates what appears to be an infinite loop (maybe a memory leak?). Attached is the code I'm working on, as well as screenshots of it running in Coderunner2.
Thanks in advance!
import java.util.*;
import java.io.*;
public class phonebill
{
public static void main(String[] arg)
{
Scanner sc = new Scanner(System.in);
System.out.print("Please input the account number: ");
int acct = sc.nextInt(); // reads arbitrary account number
System.out.print("Please input service code: ");
char svc_code = sc.next().charAt(0); // reads service code
character
/* the following blocks check for the appropriate service codes.
* valid codes include p or P for 'Premium' service, and
* r or R for regular service. if no valid code is read,
* the program exits, informing the user to input a valid code.
*/
if (svc_code == 'p' || svc_code == 'P')
{
System.out.print("Please input daytime minutes: ");
int day_min = sc.nextInt();
System.out.print("Please input nighttime minutes: ");
int night_min = sc.nextInt();
System.out.println("Service code is " + svc_code + " and this condition works.");
}
else if (svc_code == 'r' || svc_code == 'R')
{
System.out.print("Please input used minutes: ");
int mins = sc.nextInt();
System.out.println("Service code is " + svc_code + " and this condition works.");
}
else
{
System.out.println("Please input a valid service code.");
}
System.out.print("That's all for now folks");
}
}
Code running normally
Code being weird
UPDATE: I'm just bad at Java and scanners.
It's not an infinite loop, or a memory leak.
It's just waiting for you to enter a non-empty string.
$ java phonebill
Please input the account number: 123
Please input service code:
string
Please input a valid service code.
That's all for now folks
(The blank lines are where I was just hitting enter. I eventually typed "string", and it stopped).
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing the Java MOOC by Helsinki University. Stuck on the following problem:
Write a program which prints the integers from 1 to a number given by the user.
Sample output
Where to? 3
1
2
3
The code below outputs the expected results but is not accepted as valid. Any suggestions or pointers are welcome, thank you!
import java.util.Scanner;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = Integer.valueOf(scanner.nextLine());
int start = 1;
while (start <= userInput) {
System.out.println(start);
start++;
}
}
}
Most likely the system that tests your program is stuffing values into standard input (System.in) with spaces, and assumes that you will read with .nextInt().
If that's not it, double check the program description; what is supposed to happen if I enter -1? 0? 1985985410395831490583440958230598? FOOBAR?
If it doesn't say, then presumably the verifier won't throw those inputs at you (if it does, file a bug with the MOOC provider, the course itself needs fixing if that is the case), but if it does, you're going to have to code those rules in, probably.
This shouldn't be it, but to exactly mirror the desired result, it's System.out.print("Where to? "); - note, no ln, and a trailing space.
You did not check if the user input is valid, I would suggest starting off with the following:
check if userInput is a valid number (includes numeric characters).
check if userInput is larger or equal to 1.
your answer is ok but can be optimized to the beginners levels if that is what your teacher is expecting because:
you can get an int directly from scanner, no need to use the wrapper class Integer.
you can use another loop ... a for loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = scanner.nextInt();
System.out.println("ok!");
for (int i = 1; i <= userInput; i++)
{
System.out.println(i);
}
}
Just try by Removing
System.out.println("Where to?");
with
System.out.print("Where to?");
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm pretty new to Java so please forgive my noob question.
How can I make the error checking logic syntactically correct and what built in methods might I use?
public static void initialize(HighScores[] scores) {
Scanner input = new Scanner(System.in);
// capture input
for (int i = 0; i < 5; i++) {
System.out.println("Enter the name for score #" + i + ": ");
String name = input.next(); // Alex
System.out.println();
System.out.println("Enter the score for score #" + i + ": ");
int score = input.nextInt();
// Error checking
// if the 'input' is NOT of type 'int'
if (score.getClass().getSimpleName() != int) {
// Ask to input a numeric value
System.out.println("Please enter a numeric value! :)");
score = input.nextInt(); // inputting a value in again
}
System.out.println();
HighScores object = new HighScores(name, score);
scores[i] = object;
}
}
What it would look like if correct:
Enter the name for score #0:
Alex
Enter the score for score #0:
s
Please enter a numeric value! :)
5
Enter the name for score #0:
John
Enter the score for score #0:
3
.... etc...
You seem to be confused,
try {
int score = input.nextInt();
} catch (InputMismatchException ime) {
ime.printStackTrace();
}
Will always be of type int (or you'll get an Exception), per the Scanner#nextInt()
Scans the next token of the input as an int.
and note that the throws says
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
It is also possible to call Scanner#hasNextInt() first,
if (input.hasNextInt()) {
int score = input.nextInt();
} else {
System.out.println(input.next() + " isn't an int");
}
First, as guys already mentioned in their comments you do not need this. If your variable is defined as int it is int and you do not have to check this.
Second, int is a primitive, so you cannot say score.getClass().
However in some cases (if you write some generic code that must care about several, yet certain types) you probably want to fix your if statement as following:
Integer score = .....
.........
if (Integer.class.equals(score.getClass())) {
// your code here
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am very new to java and i'm trying to make a basic calculator. There is another question on this but I changed the things that fixed it for him but it still doesn't work. Here's my code:
import java.util.Scanner;
class HelloWorld{
public static void main(String args[])
int num1;
int num2;
String op;
Scanner input = new Scanner(System.in);
System.out.println("Enter your first number");
num1 = input.nextInt();
System.out.println("Enter your second number");
num2 = input.nextInt();
System.out.println("Enter the operation");
op = input.nextLine();
if (op.equals("*")){
System.out.println("The answer is: " + (num2 * num1));
}
if (op.equals("/")){
System.out.println("The answer is: " + (num2 / num1));
}
if (op.equals("+")){
System.out.println("The answer is: " + (num2 + num1));
}
if (op.equals("-")){
System.out.println("The answer is: " + (num2 - num1));
}
}
}
The error says:
Enter your first number
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at HelloWorld.main(HelloWorld.java:12)
I can't seem to find whats wrong (I have its something simple that i missed)
What are you entering?
Enter your first number
10
Enter your second number
20
Enter the operation
*
The answer is: 200
I'm not sure your program would even compile the way you have it, but here's one problem:
You didn't open your main method with an open curly brace.
Change this:
public static void main(String args[])
to this:
public static void main(String args[]) {
When I tested your code, it terminated after Enter the operation. However, when I changed this line:
op = input.nextLine();
to this:
op = input.next();
It worked perfectly.
Here is an example of the console input/output:
Enter your first number
10
Enter your second number
20
Enter the operation
*
The answer is: 200
Only thing I see wrong is public **satic** void main(String args[]) Other than that it's doing what it should...
Whenever, you read any token from Scanner. You have the facility to check whether it really exists with hasNext() methods. So, you can do
For checking ints :
if(input.hasNextInt())
input.nextInt()
For checking lines :
if(input.hasNextLine())
input.nextLine()
This will get rid of the NoSuchElementException
Update:
System.out.println("Enter the operation");
op = input.next(); //changing it to next() fixed it
Output
run:
Enter your first number
2
Enter your second number
3
Enter the operation
*
The answer is: 6
BUILD SUCCESSFUL (total time: 6 seconds)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
//Program always prints the line written in the if statement.
//Also, eclipse returns an error every time I try to add an else statement
import java.util.Scanner;
import java.util.Arrays;
public class Practice {
public static void main(String[] args)
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of artists you would like to search: ");
int number = input.nextInt();
String junk = input.nextLine();
String []artist = new String[number];
for(int i=0; i < number ; i++)
{
artist[i]= input.nextLine();
}
System.out.println("Here is the list of artists you searched for: " + Arrays.toString(artist) + ". Is this correct?");
String check = input.nextLine();
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false); //this continually returns both print statements in and out of the if statement even if I input something other than yes or y and I have no idea why
{
System.out.println("Cool! Enjoy your search!"); //this always prints no matter what
}
System.out.println("Please try again! Sorry for the inconvenience!"); //won't let me add an else statement
You have a dangling ; at the end of your condition
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false) // ; was here
{
}
Remove it. This is known as an empty statement. You could rewrite it as
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false)
;
{
System.out.println("Cool! Enjoy your search!"); //this always prints no matter what
}
Since a block { /* ... */ } is valid code, it will get executed no matter what.
Your "if-then" statement is being treated as a regular end statement since there is a semicolon ";" added before the scope of your "if-then" block "{ }" begins.
Oracle shows that before you start writing the body of the statement, use brackets
int choice = input.nextInt(); //How does the steak taste?
if(choice == 1) {
String Steak = "Amazing"
System.out.println(choice);
}
The variable "choice" ends with a semicolon and is now declared with a value that the user will input. Since the if-then statement is not finished after the header, brackets containing the body with further statements (each ending with a semicolon) can be executed.
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 10 years ago.
Hey guys I was working on making a number averaging program and I wanted to insert this function that allows the user to enter the letter "y" to run again and do another computation, however, my program shows the terminated message (I'm using Eclipse) after the first computation, even though I want the user to be able to enter the input.
Here is the part of the source code that puzzles me:
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
System.out.print("This is an averaging program. How many numbers would you like to average together?");
int total=input.nextInt();
int i;
float sum=0;
for(i=0; i<total; i++)
{
System.out.print("Enter your numbers: ");
sum += input.nextFloat();
}
String y;
System.out.print("Your average is: " + sum/total + "\n");
System.out.print("Would you like to do another computation? Type y for yes, or something else for no.");
y=input.nextLine();
try this:
change
sum += input.nextFloat();
to
sum += input.nextFloat();
input.nextLine();
And
int total=input.nextInt();
to
int total=input.nextInt();
input.nextLine();
Explanation. You should manually read the newline character \n after reading a number form Scanner
Of course you should also add the relevant part of the program in a do while loop in order to execute repeatedly, but you probably know that.