So I want to read a file, that contains numbers separated by spaces. For example, the file "try.txt" content is:
1 2 3
4 5 6
7 8 9
I know how to read this numbers and store them in an array with a Scanner, and two nested for loops.Ignore any possible sintax errors here. It would look like:
int i,j;
Scanner sc
for(i=0;i<array.length;i++){
for(j=0;j<array[i].length;j++){
array[i][j]=sc.nextInt();
}
}
So my question is, how can I check that what I am reading is actually an integer? What happens if nextInt() finds a letter, or another ASCII symbol?
Thank you.
Try this code
if (obj instanceof Integer)
{
// is a integer
}
else
{
// is not
}
At the end, I solved this problem using InputMissmatchException. Here is an example:
Scanner sc = new Scanner(System.in);
try{
int a = sc.nextInt();
}catch(java.util.InputMismatchException e) {
System.out.println("Invalid file content");
}
Related
This question already has answers here:
Scanner only reads first word instead of line
(5 answers)
Closed 2 years ago.
The code works for the most part, but if I type "No way" it still stops the loop. Should I set it up a different way or use a length function ? Everything I've searched on breaking a loop used integers.
See the code below:
import java.util.Scanner;
public class CarryOn {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.next());
if (answer.equalsIgnoreCase("no")){
break;
}
}
}
}
Using .next in this case only stores "no" in "no way". Use .nextLine instead:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.nextLine());
if (answer.equalsIgnoreCase("no")){
break;
}
}
Output:
Shall we carry on?
no way
Shall we carry on?
no
Check this post for more information.
scanner.next()
only reads a single token. No way is two tokens: No and way.
Use scanner.nextLine() instead, if you want to read the whole line.
This question already has answers here:
What is the use of System.in.read()?
(10 answers)
Closed 4 years ago.
I am really new to Java, and I was following a book tutorial on how to read user input. Their code was...
class Example {
public static void main(String args[]) throws java.io.IOException {
// System.out.println()
char ch;
System.out.print("Press a key followed by ENTER: ");
ch = (char) System.in.read();
System.out.println("Your key is: " + ch);
}
}
I tried to experiment and read user input as an integer like this...
class Example {
public static void main(String args[]) throws java.io.IOException {
int foo;
System.out.print("Enter a number: ");
foo = (int) System.in.read();
System.out.print("Your number was: " + foo);
}
}
However, upon typing for example number 12, I get the output as 49. Why is that? How come the book tutorial worked then?
EDIT: When I type in 'w' in my program, it still prints out 119. Surely I thought the throws thing was dealing with that? Or is it not?
And what is a Scanner (just saw it in the comments)?
System.in.read() Reads the next byte of data from the input stream.
So you are just reading 1 from input and you are printing ASCII code of 1 which is 49. If you want to show the character you should read it as char or convert it:
System.out.print("Your number was: " + (char) foo)
Answering Your Question
However, upon typing for example number 12, I get the output as 49.Why
is that?
The reason you got 49, is because you only read the first char of the input (the program only read the '1' digit). The ASCII value of 1, surprisingly equals to 49.
Better Approach
I would suggest to use the Scanner object to read inputs from System.in, like this.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
This approach will populate the 'sentence' String, with the entire line entered in the console.
If you need a number and not a String, parse that string to an int using Integer.valueOf(yourString);
I'm kinda new to Java so I'm looking for an help to do this.
As the title says, I'm trying to write a program that checks if a number given by the user from console is inside a text file with one number for each line or not.
I am using the Scanner class to check every line, but I am having problems with what condition the if statement should have when the number is found inside the file.
I wrote down this part code (I'm not even sure if it's correct itself, so correct me if I'm wrong):
int lines = 0;
while (filescanner.hasNextLine()) {
String line = filescanner.nextLine();
lines++;
if(conditon here) {
System.out.println("I found the number on line " + lines);
}
}
Thanks in advance.
Since you are getting the input number from Scanner keyboard, you can get its value like this:
String input = keyboard.next();
Then your if condition can be if(line.contains(input))
You need to convert the line to an integer and then test it. If it is not an integer the parseInt method throws an exception.
try {
int n = Integer.parseInt(line);
if (n == number) {
// found it
}
} catch (NumberFormatException e) {
// Not a number
}
This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?
That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.
I am writing a program in which a user inputs an unknown amount of numbers on a single line, like: 2 6 3 9 12.
I have to insert those numbers in a queue. However the loop doesn't end until I enter a non-integer value. I found one solution online which was to use .useDelimiter(" *"). This works except for when I enter a two digit integer: it splits it into two separate numbers. Is there a way to end this loop without having to enter a non integer value?
Scanner in = new Scanner(System.in)
while(in.hasNextInt())
{
myQueue.insert(in.nextInt());
}
Since the numbers are on one line, you could read the line and construct a Scanner on that text. Something like,
System.out.println("Please enter a line of integer values: ");
Scanner in = new Scanner(System.in);
if (in.hasNextLine())
{
String line = in.nextLine();
Scanner scan = new Scanner(line);
while (scan.hasNextInt()) {
myQueue.insert(scan.nextInt());
}
}
Here's one way:
Scanner in = new Scanner(System.in);
while(in.hasNextLine())
{
try {
myQueue.insert(Integer.parseInt(in.nextLine()));
}
catch (NumberFormatException ex) {
break;
}
}
I think you are on the right track. There are a number of ways to do this. You could modify your current code by adding the line:
in.useDelimiter(System.getProperty("line.separator"));
This will delimit the iterator to a new line correctly on any platform.