Integer.parseInt(in.readLine()) - "null"
I just realized that if I don't enter a value in the following:
System.out.print("Enter the column you'd like to mark in: ");
int col = Integer.parseInt(in.readLine());I get this error:
Enter the column you'd like to mark in:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:476)
at la5.TicTacToeDriver.main(TicTacToeDriver.java:37)
Exception in thread "main" Is there a way to prevent this error and prompt the user for a proper input (any integer will work).
Enclose the parse attempt in a try/catch block.
Similar Messages
-
Integer.parseInt() error
I am writing an applet that reads a file containing groups of 5 lines of which the first 4 hold a number. Then these values are used to draw circles. When I compile, I get this error message: "incompatible types
found: int, required: java.lang.Integer, ia = Integer.parseInt(a)".
Suggestions?
Thanks!
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.awt.geom.*;
public class Section2 extends Applet {
TextField tekst;
public void init() {
resize(400,400);
tekst = new TextField(20);
add(tekst);
public void paint(Graphics g) {
try {
String a, b, c, d, e;
Integer ia, ib, ic, id;
File inputFile = new File(tekst.getText());
FileReader in = new FileReader(inputFile);
BufferedReader BR = new BufferedReader(in);
while (e != null){
a = BR.readLine();
b = BR.readLine();
c = BR.readLine();
d = BR.readLine();
e = BR.readLine();
ia = Integer.parseInt(a);
ib = Integer.parseInt(b);
ic = Integer.parseInt(c);
id = Integer.parseInt(d);
Graphics2D g2d = (Graphics2D)g;
Ellipse2D.Double circle = new Ellipse2D.Double(ia, ib, ic, id);
g2d.setPaint(Color.blue);
g2d.draw(circle);
in.close();
catch (IOException e) {}Ok everything works! I still have some questions:
*** Can anyone tell me why I get this:
--------------------Configuration: Section2 - j2sdk1.4.0_01 <Default>--------------------
Note: C:\Program Files\Xinox Software\JCreator LE\MyProjects\Section textfield\Section2.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
Process completed.
*** Is there a way to go from string to double in one step?
This is the code:
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.awt.geom.*;
public class Section2 extends Applet {
TextField tekst;
Button knop;
public void init() {
resize(400,400);
tekst = new TextField(20);
add(tekst);
knop = new Button("teken");
add(knop);
public boolean action (Event e, Object o){
if(e.target.equals(knop)){
repaint();
return true;
public void paint(Graphics g) {
try {
String a, b, c, d, e;
Integer ia, ib, ic, id;
File inputFile = new File(tekst.getText());
FileReader in = new FileReader(inputFile);
BufferedReader BR = new BufferedReader(in);
e = "start";
if (tekst.getText() != null){
while (e != null){
a = BR.readLine();
b = BR.readLine();
c = BR.readLine();
d = BR.readLine();
e = BR.readLine();
ia = Integer.valueOf(a);
ib = Integer.valueOf(b);
ic = Integer.valueOf(c);
id = Integer.valueOf(d);
Graphics2D g2d = (Graphics2D)g;
Ellipse2D.Double circle = new Ellipse2D.Double(ia.doubleValue(), ib.doubleValue(), ic.doubleValue(), id.doubleValue());
g2d.setPaint(Color.blue);
g2d.draw(circle);
in.close();
catch (IOException e) {} -
Something's wrong with my Integer.parseInt...
hi...I think something's wrong with my code.
when i don't add the loop for(int s = h; s > 0; s--) { }, it's correct, but when i do, it shows:
java.lang.NumberFormatException: 27.0
at java.lang.Integer.parseInt(Integer.java:414)
at java.lang.Integer.parseInt(Integer.java:454)
at chiayaochien3.evaluate.find(evaluate.java:55)
at chiayaochien3.evaluate.operate(evaluate.java:48)
at chiayaochien3.Main.main(Main.java:10)
Exception in thread "main"
(But i am sure the things in Integer.parseInt is String...)
public class Main
public static void main(String[] args)
String[] data = {"3","+","12","*","27","/","1","-","6", "+", "222"};
String[] operStack = null;
String[] numStack = null;
myStack num1 = new myStack();
myStack num2 = new myStack();
myStack oper1 = new myStack();
myStack oper2 = new myStack();
int calculateNum1 = 0;
int calculateNum2 = 0;
String calculate1 = null;
String calculate2= null;
String oper = null;
double resultNum = 0;
double result = 0;
int operSize = 0;
int numSize = 0;
int h = 0;
for(int i = 0; i < data.length; i++) {
String f = data;
if(f.compareTo("+") == 0)
oper1.push(f);
else if(f.compareTo("-") == 0)
oper1.push(f);
else if(f.compareTo("*") == 0) {
oper1.push(f);
h++;
else if(f.compareTo("/") == 0){
oper1.push(f);
h++;
else if(f.compareTo("^") == 0){
oper1.push(f);
h++;
else
num1.push(f);
}//end of for
for(int s = h; s > 0; s--){
while(!oper1.isEmpty()) {
calculateNum1 = Integer.parseInt((String)num1.pop());
oper = (String)oper1.pop();
if(oper.compareTo("*") == 0) {
calculateNum2 = Integer.parseInt((String)num1.pop());
resultNum = calculateNum2*calculateNum1;
num2.push(String.valueOf(resultNum));
while(oper1.isEmpty() == false && num1.isEmpty() == false) {
oper2.push((String)oper1.pop());
num2.push((String)num1.pop());
}//end of while
}//end of if
else if(oper.compareTo("/") == 0) {
calculateNum2 = Integer.parseInt((String)num1.pop());
resultNum = calculateNum2/calculateNum1;
num2.push(String.valueOf(resultNum));
while(oper1.isEmpty() == false && num1.isEmpty() == false) {
oper2.push((String)oper1.pop());
num2.push((String)num1.pop());
}//end of while
}//end of else-if
else if(oper.compareTo("^") == 0) {
calculateNum2 = Integer.parseInt((String)num1.pop());
resultNum = Math.pow(calculateNum2, calculateNum1);
num2.push(String.valueOf(resultNum));
while(oper1.isEmpty() == false && num1.isEmpty() == false) {
oper2.push((String)oper1.pop());
num2.push((String)num1.pop());
}//end of while
}//end of else-if
else {
num2.push(String.valueOf(calculateNum1));
oper2.push(oper);
}//end of else
}//end of while
while(!oper2.isEmpty()){
oper1.push((String)oper2.pop());
while(!num2.isEmpty()) {
num1.push((String)num2.pop());
while(!num1.isEmpty()) {
System.out.println(num1.pop());
while(!oper1.isEmpty())
System.out.println(oper1.pop());
}//end of main
}//end of class"27.0" is not an integer. (Well, it is numerically, but it's a representation of a double.)
-
String equivalent of Integer.parseInt()
Hey..
Integer.parseInt() reads an integer that is being inputted right? what im looking though is some sort of a String equivalent of Integer.parseInt.
ex:
nString = JOptionPane.showInputDialog("Enter number:");
n = Integer.parseInt(nString);
what im looking:
nString = JOptionPane.showInputDialog("Enter text:");
n = ? (nString);
a keyword that reads the text inputted.how do i reset the counter to 0 if the user tries again? because it doesn't reset and it makes a logical error if the user tries again.
while (trya != 0){
if ((trya > 1) || (trya < 0))
break;
else{
z=JOptionPane.showInputDialog("Choose Difficulty:\n[1]BATHROOM SINGER\n[2]MAINSTREAM MUSICIAN\n[3]GRAMMY WINNER");
x=Integer.parseInt(z);
switch(x){
case 1:
JOptionPane.showMessageDialog(null,"DIFFICULTY: BATHROOM SINGER");
String stringInput = JOptionPane.showInputDialog(q1);
if (stringInput.equals(a1)){
JOptionPane.showMessageDialog(null, "Correct!");
i++;
} else {
j++;
JOptionPane.showMessageDialog(null,"Wrong");
String stringInput29 = JOptionPane.showInputDialog(q15);
if (stringInput29.equals(a15)){
JOptionPane.showMessageDialog(null, "Correct!");
i++;
} else {
j++;
JOptionPane.showMessageDialog(null,"Wrong");
JOptionPane.showMessageDialog(null,"Correct answers: "+i+"\nWrong answers: "+j+"\nTHANKS FOR PLAYING");
break;
default:
JOptionPane.showMessageDialog(null,"Press either [1] [2] or [3]", "ERROR",JOptionPane.WARNING_MESSAGE);
break;
stry = JOptionPane.showInputDialog("Do you want to PLAY AGAIN? \n Press [1] for YES \n Press [0] for NO");
trya = Integer.parseInt(stry);
} -
Integer.parseInt, NumberFormatException
Hi,
I'm trying to convert numbers back and forth with parseInt and toHexString.
The number that I want to manipulate is 56789abc.
String str = Integer.toHexString(1450744508);
int i = 0;
try
i = Integer.parseInt(str, 16);
catch(NumberFormatException e)
e.printStackInfo();
I'm not sure why I'm getting NumberFormatException, since I think
56789ABC doesn't cross the line. It's not out of boundary.
Any suggestion or help really be appreciated.
Thanks in advance,I don't know what you're talking about.
Integer.parseInt("56789ABC", 16);gives 1450744508
Works fine. -
Integer.parseInt() method
Hi to all
I'm trying to write a piece of a lexical analizer in Java and I need the method the does the contrary of Integer.parseInt() method in order to do the following:
once i have as input an integer and with the Integer.parseInt() method i know it's value I want to count it's digits. I'm sure there is a method that do the contrary of Integer.parseInt() method that I can't remeber.
Thanks for your help
MaddyInteger.parseInt() takes in a String and returns an int value, so the contrary would take in an int value and return a String. Is this what you want?
You can use Integer.toString()
Also, when you call Integer.parseInt(String s), you should already have the number as a String (the argument).
Maybe I am not understanding the question right. If not, please explain exactly what you need. -
Hi,
There is a new feature added in java 7 on integer, called as underscore '_" and it is working fine
if it is a normal int variable but if it is coming with String jvm throw the error.
if any one of you have java8 installed on your PC can you check this is working on that version.
int a = 1000_000;
String strNum = "1000_000";
// System.out.println("..abc..."+ Integer.parseInt(strNum));
System.out.println("a..."+a);
Thank you,
Shailesh.what is your actual question here?
bye
TPD -
Integer.parseInt problems
Hi everyone,
I want to use the Integer.parseInt and Byte.parseByte methods to parse hex strings - the problem is that they don't parse negative 2's complement numbers, they explicitly need a minus sign in front of an otherwise unsigned number to show that it's negative.
Examples:
//System.out.println(Integer.parseInt(Integer.toHexString(-1), 16)); //NumberFormatException
System.out.println(0xffffffff); // but this prints -1
//System.out.println(Byte.parseByte("ff", 16)); //NumberFormatException
System.out.println(Byte.parseByte("-1", 16)); // but this worksIs there some other method that will do what I need?
Regards,
JonathanHere's a dirty solution:public class Test {
private static char[] digits = new char[] {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
public static void main (String[] parameters) {
String number = Integer.toHexString (parameters[0].equals ("+") ? Integer.MAX_VALUE : parameters[0].equals ("-") ? Integer.MIN_VALUE : Integer.parseInt (parameters[0]));
if ((number.length () == 8) && (getPosition (number.charAt (0)) >= 8)) {
String newNumber = "";
for (int i = 0; i < number.length (); i ++) {
newNumber += digits[15 - getPosition (number.charAt (i))];
number = "";
boolean carry = true;
for (int i = 7; i >= 0; i --) {
int position = getPosition (newNumber.charAt (i));
if (carry) {
position = (position + 1) % 16;
carry = (position == 0);
number = digits[position] + number;
number = "-" + number;
int numberAsInt;
try {
numberAsInt = Integer.parseInt (number, 16);
} catch (NumberFormatException exception) {
// -8000000
numberAsInt = Integer.MIN_VALUE;
System.out.println (numberAsInt);
private static int getPosition (char digit) {
int position = 0;
while ((position < digits.length) && (digits[position] != digit)) {
position ++;
return position;
}Start with java Test <yourNumber>: + for Integer.MAX_VALUE, - for Integer.MIN_VALUE.
I don't claim it's good or efficient: it's working though. There's lots of things to improve.
Kind regards,
Levi -
Integer.parseInt()
Hi!
I have a problem that for an experienced programmer like you should be easy.
I have in my program:
int num = Integer.parseInt(numbers);
And I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "195400011111111111111113"
It (195400011111111111111113) looks like not an integer,and I tried:
long num = Integer.parseInt(numbers);
But I get the same error.
What could I do?
Thank you,
NataThat number is too big for an int, so Integer.parseInt doesn't like it. It doesn't matter if you put a long on the left side of the equals sign, Integer.parseInt only handles ints.
Do you know about the Long class? Have you looked at its docs to see if it might have something that can help you? -
NetBeans 6.5 - Integer.parseInt(String)
Hello,
I'm beginner with NetBeans 6.5.
I created a simple hello-java application and a simple hello java-web JSF application.
I have no error with hello-java application for these 2 lines:
String name = "12345";
int aInt = Interger.parseInt(name) ;
but I get exception handler from java-web JSF application as below.
Hope you help me to solve this, Thanks !
Exception Handler
Description: An unhandled exception occurred during the execution of the web application. Please review the following stack trace for more information regarding the error.
Exception Details: java.lang.NumberFormatException
null
Possible Source of Error:
Class Name: java.lang.Integer
File Name: Integer.java
Method Name: parseInt
Line Number: 415
Source not available. Information regarding the location of the exception can be identified using the exception stack trace below.
......they're different, i was trying to convert the string entered in a TextField to a number, and thought that I already hard coded '12345' in the code to see whether the parseInt works therefore i didn't enter anything in the TextField.
thanks raychen ! -
Class of Integer.parseInt
Hi..,
I really need help. I am trying to make a really simple program. And that I want to make an argument class so that I can reuse it again and again without typing the long word (Integer...)
Here is the problem:
Rational r2 = new Rational(toInt(args[0]));
I think I should make a toInt method, but I don't know how. It is quite confusing. I think this toInt method, we should put it inside the main method. But i don't know yet.
Please Help me!well with the way you wrote it, toInt is a class, not a method. What you are probably envisioning is a class with a constructor which takes a String parameter and returns an int. Unfortunately, constructors don't return values. You can try using the object wrapper class Integer though.
One suggestion, if you hate the typing for getting arg parameters, make a method which takes the whole args array and parses them into a nice int array or some other data structure you dream up to make it easier? -
Is there any way to use Integer.parseInt using jstl
Hi
actually i m getting a string in a varible i need to convert it to int so that i can use it for further calculation.
so plz tell how to do that...
thanksThe exception clearly states the variable isn't a valid number. Print out the value and see what it is.
And no, you can't set the 'JSTL variable' for the simple reason that there are no 'JSTL variables' ( at least none that are public ). You're probably thinking of the EL. And no, you can't do anything there either.
People on the forum help others voluntarily, it's not their job.
Help them help you.
Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
(Yes I know it's on JavaRanch but I think it applies everywhere)
---------------------------------------------------------------- -
Reading file and parseInt - PROBLEM
Hi, I am trying read from .txt file but I have a problem when I use Integer.parseInt. Can you see what could be wrong in this source:
public String loadPlayerFromTxt() {
String result = "";
try{
FileInputStream fstream = new FileInputStream("Test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int position = 0;
while ((br.readLine()) != null) {
Gamer gamer = new Gamer();
gamer.setName(br.readLine());
gamer.setRace(br.readLine());
gamer.setRole(br.readLine());
gamer.setLevel(Integer.parseInt(br.readLine()));
String [] array = new String [6];
String abilities = br.readLine();
String str = abilities.trim();
//System.out.println(abilities);
array = str.split(",");
gamer.setStrength(Integer.parseInt(array[0]));
gamer.setEndurance(Integer.parseInt(array[1]));
gamer.setDexterity(Integer.parseInt(array[2]));
gamer.setIntelligence(Integer.parseInt(array[3]));
gamer.setWisdom(Integer.parseInt(array[4]));
gamer.setCharisma(Integer.parseInt(array[5]));
this.gcollection.addGamer(gamer,position);
position++;
result = "succesful";
in.close();
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
e.getLocalizedMessage();
return result;
Error message is:
Error: For input string: "12, 15, 19, 9, 14, 7"
java.lang.NumberFormatException: For input string: "12, 15, 19, 9, 14, 7"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:456)
at java.lang.Integer.parseInt(Integer.java:497)
at ca5.GameControle.loadPlayerFromTxt(GameControle.java:56)
at ca5.GameControle.main(GameControle.java:112)Pavel.Prochy wrote:
Hi, I am trying read from .txt file but I have a problem when I use Integer.parseInt. Can you see what could be wrong in this source:
Error: For input string: "12, 15, 19, 9, 14, 7"
java.lang.NumberFormatException: For input string: "12, 15, 19, 9, 14, 7"The Integer.parseInt() method expects a String that contains only numbers. You are passing it the following string:
12, 15, 19, 9, 14, 7Which contains punctuation and whitespace (i.e. not just numbers). When the string you pass to Integer.parseInt() contains anything but numbers you get the "NumberFormatException" thrown. What you need to do is to do some pre-processing on the string you read from the file or (ideally) change the format of the file so that you have each of the numbers on their own line rather than having multiple numbers on the same line. If you HAVE to keep all the numbers on the same line then you will need to do the following (or something very similar to it):
public class Tester3 {
public static void main(String[] args) {
String input = "12, 15, 19, 9, 14, 7";
String[] strings = input.split(",");
for(String string : strings) {
int parameter = Integer.parseInt(string.trim());
System.out.println("parameter: "+parameter);
}Program output from above code:
parameter: 12
parameter: 15
parameter: 19
parameter: 9
parameter: 14
parameter: 7When you use the Integer.parseInt() call you should consider the possibility that your input will cause the call to fail. You can pre-process the input to ensure it will not fail, catch the NumberFormatException by wrapping the call to Integer.parseInt() in a try-catch block or create a method in your class that throws a NumberFormatException to its caller and let the caller handle the error
Edited by: amp88 on Nov 4, 2009 2:26 AM
Edited by: amp88 on Nov 4, 2009 2:27 AM -
Problem with input.readLine()
import java.io.*;
public class HorseMain
public static void main(String[] args) throws IOException
//declare the FILENAME
//the user will later give the FILENAME
String horseFILENAME;
//declare the variables to be manipulated
String name, stable, winner, commentsStewards, commentsJockey, commentsPersonal;
int rating, race, distance;
String command;
//Mastery Factor 9: Parsing a text file or other data stream
//This will be used to accept the input from the user
BufferedReader input = new BufferedReader( new InputStreamReader(System.in) );
System.out.println("\t\t\t\tHORSES");
System.out.println("Enter the name of the file where the horses are saved:");
horseFILENAME = input.readLine();
//calling the HorseFile class
//the actual argument horseFILENAME will be used to open the file
HorseFile horse = new HorseFile(horseFILENAME);
//call the load method to load the contents of the file storing the data
horse.load();
//asking for user input
System.out.println("Please enter one of the given commands");
System.out.println("\t[a]dd a horse");
System.out.println("\t[d]elete a horse");
System.out.println("\t[e]dit details of a horse");
System.out.println("\t[s]earch for a horse by its name");
System.out.println("\t[p]rint the details of all the horses in the collection");
System.out.println("\t[g]et the horses having encountered problems in their last race");
System.out.println("\t[q]uit the program");
while (true) //the system must return true
System.out.println("Command: ");
command = input.readLine();
//using simple if...else selection to determine what action to be taken from command
//if the user wants to add a horse
if (command.equals("a"))
obtainName(name);
//perform search to determine whether this horse already exists
//if the horse already exists, message to inform user
if (horse.search(name) != null)
//message to inform the user that this horse already exists
System.out.println(name+ " already exists!");
else
//obtain the details on the horse
obtainStable(stable);
obtainRating(rating);
obtainRace(race);
obtainDistance(distance);
obtainWinner(winner);
obtainCommentsStewards(commentsStewards);
obtainCommentsJockey(commentsJockey);
obtainCommentsPersonal(commentsPersonal);
//add a new horse record
if (!horse.add(name, stable, rating, race, distance, winner, commentsStewards, commentsJockey, commentsPersonal))
System.out.println("Sorry");
System.out.println(name + " cannot be written to file");
//if the user wants to delete a horse
if (command.equals("d"))
System.out.println("Enter name of horse to be deleted: ");
name = input.readLine();
//perform search to determine whether this horse already exists
//if horse does exist, horse is deleted
if (horse.search(name) != null)
horse.delete(name);
System.out.println(name + " deleted!");
//if horse does not exist, message is output
else
System.out.println(name + " not found!");
//if the user wants to edit the details of a horse
if (command.equals("e"))
System.out.println("Enter name of horse to be edited: ");
name = input.readLine();
//perform search to determine whether this horse already exists
//if the horse does exist
if (horse.search(name) != null)
//obtain the new details of the horse
obtainStable(stable);
obtainRating(rating);
obtainRace(race);
obtainDistance(distance);
obtainWinner(winner);
obtainCommentsStewards(commentsStewards);
obtainCommentsJockey(commentsJockey);
obtainCommentsPersonal(commentsPersonal);
horse.edit(name, stable, rating, race, distance, winner, commentsStewards, commentsJockey, commentsPersonal);
//if the horse does not exist
else
System.out.println(name + "not found in collection");
//if the user wants to print the details of all the horses
if (command.equals("p"))
horse.display();
//if the user wants to quit the program
if (command.equals("q"))
break; //the system exits from the if...else selection
input.close();
horse.save();
/**This is the method to get the name of a horse from the user
**validation rules: length check
**The length of a horse name cannot exceed 18 characters.
public static void obtainName(String name)
System.out.println("Name of horse: ");
name = input.readLine();
//using simple if...else to validate user input
if (name.length() <= 18)
//do nothing
else
//output error message
System.out.println("Error! Name should not exceed 18 characters");
//Using mastery factor recursion to allow the user to input the name again
obtainName(name);
/**This is the method to get the stable of a horse from the user
**No validation rules are used
**Any string is accepted
public static void obtainStable(String stable)
System.out.println("Stable: ");
stable = input.readLine();
/**This is the method to get the rating of the horse from the user
**Validation rules: range check
**Rating should be between 20 and 110
public static void obtainRating(int rating)
System.out.println("Rating: ");
rating = Integer.parseInt(input.readLine());
//using multiple if...else selection
if ( (rating >= 20) && (rating <= 110) )
//do nothing
else
//output error message
System.out.println("Error! Rating should be between 20 and 110");
//using mastery factor - recursion - to allow the user to input the rating again
obtainRating(rating);
/**This is the method to get the number of the last race run by the horse
**Validation rules: range check
**Race number should be between 11 and 308
public static void obtainRace(int race)
System.out.println("Race number: ");
race = Integer.parseInt(input.readLine());
//using if...else
if ( (race >= 11) && (race <= 308) )
//do nothing
else
//output error message
System.out.println("Error! Race number should 11 and 308");
//using mastery factor - recursion - to allow the user to input the rating again
obtainRace(race);
/**This is the method to get the distance of the last race
**Validation rule: comparison check
**Distance can either be 1365, 1400, 1500, 1600, 1800, 2000, 2200, 2400
public static void obtainDistance(int distance)
System.out.println("Distance: ");
distance = Integer.parseInt(input.readLine());
//using if...else
if ( (distance == 1365) || (distance == 1400) || (distance == 1500) || (distance == 1600) || (distance == 1800) || (distance == 2000) || (distance == 2200) || (distance == 2400) )
//do nothing
else
//output error message
System.out.println("Error! Distance can either 1365, 1400, 1500, 1600, 1800, 2000, 2200, 2400");
//using mastery factor recursion to allow the user to input the distance again
obtainDistance(distance);
/**This is the method to get the winner of the last race
**Validation rule: length check
**The name of the winner cannot exceed 18 characters
public static void obtainWinner(String winner)
System.out.println("Winner: ");
winner = input.readLine();
//using if...else
if (winner.length() <= 18)
//do nothing
else
//output error message
System.out.println("Error! The name of the winner cannot exceed 18 characters");
//using mastery factor recursion to allow the user to input the winner again
obtainWinner(winner);
/**This is the method to get the stewards' comments on a horse
**No validation rules
**Any string is accepted
public static void obtainCommentsStewards(String commentsStewards)
System.out.println("Stewards' comments: ");
commentsStewards = input.readLine();
/**This is the method to get the stewards' comments on a horse
**No validation rules
**Any string is accepted
public static void obtainCommentsJockey(String commentsJockey)
System.out.println("Jockey's comments: ");
commentsJockey = input.readLine();
/**This is the method to get the stewards' comments on a horse
**No validation rules
**Any string is accepted
public static void obtainCommentsPersonal(String commentsPersonal)
System.out.println("Personal comments: ");
commentsPersonal = input.readLine();
}I see one problem already though. You defined "input" as a local variable in your main method, and then refer to it all over the place, outside of the main method.
If you want to use input like that, you'll have to define it as a field, not a local variable.
By the way your code is structured in a kind of hairy way. In OOP you usually want to structure your code around self-contained, encapsulated state and behavior, not just as a bunch of individual actions effecting global variables. -
Problem with entering integer numbers from keyboard
I have written this simple code:
import java.io.*;
public class Simple{
public static void main(String[] args)throws Exception{
System.out.println("Enter two integer numbers: ");
BufferedReader enter=new BufferedReader(new InputStreamReader(System.in));
int first=Integer.parseInt(enter.readLine());
int second=Integer.parseInt(enter.readLine());
System.out.println("Result is: "+(first+second));
and it works fine if I type first number, press Enter, then type
second number and press Enter.
But if I type in one line: 2 3 (with space between) I get run-time error:
Exception in thread "main"...bla...bla at java.lang.Integer.parseInt(Integer.java)...
I know that error is coming from Integer.parseInt(string) in my code, but I
don't know how can I avoid it.
In C that is rather simple scanf("%d %d",&first,&second), but in Java it's much more
complicated.
Do you have any suggestions how to solve this problem?store the user input in a string
use a StringTokenizer st
then
while(st.hasNext())
int first=Integer.parseInt(st.nextToken());
but you should really catch a NumberFormatException
walker
Maybe you are looking for
-
XMLFormService Error offline deploying adobe document services - 2
Hi, I am doing an offline deployment of Adobe document Services SP16. I am using the Software Deployment Manager to do this. The installation fails at the XMLFormService. Any hints or suggestions. Thank You. Sumit. [code]=============================
-
Refresh whole relational model from database
Version 3.2.09 - Build MAIN-09.30 Hi, I have created a model of my database in SQL Developer using the Data Modeller component by dragging all the table objects from the Tables tree onto the relational and logical panes. As I make changes to the data
-
Disable JWS BASIC Auth dialog ?
I have a Swing based client application that has a custom Login page. We have converted our client/server access from RMI to SOAP. The issue I have is when a user enters incorrect user/pass in my custom swing based login UI, JWS intercepts the respon
-
Missing contact info for one of the users. Can't get it back
?missing contace info for one of the users. can't get it back?
-
i'm using aperture since version 1. and till today i see the same color rendering issues which occurs when applying heavy exposure correction on my canon pro camera files. when i correct overexposed images i get a strange yellow posterisation not a