Click to See Complete Forum and Search --> : Basic java problem
hugo84
August 20th, 2009, 08:21 AM
Hi i need some help to implement the limit of characters one can type. It should show an error msg that the user cannot input more than 2 characters in x coordinate and y coordinate. How should i do that?
import java.util.Scanner;
public class P1
{
public static void main(String[]args)
{
int xaxis,yaxis;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the X Coordinates:");
xaxis = sc.nextInt();
System.out.println("Enter the Y Coordinates:");
yaxis = sc.nextInt();
if(xaxis >=0 && yaxis >=0)
System.out.println("Q1");
else if(xaxis < 0 && yaxis >=0)
System.out.println("Q2");
}
}
Londbrok
August 20th, 2009, 11:28 AM
First you should consider what happens if the user enters a wrong input? How do you get to ask for a new one? As to limiting things to simply 2 characters... how is that difficult? Digits smaller than -99 and greater than 99 have more than "2 characters".. why not check that?
hugo84
August 20th, 2009, 11:56 AM
First you should consider what happens if the user enters a wrong input? How do you get to ask for a new one? As to limiting things to simply 2 characters... how is that difficult? Digits smaller than -99 and greater than 99 have more than "2 characters".. why not check that?
Hi, Thanks for the advice thats a good point, however could you give me more specific instructions as i am quite a newbie in java. Thanks
Xeel
August 20th, 2009, 11:58 AM
int strlength = str.length();
hugo84
August 20th, 2009, 12:04 PM
int strlength = str.length();
It gives me this error
P1.java:21: int cannot be dereferenced
int strlength = xaxis.length();
^
1 error
holestary
August 20th, 2009, 12:13 PM
u meaned that??
if(xaxis >=0 && xaxis<=99 && yaxis >=0 && yaxis<=99)
System.out.println("Q1");
else if(xaxis < 0 && xaxis>=-99 && yaxis >0 && yaxis<=99)
System.out.println("Q2");
hugo84
August 20th, 2009, 12:22 PM
Im actually planning to do something like that. however i had error reading the length
int strlength = xaxis.length();
if ( strlength > 2) {
System.out.println("Pls input again");
System.exit(0);
}
else
....
holestary
August 20th, 2009, 12:48 PM
import java.util.Scanner;
public class P1
{
public static void main(String[]args)
{
String xaxis,yaxis;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the X Coordinates:");
xaxis = sc.next();
System.out.println("Enter the Y Coordinates:");
yaxis = sc.next();
if(xaxis.length()<2 && yaxis.length()<2)
{
here you have to convert string to int and compare them last write what u want..
}
}
}
holestary
August 20th, 2009, 12:51 PM
for converting..
http://www.java2s.com/Code/Java/Language-Basics/Convertstringtoint.htm
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.