Runtime error with scanners - java

Why does my code have a runtime error?(java)
import java.util.Scanner;
public class StudentID
{
static int gradeLevel;
static int id;
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("---Student ID---");
System.out.print("Enter your first name: ");
String firstName = keyboard.next();
System.out.print("\nEnter your last name: ");
String lastName = keyboard.next();
System.out.print("\nEnter your grade level: ");
gradeLevel = keyboard.nextInt();
System.out.print("\nEnter your id: ");
id = keyboard.nextInt();
System.out.print("\nThe text for your student id is:");
String result = getIDText(firstName, lastName, gradeLevel, id);
System.out.print(result);
}
public static String getIDText(
String firstName,
String lastName,
int gradeLevel,
int id)
{
String result =
"\n\nName: " + lastName + ", " + firstName +
"\nGrade: " + gradeLevel +
"\nID: " + id;
return result;
}
}
I can enter my my data just fine, but after type in my ID and press enter, my program crashes saying i have an error at id = keyboard.nextInt();
My error is this:
java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at
java.util.Scanner.nextInt(Scanner.java:2117) at
java.util.Scanner.nextInt(Scanner.java:2076) at
StudentID.main(StudentID.java:18)

Code works fine in case you print integer value for ID. If you print String value, like e.g. aaa, you get this java.util.InputMismatchException. If you would like to check incorrect data, you have to read always String an then in the code manually convert it.
P.S. You should close Scanner isntance somehwere: keyboard.close()

There are 2 ways to resolve this:
1. use keyboard.nextLine() instead of keyboard.next if your string input has spaces in between as the input is considered only till it encounters first space.
2. if you want to use keyboard.next() only, the check whether the input is int when you want for e.g:
if(keyboard.hasNextInt())
{
id = keyboard.nextInt();
}

Related

how can i call a variable from another function/method?

I have an assignment to do a CV that users will input on and display it. However, I don't know how I can call a variable to another to function to print/display.
Here is the code:
import java.util.Scanner;
public class curriculumVitae1{
public static String firstName;
public static String middleName, lastName, birthDate, maritalStatus, homeAddress, provincialAddress, mobileNumber, anotherMobile, landlineNumber, anotherLandline, primaryYears;
private static void main (String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nCurriculum Vitae");
System.out.print("\nInput your last name: ");
String lastName;
lastName = input.nextLine();
System.out.print("\nInput your first name: ");
String firstName;
firstName = input.nextLine();
System.out.print("\nInput your middle name: ");
String middleName;
middleName = input.nextLine();
System.out.print("\nInput your birthdate: ");
String birthDate;
birthDate = input.nextLine();
System.out.print("\nInput your marital status (Married, Widowed, Separated, Divorced, Single) : ");
String maritalStatus;
maritalStatus = input.nextLine();
System.out.print("\nInput your home address: ");
String homeAddress;
homeAddress = input.nextLine();
curriculumVitae1.cv();
}
private static void provincial(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nDo you have a provincial address? Enter Y if yes, and N if no: ");
char provincialQuestion;
provincialQuestion = input.nextLine().charAt(0);
if (provincialQuestion=='Y'){
System.out.print("\nInput your provincial address: ");
String provincialAddress;
provincialAddress = input.nextLine();
}
else if(provincialQuestion=='N'){
}
}
private static void mobile(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nContact Details ");
System.out.print("\nInput your mobile number: ");
String mobileNumber;
mobileNumber = input.nextLine();
System.out.print("\nDo you have another mobile number? Enter Y if yes, and N if no: ");
char mobileQuestion;
mobileQuestion = input.nextLine().charAt(0);
if (mobileQuestion=='Y'){
System.out.print("\nInput another mobile number: ");
String anotherMobile;
anotherMobile = input.nextLine();
}
else if(mobileQuestion=='N'){
}
}
private static void landline(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nInput your landline number: ");
String landlineNumber;
landlineNumber = input.nextLine();
System.out.print("\nDo you have another landline number? Enter Y if yes, and N if no: ");
char landlineQuestion;
landlineQuestion = input.nextLine().charAt(0);
if (landlineQuestion=='Y'){
System.out.print("\nInput another mobile number: ");
String anotherLandline;
anotherLandline = input.nextLine();
}
else if (landlineQuestion=='N'){
}
}
private static String email(){
Scanner input = new Scanner(System.in);
System.out.print("\nInput your email address: ");
String emailAddress;
emailAddress = input.nextLine();
return emailAddress;
}
private static String tertiary(){
Scanner input = new Scanner(System.in);
System.out.print("\nEducation History ");
System.out.print("\nTertiary Education ");
System.out.print("\nInput your tertiary education course: ");
String tertiaryCourse;
tertiaryCourse = input.nextLine();
System.out.print("\nInput your tertiary education school: ");
String tertiarySchool;
tertiarySchool = input.nextLine();
System.out.print("\nInput your tertiary education inclusive years (xxxx-xxxx): ");
String tertiaryYears;
tertiaryYears = input.nextLine();
System.out.print("\nDo you have any honors/achivements received during your tertiary education? Enter Y if yes, and N if no: ");
char tertiaryQuestion;
tertiaryQuestion = input.nextLine().charAt(0);
if (tertiaryQuestion=='Y'){
System.out.print("\nInput your honor/s or achivement/s:");
String tertiaryAchievements;
tertiaryAchievements = input.nextLine();
return tertiaryAchievements;
}
else if (tertiaryQuestion=='N'){
return "------";
}
}
private static void secondary(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nSecondary Education ");
System.out.print("\nInput your secondary education school: ");
String secondarySchool;
secondarySchool = input.nextLine();
System.out.print("\nInput your secondary education inclusive years (xxxx-xxxx): ");
String secondaryYears;
secondaryYears = input.nextLine();
System.out.print("\nDo you have any honors/achivements received during your secondary education? Enter Y if yes, and N if no: ");
char secondaryQuestion;
secondaryQuestion = input.nextLine().charAt(0);
if (secondaryQuestion=='Y'){
System.out.print("\nInput your honor/s or achivement/s:");
String secondaryAchievements;
secondaryAchievements = input.nextLine();
}
else if (secondaryQuestion=='N'){
}
}
public static void primary(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nPrimary Education ");
System.out.print("\nInput your primary education school: ");
String primarySchool;
primarySchool = input.nextLine();
System.out.print("\nInput your primary education inclusive years (xxxx-xxxx): ");
String primaryYears;
primaryYears = input.nextLine();
System.out.print("\nDo you have any honors/achivements received during your primary education? Enter Y if yes, and N if no: ");
char primaryQuestion;
primaryQuestion = input.nextLine().charAt(0);
if (primaryQuestion=='Y'){
System.out.print("\nInput your honor/s or achivement/s:");
String primaryAchievements;
primaryAchievements = input.nextLine();
}
else{
System.out.print("------");
}
}
public static void cv(String args[]){
System.out.println(" Curriculum Vitae");
System.out.print("\nName:" + firstName + " " + middleName + " "+ lastName);
System.out.print("\nBirthdate:" + birthDate);
System.out.print("\nMarital Status:" + maritalStatus);
System.out.print("\nHome Address:" + homeAddress);
System.out.print("\nProvincial Address:" + provincialAddress);
System.out.print("\nMobile Number:" + mobileNumber );
System.out.print("\nAnother Mobile Number:" + anotherMobile);
System.out.print("\nLandline:" + landlineNumber);
System.out.print("\nYear: " + primaryYears);
}
}
However, I always get the error that
C:\Users\BEST\Desktop\wew>javac curriculumVitae1.java
curriculumVitae1.java:33: error: method cv in class curriculumVitae1 cannot be applied to given types;
curriculumVitae1.cv();
^
required: String[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Please help me on how can I print out another variable from other function. Or some alternatives that I can do.
Your methods expect an (String[] args) however since you don't use them I would remove them. Try
public static void cv() {
The error details highlight that you're calling the method without providing the required parameters in the method signature public static void cv(String args[]):
The required part tells you what types of arguments are expected, here String[] and the found part tells you what it saw instead, here it saw you passed no arguments.
The reason tells you that the actual (what you provided) number of arguments differs from the formal (what the method signature defines) number of arguments expected, i.e. not enough or too many arguments were provided.
You can also get this from the original error message:
error: method cv in class curriculumVitae1 cannot be applied to given types;
curriculumVitae1.cv();
It doesn't explicitly state it, but from the line of code shown below you can see that the "given types" are nothing because the method was called with no arguments—nothing inside the parentheses.
Like Peter Lawrey said, you can just remove the String args[] from your method signature since you don't use it.
Hope this helps you understand error messages and what they're telling you a little better!
Make the following changes to your program:
Change the access specifier of main() method from private to public. Otherwise the code will throw the error - Does not contain a main method
Since you have firstName, middleName, lastName, birthDate etc. declared as static variables do not declare them as local variables in main method. Assign the values to the already declared static variables in the main() method as shown below:
public static void main (String args[]){
Scanner input = new Scanner(System.in);
System.out.print("\nCurriculum Vitae");
System.out.print("\nInput your last name: ");
//String lastName;
lastName = input.nextLine();
System.out.print("\nInput your first name: ");
//String firstName;
firstName = input.nextLine();
System.out.print("\nInput your middle name: ");
//String middleName;
middleName = input.nextLine();
System.out.print("\nInput your birthdate: ");
//String birthDate;
birthDate = input.nextLine();
System.out.print("\nInput your marital status (Married, Widowed, Separated,
Divorced, Single) : ");
//String maritalStatus;
maritalStatus = input.nextLine();
System.out.print("\nInput your home address: ");
//String homeAddress;
homeAddress = input.nextLine();
//System.out.println();
cv();
}
Remove the String[] args argument from cv() method as it is not being used.
Since cv() is a static method, it can be called directly from the main().
Return the string type varaible from tertiary() method as it is giving a compile error. You can do so by declaring tertiaryAchievements variable outside the if-else block and then returning it as shown below:
String tertiaryAchievements="";
if (tertiaryQuestion=='Y')

Exception in thread "main" java.util.InputMissMatchException

I am a beginner in java programming. I have a question on whats going on, whenever i try to compile it, it keeps giving me error like this :
Exception in thread "main" java.util.InputMissMatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at MoreUserInputOfData.main(MoreUserInputOfData.java:28)
if someone would like to help me clean up my code as well, it wouldn't hurt..
import java.util.Scanner;
public class MoreUserInputOfData{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String firstName, lastName, loginName;
int grade, studentID;
double gpa;
System.out.println("Please enter the following information, so i cann sell it for a profit!");
System.out.print("First name: ");
firstName = keyboard.next();
System.out.print("Last name: ");
lastName = keyboard.next();
System.out.print("Grade (9-12): ");
grade = keyboard.nextInt();
System.out.print("Student ID: ");
studentID = keyboard.nextInt();
System.out.print("Login: ");
loginName = keyboard.next();
System.out.print("GPA (0.0-4.0): ");
gpa = keyboard.nextDouble();
System.out.println("");
System.out.println("Your information:");
System.out.println("Login:"+loginName);
System.out.println("ID: "+studentID);
System.out.println("Name: "+lastName+", "+firstName);
System.out.println("GPA: "+gpa);
System.out.println("Grade: "+grade);
}
}
Look at your code at line 28. When you input data, maybe you input the wrong type that the variable can't accept. For example: nextDouble require dot like 0.3 but you input 3.
For nextDouble : InputMismatchException -- if the next token does not match the Float regular expression, or is out of range
you should write it by prevent exception like:
// find the next double token and print it
// loop for the whole scanner
while (keyboard.hasNext()) {
...
// if the next is a double, print found and the double
System.out.print("GPA (0.0-4.0): ");
if (keyboard.hasNextDouble()) {
gpa = keyboard.nextDouble();
} else {
System.out.print("Not double");
}
...
}

Repeat a method from "if" until a proper value to be returned is entered

I'm trying to learn the basics of Java when I have nothing to do at work, and I wanted to play around with input. This is what I have now:
import java.util.Scanner;
public class Input {
private static Scanner input;
public static void main(String [] args){
String name = (askName());
double age = (askAge());
System.out.println("Your name is " + name + " and your age is " + age);
}
static String askName(){
System.out.print("What is your name?");
input = new Scanner(System.in);
//listens for strings
String name = input.next();
return name;
}
static double askAge(){
System.out.print("What is your age?");
input = new Scanner(System.in);
//listens for doubles
double age = input.nextDouble();
if (input.hasNextDouble()){
return age;
} else {
System.out.println("Please insert a number:");
askAge();}
}
}
And this is what I get:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type double
at Input.askAge(Input.java:16)
at Input.main(Input.java:6)
What do I do to force the user to enter an integer (that is, how do I make the method repeat itself until it gets an int that it can return?)
Return the value of the recursive call:
System.out.println("Please insert a number:");
return askAge();
However: it would be better to use a loop rather than recursion here, since you could (eventually) get a StackOverflowError if you keep on entering an invalid value.
If condition is used for decision making and not for looping.
Use a while loop , Break the loop when u get the correct value.
I am wiring a sudo code.
while(true){
if (input.hasNextDouble()){
//Assign value to a variable ;
//Break loop
} else {
//Re ask question
System.out.println("Please insert a number:");
}
}
Example link for your help.
The exception you are getting is because you are not returning any value from askAge() in else part.
I would rather do it this way:
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String name = getString(sc, "What is your name? ");
int age = getInt(sc, "What is your age? ");
System.out.println("Your name is " + name + " and your age is " + age);
}
/* You increase the performance when using an already existing single
scanner multiple times for different reasons (to get a name, first name,
second name, age, etc.), instead of making a new Scanner each time */
public static String getString(Scanner sc, String message) {
System.out.print(message);
return sc.nextLine();
}
public static int getInt(Scanner sc, String message) {
System.out.print(message);
if (sc.hasNextInt()) {
return sc.nextInt();
} else {
sc.next(); // required to skip the current input
return getInt(sc, "Please insert a number: ");
}
}
Please change your mathod like,
static double askAge(){
System.out.print("What is your age?");
input = new Scanner(System.in);
//listens for doubles
if (input.hasNextDouble()){
return input.nextDouble();
} else {
System.out.println("Please insert a number:");
}
return askAge();
}}

Number format exception in java, taking wrong input

When using the code
else if(command.equalsIgnoreCase("add")) {
System.out.println("Enter the Student's Name: ");
String name = input.nextLine();
System.out.println("Enter the Student's Number: ");
String studNum = input.nextLine();
System.out.println("Enter the Student's Address: ");
String address = input.nextLine();
langara.addStudent(name, address, studNum);
System.out.println("A Student added to the College Directory");
}
If the user enters add, it's suppose to go through the above procedure, In the collage class (langara) there is a "addStudent" method :
public void addStudent(String name, String address, String iD) {
Student firstYear = new Student(name, address, iD);
collegeStudents.add(firstYear);
}
And this creates a student object of the student class using the constructor:
public Student(String name, String address, String iD) {
long actualId = Long.parseLong(iD);
studentName = name;
studentID = actualId;
studentAddress = new Address(address);
numberOfQuizzes = 0;
scoreTotal = 0;
}
I'm getting the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Abernathy, C."
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at Student.<init>(Student.java:48)
at College.addStudent(College.java:33)
at CollegeTester.main(CollegeTester.java:53)
It's as if it's trying to convert the Students name to long, but it's supposed to convert the student ID to long..
This is where scanner is created, college is created, and command is initialized:
Scanner input = new Scanner(System.in);
College langara = new College();
String command = "";
System.out.print("College Directory Commands:\n" +
"add - Add a new Student\n" +
"find - Find a Student\n" +
"addQuiz - Add a quiz score for a student\n" +
"findHighest - Find a student with the highest quiz score\n" +
"delete - Delete a Student\n" +
"quit - Quit\n");
command = input.nextLine();
The input is being read from a input.txt file, with each input on it's own line.
The input at the beginning of the file for this command is:
add
Abernathy, C.
10010123
100, West 49 Ave, Vancouver, BC, V7X2K6
What is going wrong here?
It looks right now, but I would swear that when I first looked at this (and copy/pasted your code) that the call to langara.addStudent had the parameters as name, studNum, address. I put this class together with your input file and it appears to work fine:
import java.io.FileInputStream;
import java.util.Scanner;
public class StackOverflow_32895589 {
public static class Student
{
String studentName;
long studentID;
String studentAddress;
long numberOfQuizzes;
long scoreTotal;
public Student(String name, String address, String iD)
{
studentName = name;
studentID = Long.parseLong(iD);
studentAddress = address;
numberOfQuizzes = 0;
scoreTotal = 0;
}
}
public static void main(String[] args)
{
try{
System.setIn(new FileInputStream("c:\\temp\\input.txt"));
}
catch (Exception e)
{
throw new RuntimeException(e);
}
Scanner input = new Scanner(System.in);
String command = input.nextLine();
if (command.equals("add"))
{
System.out.println("Enter the Student's Name:");
String name = input.nextLine();
System.out.println("Enter the Student's Number:");
String studNum = input.nextLine();
System.out.println("Enter the Student's Address:");
String address = input.nextLine();
System.out.println("[" + name + "][" + studNum + "][" + address + "]");
input.close();
addStudent(name, address, studNum);
}
}
public static void addStudent(String name, String address, String iD)
{
Student firstYear = new Student(name, address, iD);
}
}

having trouble compling this code for a starwars name generator

I need to use first three letters of actual first name + first two letters of actual last name, and first two letters of mother's maiden name + first three letters of birth city. I also need to have the first letter be capitalized. Using toUpperCase() and toLowerCase(). Thanks!
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
System.out.printf("Enter your first name: ");
/* This should be string as your gettting name*/
String firstname = input.nextLine();
firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1);
/* Don't need new variable use same and that also should be string. */
System.out.printf("Enter your last name: ");
String lastname = input.nextLine();
lastname = lastname.substring(0,2). toUpperCase() + lastname.substring(1);
System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,2);
System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,3);
String StarWarsName = firstname+lastname+mothersname+cityname;
System.out.println("May the force be with you, " + StarWarsName );
}
}
//* Updated code
import java.util.Locale;
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.printf("Enter your first name: ");
String firstname = input.nextLine();
firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1).toLowerCase();
System.out.printf("Enter your last name: ");
String lastname = input.nextLine();
lastname = lastname.substring(0,1). toUpperCase() + lastname.substring(1).toLowerCase();
System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,2);
System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,3);
String StarWarsName = firstname+lastname+" "+mothersname+cityname;
System.out.println("May the force be with you, " + StarWarsName );
}
}
Corrected the code and explained the changes in comments. Go through comments also. Don't just copy this code.
import java.util.Scanner;
public class test1
{
public static void main(String[] args)
{
Scanner input = new Scanner();
System.out.printf("Enter your first name: ");
/* This should be string as your gettting name*/
String firstname = input.nextLine();
/* Don't need new variable use same and that also should be string. */
firstname = firstname.substring(0,1);
System.out.printf("Enter your last name: ");
String lastname = input.nextLine();
lastname = lastname.substring(0,2);
System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,1);
System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,2);
String StarWarsName = ( "firstname" + "lastname " + "mothersname " + "cityname");
System.out.println("May the force be with you, " + StarWarsName );
}
}
firstname cannot be resolved to a variable
You didn't declare firstname. Not only firstname you didn't declare lastname, mothersname, cityname. So you should declare all. Those should be String.
You didn't create Scanner object. Create Scanner class object.
Scanner input = new Scanner(System.in);
Next change. You declared cityname as two times and as inttype. But nextLine() returns String not int.
String cityname = input.nextLine();//returns String, not int
cityname = city.substring(0,3);//returns the first 3 characters as String, not int
String#substring() returns String not int. So check the entire code.
Change
String StarWarsName = ( "firstname" + "lastname " + "mothersname " + "cityname");
to
String StarWarsName = firstname+lastname+" "+mothersname+cityname;
All these are variables not values. So don't put in double quotes.
Edit: Capitalize the first letter of firstname
firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1).toLowerCase();

Categories