i get Exception in thread "main" java.util.InputMismatchException when running code - java

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at PeriodicTable.elementsInt(PeriodicTable.java:54)
at PeriodicTable.findElement(PeriodicTable.java:107)
at PeriodicTable.main(PeriodicTable.java:82)
is the error i get when running this code. can anyone tell me where i went wrong? for further information, i'm trying to create a code where it pulls from the periodic table and gives you the element information according to your atomic or abbreviation.
this is the code so far:
public class PeriodicTable {
static class PeriodicElement{
int[] atomicNumber = new int[200];
double[] atomicMass = new double[200];
String[][] abbreviation = new String[200][200];
String[] theTable = new String[200];
public String[] toString(String[] arr){
String[] s = Arrays.toString(arr).split(" ");
return s;
}
public PeriodicElement(String[] pElement) {
toString(pElement);
}
}
public PeriodicTable(String[] theTable) throws IOException{
Scanner inputFile = new Scanner(new File("/Users/eddie/workspace/PeriodicTable/src/table.txt"));
while (inputFile.hasNextLine()){
int i = 0;
theTable[i] = inputFile.nextLine();
i++;
}
inputFile.close();// close the file when done
}
public static String[] readTable(String[] table)throws IOException{
PeriodicTable inputFile = new PeriodicTable(table);
return table;
}
public static int elementsInt(int found)throws IOException{
Scanner inputFile = new Scanner(new File("/Users/eddie/workspace/PeriodicTable/src/table.txt"));
while (inputFile.hasNextLine()){
int[] table = new int[200];
int i = 0;
table[i] = inputFile.nextInt();
if (found == table[i]){
System.out.println("found your number!");
return table[i];
}
else
i++;
}
inputFile.close();// close the file when done.
return found;
}
public static void main(String[] args)throws IOException { // Main Method
final int NUMBER_ELEMENTS = 0;
Scanner keyboard = new Scanner(System.in);
String yourName = "your Name";
System.out.println("Periodic Table by " + yourName);
System.out.println(" ");
System.out.println("Number of elements: " + getNumberOfElements(NUMBER_ELEMENTS));
System.out.println("1. Search atomic number ");
System.out.println("2. Search abbreviation ");
System.out.println("3. Print table ");
System.out.println("4. Exit ");
int choice = keyboard.nextInt();
switch (choice) {
case 1: System.out.print("Enter an atomic number: ");
int aNumber = keyboard.nextInt();
findElement(aNumber);
System.out.println("your atomic number is: " + findElement(aNumber) );
break;
case 2: System.out.print("Enter an abbreviation");
String abbreviation = keyboard.next();
break;
case 3: String[] everything = new String[200];
PeriodicElement print = new PeriodicElement(printTable(everything));
for(int i=0; i<everything.length ;i++){
System.out.println(print);
}
break;
case 4: break;
}
}
public static int getNumberOfElements(int num){
return num = 118;
}
public static int findElement(int e1)throws IOException {
return elementsInt(e1);
}
public static String[] printTable(String[] display)throws IOException{
PeriodicElement printAll = new PeriodicElement(printTable(display));
for(int i=0; i<display.length ;i++){
System.out.println(printAll);
}
return display;
}
}

Seems that your table.txt file contains not only numbers, that's why inputFile.nextInt() throws this exception.
From JavaDoc:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

This Exception is thrown by a Scanner when either the read character isn't what its supposed to find(in this case an integer) or the found token is out of range.
Since the largest predicted Atomic number is 172(correct me if i am wrong), it is well within the range...
Thus, most probably the exception is because you have something other than integers in your table.txt file.Maybe a string, a character, "." etc.
why don't you put it in a try block and run a counter to find the line number where this error happens and check your file.

Related

Java While loop condition isn't being exicuted

I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code:
import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
arr[0] = input.nextLine();
counter++;
do{
arr[counter] = input.nextLine();
if (input.equals("zzz")){
System.out.println("bleh");
}
counter++;
} while (!input.equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
Replace
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
}
counter++;
with
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
} else {
counter++;
}
and
while (!input.equals("zzz") && counter <= 14)
with
while (!arr[counter].equals("zzz") && counter <= 14)
Explanation: zzz is a string which you have to compare with the input string stored in arr[counter].
Also, in order to avoid NullPointerException, you should perform sort operation on the copy of the array without any null element. Given below is the complete program:
import java.util.Arrays;
import java.util.Scanner;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
do {
System.out.print("Enter item or type 'zzz' to quit: ");
arr[counter] = input.nextLine();
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
} else {
counter++;
}
} while (!"zzz".equals(arr[counter]) && counter <= 14);
arr = Arrays.copyOf(arr, counter);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
A sample run:
Enter item or type 'zzz' to quit: a
Enter item or type 'zzz' to quit: b
Enter item or type 'zzz' to quit: c
Enter item or type 'zzz' to quit: zzz
bleh
Array is [a, b, c]
import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
arr[counter] = input.nextLine();
counter++;
do{
arr[counter] = input.nextLine();
if (arr[counter].equals("zzz")){System.out.println("bleh");}
counter++;
}while (!arr[counter].equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
You meant to compare the input String, not the Scanner object. I also removed your magic number "0" index that you had , since you already set your counter to 0.
The reason your code isn't working is that input is the scanner object, and the equals method on the scanner object doesn't refer to the data being read by it. A way of doing this so that it works would be:
import java.util.*;
public class Help {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
String inputString = null;
System.out.println("Enter item or type 'zzz' to quit");
do{
inputString = input.nextLine();
arr[counter] = inputString;
if (inputString.equals("zzz")){System.out.println("bleh");}
counter++;
}while (!inputString.equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
input is a Scanner. It will never equal a String.
Try this
Scanner sc = new Scanner(System.in);
String input; // this is now a proper string to compare
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
input = sc.nextLine();
int counter = 0;
while (counter < arr.length) {
if (input.equals("zzz")) return; // check most recently entered input
arr[counter++] = input; // if not returned, store in the list and increase counter
input = sc.nextLine(); // prompt next line
}
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));

Exception while reading data from keyboard

I'm newbie in Java and I'm trying to read data from keyboard but I'm getting an exception and I don't know why and how to fix it.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Test r = new Test();
System.out.println("Type a int number : " + r.readInteger());
System.out.println("type a double number: " + r.readDouble());
}
public int readInteger() {
Scanner input = new Scanner(System.in);
int val = 0;
while(true) {
if(input.hasNextInt()) {
val = input.nextInt();
input.nextLine();
break;
}
else {
System.out.println("Invalid data type.");
input.nextLine();
}
}
input.close();
return val;
}
double readDouble() {
Scanner input = new Scanner(System.in);
double val = 0;
while(true) {
if(input.hasNextDouble()) {
val = input.nextDouble();
input.nextLine();
break;
}
else {
System.out.println("Invalid data type.");
input.nextLine();
}
}
input.close();
return val;
}
}
The excpetion:
[roger#archroger ~]$ java Test
3
Type a int number : 3
Invalid data type.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Test.readDouble(Test.java:44)
at Test.main(Test.java:8)
Don't close the scanner when it's input stream is System.in. This will close the standard input as well and statements like scanner.nextLine() will throw a NoSuchElementException when you do not check if the line is present. You check with scanner.hasNextInt() if another integer token is available and then try to get another line with scanner.getNextLine() without testing if this line exists at all. Use scanner.hasNextLine().

Ending while loop in Java

I'm making a program for my assignment. This is not the whole program but it's just a part of it.
I want from the user to enter some integer values to be stored in "items" arrays. When the user input "stop" the loop should close and here is the problem.. when I write stop the program stops and give me some errors.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=0, lines=1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true){
i=i+1;
if ("stop".equals(scan.nextLine()))
break;
else
items[i] = scan.nextInt();
}
}
There are certain mistakes in your code. It's more better if you could just add the error.
Try this code.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0, lines = 1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true){
String InputTxt = scan.nextLine();
if (InputTxt.equals("stop"))
break;
else{
try{
items[i] = Integer.parseInt(InputTxt);
i++;
}catch(Exception e){
System.out.println("Please enter a number");
}
}
}
}
On top of other answers, I would like to advise you to change the looping from
while(true)
to
//first you need to remove the local variable i
for(int i = 0; i < items.length; ++i)
Using this approach will help you to avoid IndexOutOfBoundsException when users key in more than 100 integer values.
your problem is this line : items[i] = scan.nextInt(); because you are trying to get integer while the input is string stop
EDIT
one possible solution is that you get your data as string and check if it is stop or not and if not then try to parse it to integer like code bellow:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=0, lines=1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true)
{
i=i+1;
String str = scan.nextLine()
if ("stop".equals(str))
break;
else
{
items[i] = Integer.parseInt(str)
}
}
}

java - specifiing Int as input with Scanner

i have a function to read user input. it takes a parameter to choose reading Ints or Strings. When i try to make sure that it reads only Ints with while(!sc.hasNextInt()) it works, but only when i step it in debug mode. whenever i try to use it while program is running it throws an exception regardless of input being a number or characters.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Databaz.ctecka(Databaz.java:14)
at Databaz.main(Databaz.java:38)
this points me to sc.next(); line in my function:
static String ctecka(int volba)
{
Scanner sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next(); //this is where exception points
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
sc.close();
return vystup;
}
function is being used from code:
int volba = Integer.parseInt(ctecka(1)); //it returns String so i parse it
That happens because you close your scanner sc.close(); which closes your inputStream then you try to access it again (have a look here), so to solve your problem, generalize your scanner variable, and then close it only when you finish all the ctecka() method calls, like the following:
Scanner sc;
private void some_method(){
int volba1 = Integer.parseInt(ctecka(1));
int volba2 = Integer.parseInt(ctecka(1));
int volba3 = Integer.parseInt(ctecka(2));
int volba4 = Integer.parseInt(ctecka(3));
sc.close();
}
String ctecka(int volba){
sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next();
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
return vystup;
}

how to take user input in Array using java?

how to take user input in Array using Java?
i.e we are not initializing it by ourself in our program but the user is going to give its value..
please guide!!
Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
See also:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
import java.util.Scanner;
class bigest {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("how many number you want to put in the pot?");
int num = input.nextInt();
int numbers[] = new int[num];
for (int i = 0; i < num; i++) {
System.out.println ("number" + i + ":");
numbers[i] = input.nextInt();
}
for (int temp : numbers){
System.out.print (temp + "\t");
}
input.close();
}
}
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.
Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.
If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.
Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();

Categories

Resources