Exception in thread "main" java.util.InputMismatchException
i need help with one exercise in java, i'm stuck on this error 2 hours maybe. Any help would be great.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
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 prodavnica.Prodavnica.main(Prodavnica.java:60)
Java Result: 1
package prodavnica;
public class Proizvod {
private String ime_proizvod;
private static int cena;
public Proizvod(String ime_proizvod, int cena) {
this.ime_proizvod = ime_proizvod;
this.cena=cena;
}
public String getIme_proizvod() {
return ime_proizvod;
}
public void setIme_proizvod(String ime_proizvod) {
this.ime_proizvod = ime_proizvod;
}
public static int getCena() {
return cena;
}
public static void setCena(int cena) {
Proizvod.cena = cena;
}
public void pecatiPodatoci(){
System.out.println("Ime: "+ime_proizvod+" Cena: "+cena);
}
}
AND:
package prodavnica;
import java.util.Scanner;
public class Prodavnica {
private String ime_prodavnica;
private Proizvod proizvodi[]=new Proizvod[20];
public Prodavnica(String ime_prodavnica) {
this.ime_prodavnica = ime_prodavnica;
}
int br=0;
public void dodadiProizvod(Proizvod p){
proizvodi[br]=p;
br++;
}
public Proizvod najskapProizvod(){
Proizvod max=proizvodi[0];
for(int r=0;r<proizvodi.length;r++){
if(max.getCena()<proizvodi[r+1].getCena()){
max=proizvodi[r+1];
}
}
return max;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Prodavnica pro1=new Prodavnica("Tinex");
int n;
System.out.println("Vnesete kolku proizvodi ke stavite: ");
n=input.nextInt();
String imer = input.nextLine();
int cenar = input.nextInt();
pro1.dodadiProizvod(new Proizvod(imer, cenar));
System.out.println("Ime-pr: "+pro1.proizvodi[0].getIme_proizvod()+" Cena= "+pro1.proizvodi[0].getCena());
}
}
I can't enter The string "imer" or the int "cenar" on the variable "proizvodi" from the class Proizvod.
Any Help? why i get this error? Thanks!
Solution 1:
This Exception 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.
String imer = input.next();// Use for String Input
input.nextLine();//Use for next line of input
int cenar = input.nextInt();
Solution 2:
You need to put an int in before you get to imer or cenar:
n=input.nextInt();
This line doesn't appear to be doing anything, either remove it, or put a number in before you put your imer or cenar values in.