'Exception in thread Main....' error in Java - java

I am really a novice at Java but I'm giving it a shot with this program. This is a program to perform basic mathematical calculations, but with input from user.
import java.io.*;
import java.util.Scanner;
public class Math
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
int sa1, sa2, ss1, ss2, sm1, sm2, s;
boolean c = false;
double sd1, sd2;
while(c==false)
{
System.out.print("Do you want to: \n[1] Add. \n[2] Subtract. \n[3] Multiply. \n[4] Divide. \n[5] Exit \nPlease insert an option number below and press enter: ");
s = in.nextInt();
if (s==1)
{
System.out.print("You have chosen option 1 \nPlease enter your first number: ");
sa1 = in.nextInt();
System.out.print("Please enter your second number: ");
sa2 = in.nextInt();
System.out.print(sa1+ " + " +sa2+ " = " +(sa1+sa2));
}
if (s==2)
{
System.out.print("You have chosen option 2 \nPlease enter your first number: ");
ss1 = in.nextInt();
System.out.print("Please enter your second number: ");
ss2 = in.nextInt();
System.out.println(ss1+ " - " +ss2+ " = " +(ss1-ss2));
}
if (s==3)
{
System.out.print("You have chosen option 3 \nPlease enter your first number: ");
sm1 = in.nextInt();
System.out.print("Please enter your second number: ");
sm2 = in.nextInt();
System.out.println(sm1+ " x " +sm2+ " = " +(sm1*sm2));
}
if (s==4)
{
System.out.print("You have chosen option 4 \nPlease enter your first number: ");
sd1 = in.nextDouble();
System.out.print("Please enter your second number: ");
sd2 = in.nextDouble();
System.out.println(sd1+ " divided by " +sd2+ " = " +(sd1/sd2));
}
if(s>=6)
{
System.out.println("You have entered an incorrect option");
}
System.out.print("Would you like to try again? (Y/N): ");
String ans = in.nextLine();//prob with this line
char ans1 = ans.charAt(0);//or this line
if (ans1=='N' || ans1=='n')
{
c = true;
}
if(s==5)
{
c = true;
}
}
}
}
When I complile it I get an error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Math.main(Math.java:58)
I've tried searching everywhere for an answer. Can anyone help me with this? It needs to be able to read either a 'Y' or a 'N' from the user.

You get the exception when you run it. Not when you compile it. And the error message says:
you're trying to get the char at index 0 of a string, but the String has no index 0. This exception happens at line 58 of Main.java.
A String which doesn't have a char at index 0 is an empty string.
This probably happens because the last thing you read from SYstem.in() is a number, and reading a number doesn't consume the end-of-line that comes after. Add a call to readLine() before reading Yes or No from the user. And don't assume that the user will do what you tell him to do. That's almost never true. Validate the inputs you read.

Related

How can I make the sign out option to not appear even though I already pressed 1 to sign in (do while loop Java)

Hello I am currently new to Java and I would like to know how can I make the sign out option disappear since I already entered the option to sign in.
TL;DR the sign out option is still appearing even though I already pressed 1 to sign in.
I also need help on making a deduction and salary system
Here's my code:
import java.io.*;
public class Security{
public static void main(String[] args)
{
BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in));
int sign=0;
int hour=0;
int minute=0;
int out=0;
int hour2=0;
int minute2=0;
int pre=0;
int late=0;
int deduction=0;
String Str_1;
String Str_2;
String Str_3;
String Str_4;
String Str_5;
String Str_6;
String Str_7;
try{
System.out.println("Press 1 to sign in ");
Str_1=dataIn.readLine();
sign=Integer.parseInt(Str_1);
System.out.println("Press 2 to sign out ");
Str_5=dataIn.readLine();
sign=Integer.parseInt(Str_5);
if(late>=3)
{
System.out.println("Your Salary has been deducted");
deduction=pre-50;
}
do{
System.out.println("Everytime you sign in you get a 50$ salary");
System.out.println("Enter your name: ");
Str_2=dataIn.readLine();
System.out.println("Enter Hour: ");
Str_3=dataIn.readLine();
hour=Integer.parseInt(Str_3);
System.out.println("Enter Minute: ");
Str_4=dataIn.readLine();
minute=Integer.parseInt(Str_4);
do{
System.out.println("Number of lates: "+late);
late++;
}while(hour>7||minute>30);
if(hour<=7&&minute<=30)
{
System.out.println("You are on time!");
}
else if(hour>7||minute>30)
{
System.out.println("You are late!");
}
System.out.println("Press 1 to sign in ");
Str_1=dataIn.readLine();
sign=Integer.parseInt(Str_1);
System.out.println("Press 2 to sign out ");
Str_5=dataIn.readLine();
sign=Integer.parseInt(Str_5);
}while(sign==1);
while(sign==2)
{
System.out.println("Enter Your Name: ");
Str_5=dataIn.readLine();
System.out.println("Enter Hour: ");
Str_6=dataIn.readLine();
hour2=Integer.parseInt(Str_6);
System.out.println("Enter Minute: ");
Str_7=dataIn.readLine();
minute2=Integer.parseInt(Str_7);
System.out.println("Thank you for working hard!");
System.out.println("Here's your salary!");
pre=0+50;
}
System.out.println("Press 1 to sign in ");
Str_1=dataIn.readLine();
sign=Integer.parseInt(Str_1);
System.out.println("Press 2 to sign out ");
Str_5=dataIn.readLine();
sign=Integer.parseInt(Str_5);
}
catch(Exception e)
{
System.out.println("Oops you entered something wrong");
}
}
}
System.out.println("Press 1 to sign in , Press 2 to sign out ");
Str_1=dataIn.readLine();
sign=Integer.parseInt(Str_1);
if(sign==2)
Str_5=Str_1;//i write here because maybe u need str_5
But why are you using str_1,2,3,4,5...
sign = Integer.parseInt(in.readLine());

Ask user for numerical input and return character at that index?

I am stumped on how to go about completing this. The script needs to Ask the user for a sentence, tell them the length, return the character at that index, than ask them for a character and give the first location it appears. I just cant figure out how to use the numerical input to find return the character at that index. (I know its probably a simple answer).Everything else works.
public class Sentence
{
Scanner scan = new Scanner (System.in);
int sentlength;
int letterenter;
int lowerinput;
int letterloc;
String enterletter;
public void sentence()
{
System.out.print("Please enter a sentence");
String originalsent = scan.nextLine();
sentlength=originalsent.length();
System.out.println("The sentence is "+sentlength+" charecters long");
System.out.println("Please enter a number less than the length of the sentence");
lowerinput = scan.nextInt();
System.out.println("Please enter a charecter");
enterletter = scan.next();
letterloc = originalsent.indexOf(""+enterletter+"");
System.out.println(""+letterloc+"");
}
public static void main(String[] args)
{
Sentence worksheet= new Sentence();
worksheet.sentence();
}
}
I believe you are looking for something like this from your question
System.out.print("Please enter a sentence: ");
String originalsent = scan.nextLine();
sentlength=originalsent.length();
System.out.println("The sentence is "+ sentlength +" characters long");
System.out.println("Please enter a number less than the length of the sentence: ");
lowerinput = scan.nextInt();
System.out.println("The character at index " + lowerinput + " is " + originalsent.charAt(lowerinput));
System.out.println("Please enter a character: ");
enterletter = scan.next();
System.out.println("The first index " + enterletter + " shows up is at " + originalsent.indexOf(enterletter));
When run outputs the following
Please enter a sentence: the cow flew over the moon
The sentence is 26 charecters long
Please enter a number less than the length of the sentence:
5
The character at index 5 is o
Please enter a charecter:
o
The first indext o shows up is at 5
It's very easy :
System.out.println(originalsent.charAt(lowerinput));

Exit a program when IF statement == true?

I'm trying to create a program computes and prints how many real solutions for the given equation.
the User enter the values for A,B and C.
And I want the program to exit if the user entered a value for A = 0 and not to continue asking for the others value.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a vlaue for A : ");
int coA = s.nextInt();
if (coA==0){
System.out.println("Error ! Enter a vlaue larger than 0 ");
};
System.out.println("Enter a vlaue for B : ");
int coB = s.nextInt();
System.out.println("Enter a vlaue for C : ");
int coC = s.nextInt();
double coTotal = (Math.pow(coB, 2))-4*coA*coC;
if(coTotal>0){
System.out.println(" The System has two solutions ");
}
if (coTotal==0){
System.out.println(" The System has one solutions ");
}
if(coTotal<0){
System.out.println(" The System has ZERO solutions ");
}
}
If this code is in main you can use System.exit, like this. I used -1 to indicate there was an issue with the input. You could use a different error code:
Scanner s = new Scanner(System.in);
System.out.println("Enter a vlaue for A : ");
int coA = s.nextInt();
if (coA==0){
System.out.println("Error ! Enter a vlaue larger than 0 ");
System.exit(-1);
};
System.out.println("Enter a vlaue for B : ");
int coB = s.nextInt();
System.out.println("Enter a vlaue for C : ");
int coC = s.nextInt();
double coTotal = (Math.pow(coB, 2))-4*coA*coC;
if(coTotal>0){
System.out.println(" The System has two solutions ");
}
if (coTotal==0){
System.out.println(" The System has one solutions ");
}
if(coTotal<0){
System.out.println(" The System has ZERO solutions ");
}

Validation for Negative numbers

System.out.print("Price of the book? ");
while (!keyboard.hasNextDouble() || priceOfBook <=0)
{
System.err.print("Invalid input - Price of " + bookTitle + "? ");
keyboard.nextLine();
}
priceOfBook = keyboard.nextDouble();
I am trying to validate the above code basically so that user can't enter negative numbers or letters or empty doubles but it's not working and I can't see where I'm going wrong. Can someone please help me?
So how i understand you need to real line until the user didint enter negative or letter.
Scanner sc = new Scanner(System.in);
double x = 0;
System.out.println("Enter price");
while (true) {
if (!sc.hasNextDouble()) {
System.out.println("Sorry price cant be negative or be letter");
break;
}
System.out.println("Enter price");
x = sc.nextDouble();
}
Hope it helps!
You put
priceOfBook = keyboard.nextDouble();
outside of your while loop :) Try like this:
while (priceOfBook <= 0)
{
System.err.print("Invalid input - Price of " + bookTitle + "? ");
priceOfBook = keyboard.nextDouble();
}
So that it will keep asking the user if he enters a number < 0.
You don't assign the user's input to priceOfBook until after the while loop. So, when your loop checks if priceOfBook is negative, it doesn't check the user's input, but the previously stored value (if there is one). This allows the user's input (even if it's negative) to pass the while loop, and then get saved as priceOfBook.
Try instead:
while (!keyboard.hasNextDouble() || priceOfBook = keyboard.nextDouble() <=0) {
System.err.print("Invalid input - Price of " + bookTitle + "? ");
keyboard.nextLine();
}

Conversion from one base to another

I already try to make a program it works as well but the problem is, that is not the same output what i want.
Note **
That is what i want..
enter starting base: it should be binary or octal or hexa
enter end base: it should be decimal
enter number: if 2 is entered as the starting base only 1s and 0s can be entered. If 16 is entered as the starting base 0-9 and A-F can be used.
and what i make :(
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting base: ");
String binaryNumber = scanner.nextLine();
System.out.println("Enter a end base: ");
String octalNumber = scanner.nextLine();
System.out.println("Enter a number: ");
String decimalNumber = scanner.nextLine();
int myInt = Integer.parseInt(binaryNumber, 2);
int myInt2 = Integer.parseInt(octalNumber, 8);
int x = myInt;
System.out.println(
binaryNumber + " in Binary, is "
+ Integer.toString(myInt, 8) + " in Octal" + " and "
+ Integer.toString(x, 10) +" in decimal");
This is what you need to do. Figure out the code and understand. You have Scanner#nextInt() method to read integers. You don't have to use nextLine() method for this. And more over, Scanner#nextInt(int radix) accepts the input in specified radix form. It throws an exception if you don't enter the input in that form. You can catch that exception to display the error message to the user.
Your goals startBase,endBase, and the variables used for them binaryNumber is mismatching. Please name your variables which convey the purpose of them.
See the modified version of your code here:
import java.util.*;
public class Tester{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting base: ");
int startBase = scanner.nextInt();
System.out.println("Enter a end base: ");
int endBase = scanner.nextInt();
int number=0;
try{
System.out.println("Enter a number: ");
number= scanner.nextInt(startBase);
System.out.println("Entered number:"+number+"(base"+startBase+")");
System.out.println("Converted number:"+Integer.toString(number,endBase)+"(enbase"+endBase+")");
}catch(InputMismatchException e){
System.out.println("Invalid input for the given radix");
e.printStackTrace(); //you can comment it if you don't need this.
}
}
}

Categories