I have just started my 2nd programming course at college and our first assignment is rather simple, intended to basically check our environment and to check we know how to submit assignments through the course website.
When I run the code we have been supplied with, it hangs where it is supposed to prompt for the user to enter a number, so that it can print it. I inserted a series of println statements to determine where it was hanging.
It prints TEST1, TEST2 and TEST3, but never makes it to TEST4. So there must be something wrong with the line:
number = input.nextInt();
But I can't for the life of me see what's wrong with that line. Any help would be greatly appreciated! :)
Anyway, here is the code
package rossassignment1;
import java.util.Scanner; // use the Scanner class located in the "java.util" directory
public class RossAssignment1 {
public static void main (String[] args) {
System.out.println("TEST 1");
int number;
System.out.println("TEST 2");
Scanner input = new Scanner(System.in);
System.out.println("TEST 3");
number = input.nextInt();
System.out.println("TEST 4"); // display the number with other messages
System.out.print("This program reads an integer from a keyboard,\n"
+ " and print it out on the display screen.\n"
+ "The number is: " + number + ".\n"
+ "make sure that you get the exact same output as the expected one!\n");
}
}
After the line input.nextInt() is run the program is waiting for the user (you, or whatever marking system is being used) to input an integer in the console. After you do so the program will continue to your TEST4 line.
If after entering an integer, the codes after that still don't show up, you can do this:
number = input.nextInt();
input.nextLine(); //Add this
It will clear the newline.
Alternatively, I prefer to do this:
number = Integer.parseInt(input.nextLine());
Related
I'm new to java and am trying to validate numbers being entered into the console. I want an integer, but I know if a letter is entered for example an error would occur, so I thought I'd use try & catch. This works if try and do it first time round, but I want to loop through until the user inputs a valid integer. Got this working, but when I get a valid number and print out the number I get a list of all attempts.... Hope this makes sense
import java.util.Scanner;
public class ConvertStringInt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.print("Enter a whole number: ");
try {
i = sc.nextInt();
} catch (Exception e){
System.out.println("Error");
main(args);
}
System.out.println(i);
}
}
Here is the output from the console....
Enter a whole number: a
Error
Enter a whole number: d
Error
Enter a whole number: 2.0
Error Enter a whole number: 1
1
0
0
0
Could somebody please explain this?
Thanks in advance
Neil
You are seeing outputs for each input because you call main recursively. If you immediately type a correct int, the flow is this:
main
ask for input -> int
print i (1)
But in your case the input is not an int. This is what happens: you type the first input, it fails. You do not print yet because you first call main again, asking for the next input. Only when you get a correct int you print, and then finish and allow the previous main-execution to finish by printing, which then allows the previous... and so on:
main(args)
ask for input -> a !int
main(args)
ask for input -> d !int
main(args)
ask for input -> 2.0 !int
main(args)
ask for input -> 1 int
print 1 (1)
print 0 (2.0)
print 0 (d)
print 0 (a)
Look at Ravi's answer for a proper way to repeatedly ask for input without using try/catch (which is discouraged).
You could check for integer token in loop
while (!sc.hasNextInt()) // loop until next token is integer
{
// do something or print error
System.out.println(sc.next() +"is not number");
}
i = sc.nextInt();
I am programing in java and have also very little programming experience.
I am trying to make a program there you first write in a number of integers in a scanner. In the next window you are supposed to write only one integer and that integer the program will search for and tell if it is or isn't in the "Scanner numbers"
My problem is that when i for example write 1 2 3 and in the next window write 2 it doesn't recognize there is a 2 in the scanner but if I instead write a 1 it works nicely.
Heres the code:
public class Inlämningsuppgift_kap9 {
public static void main(String[] args) {
String s1 = JOptionPane.showInputDialog("Write any number of integers!");
Scanner sc1 = new Scanner(s1);
String s2 = JOptionPane.showInputDialog(
"Chose a integer that the program will search for!"
);
int a = Integer.parseInt(s2);
while(sc1.hasNextInt()){
if(a == sc1.nextInt()){
JOptionPane.showMessageDialog(null, "The integer can be found");
System.exit(0);
}
else {
JOptionPane.showMessageDialog(null, "The integer cannot be found");
System.exit(0);
}
}
}
}
Thanks for any help!
Not going to do your homework for you, but a hint there: it is not a good idea to mix Swing UIs and a scanner that reads from stdin.
In other words: either use a graphical UI for all input/output; or just read/write from/to stdin (using out.println and that scanner code).
And then: assuming that the user first enters a string such as "1 2 3 4 5"; you need some further processing. You have to split that string (for example on spaces); and then turn each of that substrings ... into a real number. As your next step is to ask the user to input a number. And when you want to know if one number is in a list of other numbers, then you need to turn your initial string into that list of numbers!
So, you want to study javadoc for:
String.split()
Integer.parseInt()
you should not parse the input. makes it much easier to do what you want.
String s1 = JOptionPane.showInputDialog("Write any number of integers!");
String s2 = JOptionPane.showInputDialog("Chose a integer that the program will search for!");
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)==s2.charAt(0)){
JOptionPane.showMessageDialog(null, "The integer can be found");
System.exit(0);
}
}
JOptionPane.showMessageDialog(null, "The integer cannot be found");
System.exit(0);
i like this solution more since it has less code an still works fine
lets just anylyze your code and hope i'm not mistaken :) , the variables are initialized,then You start a loop with
while(sc1.hasNextInt())
it basically runs for x times where x is the number of inputs (sc1 variable's length) then you test if the number in current iteration is the number you look for. If it's you print success code and close the loop. if it isn't you print failure code and also close the loop. So when you provide 1 as input the execution is fine because 1 is the 1st element but 2 as second argument is never tested because of
System.exit(0);
in else's brackets
Im having some trouble with scanning user input in one of my first java programs. When I compile and run this, I am immediately prompted for input (i.e the command line stops and blinks). When I enter anything, the first line is printed, asking me to enter an integer. Then the second line is printed and I'm prompted to enter another value.
The output from this program is the first two values that I input. This is hard to explain, but it basically asks for 3 input values and only uses two.
import java.util.Scanner;
public class objects
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer please...");
int input = sc.nextInt();
System.out.println("Enter your name please...");
String name = sc.nextLine();
System.out.println("The read values: " + input + ", " + name);
sc.close();
}
}
Put a System.out.flush() command after your println statements if you're reading from the console directly afterward
just use this:
Scanner sc = new Scanner(System.in);
System.out.print ("Enter your name please... ");
String name = sc.nextLine();
System.out.print ("Enter an integer please... ");
int input = sc.nextInt();
System.out.println ("The read values: " + input + ", " + name);
i just moved the integer below the name and it sorta fixed it. hahaha
When you introduce a number you press enter key, nextInt() uses the number but the enter (\n) remains buffered. After this if you call again nextInt(), Java tries to convert \n into a number giving you a NumberFormatException, but if you invoke nextLine() they read the enter as empty string
Here you have a better explanation and one solution
Can't use Scanner.nextInt() and Scanner.nextLine() together
It seems this is an error to do with my installation of VirtualBox. No matter what I try, the problem persists. Even if i try to only read ONE integer, it will ask me to input two values.
Thanks for everyone who tried to help, I learned a lot just trying to debug this.
I am trying to create a program that asks a user for a sentinel value (a value to enter when they want to end the list). It then asks the user to enter numbers until they re-enter the sentinel value. It then figures out the max number in the list. I'm very new to Java, and whenever I run the program is just asks for the sentinel value then does nothing else (never pops up the second input dialog). I'm sure it's something simple that I'm doing wrong, but I can't figure it out. Thanks for any help.
import java.util.*;
import javax.swing.JOptionPane;
public class HW1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
int max;
int sentinel;
int count=0;
JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel=input.nextInt();
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
max = number;
while (number!=sentinel){
count +=1;
if (number>max)
max=number;
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
}
if (count!=0){
JOptionPane.showMessageDialog(null, "The max is:" + max);
}
}
}
You are mixing the ways to input data to your program. Let's begin:
Scanner input = new Scanner(System.in);
The line above allows you to catch data in the command line from the keyboard.
JOptionPane.showInputDialog("Please enter a sentinel value: ");
This Option Pane is showing correctly, you put a value and then nothing happens. This is because your program is waiting to input something in the command line
sentinel=input.nextInt();
When your program arrives to the line above, the input.nextInt() stops the program until you put something in the command line.
The correct way should be something like this:
sentinel = Integer.parseInt(JOptionPane.showInputDialog("Please enter a sentinel value: "));
number = Integer.parseInt(JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" value to end."));
And remove:
number = input.nextInt();
sentinel=input.nextInt();
I think the confusion is this:
the JOptionPane opens with an input dialog
when the option pane closes, whatever you put there is ignored
then the code goes to this line sentinel=input.nextInt();
which waits for input from the console (e.g. you need to go back to the console, type the number there and press enter, only then the program will advance, it will block untill you do)
I would change it to something like this:
String sentinelInput = JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel= Integer.parseInt(sentinelInput);
(repeat for all places where you expect input)
An alternative solution is
Don't use the JOptionPane, and instead just System.out.println to print the user a request for input (instead of the popup dialog). Then you can and keep the existing input.nextInt() calls to collect it.
Just note that all interaction will be in the console, without any popup dialogs (which I actually prefer in terms of user experience, and also it will be working in non GUI machines such as a linux terminal...)
This should be a very basic program but I'm new to Java. I want to be able to input multiple strings into the console using Scanner to detect them. So far I've been able to get the input part right, I wanted the program to run in such a way that the results are displayed when an empty space is entered as opposed to a string. Strangely enough I've only been able to get results when i hit return twice, however, when there are more than 4 inputs hitting return once works. My counter should count the number of "Courses" entered and display them in the results but it gives inaccurate readings.
import java.util.Scanner;
public class Saturn
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("For each course in your schedule, enter its building");
System.out.println("code [One code per line ending with an empty line]");
String input;
int counter = 0;
while (!(userInput.nextLine()).isEmpty())
{
input = userInput.nextLine();
counter++;
}
System.out.println("Your schedule consits of " + counter + " courses");
}
}
You're calling Scanner#nextLine twice - once in the while loop expression and again in the body of the loop. You can just assign input from the while loop expression. In addition you can use Scanner#hasNextLine to defend against NoSuchElementException occurring:
while (userInput.hasNextLine() &&
!(input = userInput.nextLine()).isEmpty()) {
System.out.println("Course accepted: " + input);
counter++;
}