Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
{
private static final int StringIndexOutOfBoundsException = 0;
//values shared within the class
private static int sideA = 0;
private static int sideB = 0;
//main method
public static void main(String [] args)
{
System.out.println("Usage: Supply 2 integer values as triangle sides.");
System.out.println(" A-integer value");
System.out.println(" B-integer value");
System.out.println(" C-attempt a pythagorean calculation");
System.out.println(" Q-quit the program");
String value = null;
String side;
char c = 0;
int s1 =StringIndexOutOfBoundsException;
Scanner scanner = new Scanner(System.in);
boolean carryOn=true;
while(carryOn) //loop until user has finished.
{
side = JOptionPane.showInputDialog(null, "A or B?");
try
{
c =side.charAt(0);
} catch(NullPointerException NP){
System.out.println("Thanks you are done!");
}
switch(c) //which side is the user trying to set
{
case 'Q':
carryOn= false; //quit the program
break;
case 'A':
try{
value = JOptionPane.showInputDialog(null, "Enter A");
sideA = Integer.parseInt(value);
} catch(NumberFormatException NF){
System.out.println("Thats not a number. Type in an integer.");
break;
}
if (sideA<=0)
{
System.out.println("Cannot compute because A is zero. Try another integer");
break;
}
if(sideA>0)
{
System.out.println("You've inputed an A value. That value is "+sideA);
break;
}
break;
case 'B':
try{
value = JOptionPane.showInputDialog(null, "Enter B");
sideB = Integer.parseInt(value);
} catch(NumberFormatException NF){
System.out.println("Thats not a number. Type in an integer.");
break;
}
if (sideB<=0)
{
System.out.println("Cannot compute because B is zero. Try another integer");
break;
}
if(sideB>0)
{
System.out.println("You've inputed an B value. That value is "+sideB);
break;
}
break;
case 'C': //calculate an answer
double temporary = (sideA * sideA) + (sideB * sideB);
if(sideA <=0 && sideB <=0){
System.out.println("You don't have triangle. Try again");
break;
}
double result = java.lang.Math.sqrt(temporary);
System.out.println("The hypotenuse value is "+result);
break;
}
}
System.out.println("Thank you. Goodbye!");
return;
}
}
and my error is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0 at
java.lang.String.charAt(String.java:658) at
lab1.lab01.main(lab01.java:42)
What exactly is wrong?
While a String isn't exactly a char[] as it is in C, for certain operations, it's better to think of it like one.
When you attempt to index into an array that is empty or uninitialized, you'll get a similar exception - ArrayIndexOutOfBoundsException. This means that you're attempting to index into something that doesn't exist.
We know that an array of size N can be indexed to location N-1. For N = 0, we would (by math) be indexing into location -1, which is not permissible.
The same thing is happening when you perform charAt(). You're attempting to retrieve a value that doesn't exist. In other words: your String is empty.
The culprit is this line:
c =side.charAt(0);
If side is empty, you're stuck.
When you go to retrieve a value for side, as in this line:
side = JOptionPane.showInputDialog(null, "A or B?");
...add a check to ensure that it isn't empty, and wait until you get a valid length.
String side = JOptionPane.showInputDialog(null, "A or B?");
while(side.isEmpty()) {
JOptionPane.showMessageDialog("Invalid input!");
side = JOptionPane.showInputDialog(null, "A or B?");
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String user;
String pass;
String newPass;
String question = "What is your Pass Word? ";
int newPassLength;
Scanner userPass = new Scanner(System.in);
do {
do {
System.out.print("Please Enter your Pass word: ");
pass = userPass.next();
newPass = pass;
newPassLength = newPass.length();
if (newPassLength >= 3) {
System.out.println("This PassWord works.");
}
if (newPassLength <= 2) {
System.out.println("This PassWord doesn't Work.");
}
}
while (newPassLength <= 2);
Scanner userPassWord = new Scanner(System.in);
int one = 1;
int subtract = 4;
do {
System.out.print(question);
user = userPassWord.next();
if (user.equals(pass)) {
System.out.println("Pass Word is correct you may move on.");
break;
} else {
subtract = subtract - one;
if(subtract >= 0) {
System.out.println("PassWord is wrong. You have " + subtract + " more trys.");
}
}
if (subtract == 0) {
System.out.println("You have no more trys left. Would you like to reset your PassWord?(Y/N)");
}
if (user.equals("Y") || user.equals("y")) {
System.out.println("You May reset your Password.");
main(args);
break;
} else if(user.equals("No") || user.equals("no")) {
System.out.println("You do not get anymore trys. The Program will exit.");
System.exit(1);
} else if(subtract <= -1) {
System.out.println("You need to answer the question.(Y/N)");
}
}
while(true);
}
while(user == pass);
System.out.println("You may now enter the program.");
}
}
This is my output.
Please Enter your Pass word: true
This PassWord works.
What is your Pass Word? tr
PassWord is wrong. You have 3 more trys.
What is your Pass Word? tr
PassWord is wrong. You have 2 more trys.
What is your Pass Word? tr
PassWord is wrong. You have 1 more trys.
What is your Pass Word? tr
PassWord is wrong. You have 0 more trys.
You have no more trys left. Would you like to reset your PassWord?(Y/N)
What is your Pass Word? y
You May reset your Password.
Please Enter your Pass word: tr
This PassWord doesn't Work.
Please Enter your Pass word: tre
This PassWord works.
What is your Pass Word? tre
Pass Word is correct you may move on.
You may now enter the program.
You may now enter the program.
Process finished with exit code 0
Why at the end am I getting "You may now enter the program." Two times. I should only get it once and I don't think it is looping 2 times after the while loops are done but it looks like it is and I am not sure anyone have any ideas of what is wrong with my program or if I am missing something?
This bug only occurs when the logic to reset a password is triggered.
When this recursive main execution is finished, break is executed, and "You may now enter the program." is printed again.
if (user.equals("Y") || user.equals("y")) {
System.out.println("You May reset your Password.");
main(args);
break;
}
The easiest way to do this is to replace break with return.
I tried not to break the original code and fixed some of the original bugs:
public class SO_69983033 {
public static void main(String[] args)
{
boolean success = new SO_69983033().passwordSetAndCheck();
if (success) {
System.out.println("You may now enter the program.");
} else {
System.out.println("The Program will exit.");
}
}
public boolean passwordSetAndCheck() {
String user;
String question = "What is your Pass Word? ";
String newPass = setNewPassword();
Scanner userPassWord = new Scanner(System.in);
int one = 1;
int subtract = 4;
do {
System.out.print(question);
user = userPassWord.next();
if (user.equals(newPass)) {
System.out.println("Pass Word is correct you may move on.");
return true;
} else {
subtract = subtract - one;
if(subtract >= 0) {
System.out.println("PassWord is wrong. You have " + subtract + " more trys.");
}
}
if (subtract == 0) {
while (true) {
System.out.println("You have no more trys left. Would you like to reset your PassWord?(Y/N)");
user = userPassWord.next();
if (user.equals("Y") || user.equals("y")) {
System.out.println("You May reset your Password.");
return passwordSetAndCheck();
} else if(user.equals("No") || user.equals("no")) {
return false;
} else {
System.out.println("You need to answer the question.(Y/N)");
}
}
}
} while(true);
}
public String setNewPassword() {
Scanner scanner = new Scanner(System.in);
String password;
while (true) {
System.out.print("Please Enter your Pass word: ");
password = scanner.next();
if (password.length() >= 3) {
System.out.println("This PassWord works.");
return password;
}
System.out.println("This PassWord doesn't Work.");
}
}
}
I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm new at java and i tried to make a Guess The Number game.
When the loop starts, i want to check if the user has any tries left.
if (remain > 1);
then after each end of the loop I want to subtract 1 from the tries.
I also tried to gather 1 after each loop ends.
byte tries = 5, remain=(byte)(--tries);
When user is out of tries i want to break the loop and break the game:
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
Here's my code:
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte tries = 5, remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1);
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
Code works perfectly but it won't break when user is out of tries.
tries variable should be initialized outside the while loop and the if statement was being closed using a ';'
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
byte tries = 5; // tries should be initialized outside the loop
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1) { // You were using ; and this if statement was closed
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
I think you are misunderstanding a lot of concepts. Here's a commented version :
public class Master {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// The number to found
double numberToFound = (byte)(Math.random() * 21);
// The user number will be stored here
byte userInput = 0;
// The number of tries left
byte tryLeft = (byte) 5;
do {
// Ask the User an number
System.out.print("Choose a number between 1 and 21 :");
userInput = scanner.nextByte(); // Store it
// Test the number
if (userInput > numberToFound) {
System.out.println("You are lower than the number!");
} else {
System.out.println("You are higher than the number!");
}
tryLeft--; // We remove one try
} while(tryLeft > 0 && userInput != numberToFound); // We loop until there are no more try OR we found the number
// Last time check (we check why we exited the loop)
// The user found the number
if (numberToFound == userInput)
System.out.println("You have guessed the number!");
else // The user has no more tries left
System.out.println("You haven't guessed the number!");
}
}
You should avoid using while(true) if you have a breaking condition for better readability.
You can try this code.
I changed some datatypes and added the decreasing of the remain variable inside the loop.
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int number = (int)(Math.random() * 21);
int tries = 5;
int remain = tries;
while(true){
System.out.print("Choose a number between 1 and 21:");
int user = scanner.nextInt();
// User input
System.out.println(remain);
if (remain > 1) {
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
--remain;
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
First of all, you can check if the "remain" is bigger than 0 and not 1, and your code will do the job as you planned (and you don't need to check == 0 at the else) :)
Second of all small comments to make your code more arranged:
Work with parameters that are comfortable to you like int (easier to debug and work with) you should use byte only if the code really needs it.
Move parameters that you use only to check them outside the loop like tries (think on that you will define this variable on every loop iteration and you don't need to).
Add to the params you are not going to change (like tries & number after you moved outside the loop) final it will be more clear that you are not going to change this param anymore.
Other than that looks great, good luck! :)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to have a user guess a number picked by a random number generator, but my code decides to, if it doesn't equal, stick within one if statement.
System.out.println("Enter a guess between 1 and 200: ");
String guess = input.nextLine();
int userInput = Integer.parseInt(guess);
Random rnd = new Random(seed);
int x = rnd.nextInt(200) + 1;
int currentInt = 1;
String msg = "That was impossible!";
and my while loop contains many if statements:
boolean boo = false;
while (!boo) {
if (userInput == x) {
System.out.println("Congratulations! Your guess was correct!");
System.out.println("");
System.out.println("I had chosen " + x + " as the target number.");
System.out.println("You guessed it in " + currentInt + " tries.");
if (currentInt == 1) {
//do something
} else if (currentInt >= 2) {
//do something
} else if (currentInt >= 4) {
...
} else if (currentInt >= 11) {
msg = "Maybe you should play something else";
System.out.println(msg);
}
break;
} else if (userInput > x) {
System.out.println("Your guess was too high - try again.");
System.out.println("");
System.out.println("Enter a guess between 1 and 200: ");
String highGuess = input.nextLine();
int tooHigh = Integer.parseInt(highGuess);
continue;
} else if (userInput < x) {
System.out.println("Your guess was too low - try again.");
System.out.println("");
System.out.println("Enter a guess between 1 and 200: ");
String lowGuess = input.nextLine();
int tooLow = Integer.parseInt(lowGuess);
continue;
}
currentInt = currentInt + 1;
}
My code works decently, if the answer is correct in the first try then the first if statement works, but if it's greater or less than x, then the same block runs (if greater, keeps putting greater even if next input is less than)
Update userInput with tooHigh and tooLow .
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My goal is to store the amount of correct answers into the 'correctOutOf' method, which will then return the value of corrAns when called int the /*Wrapping Up*/ section of the example code below:
import java.util.Scanner;
public class littleQuiz {
public static void main(String[] args){
Scanner key = new Scanner(System.in);
char yesno;
int answer;
/*Welcome/Splash Screen*/
/*Ask if ready and accept yes or no with appropriate return response*/
System.out.print("Are you ready for a quiz? Y or N ");
yesno = key.next().charAt(0);
if (yesno == 'Y'){
/*affirmative response*/
System.out.println("Okay, here it comes!");
}
else{
/*negative response*/
System.out.println("What a wimp...");
System.exit(0);
}
/*Quiz Section*/
/*Question 1*/
System.out.println("Q1) What is the capital of Alaska?");
System.out.println(" 1) Melbourne\n" +
" 2) Anchorage\n" +
" 3) Juneau");
answer = key.nextInt();
if (answer == 3){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Question 2*/
System.out.println("Q2) Can you store the value 'cat' in a variable of type int?");
System.out.println(" 1) yes\n" +
" 2) no");
answer = key.nextInt();
if (answer == 2){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Question 3*/
System.out.println("Q3) What is the result of 9+6/3?");
System.out.println(" 1) 5\n" +
" 2) 11\n" +
" 3) 15/3");
answer = key.nextInt();
if (answer == 2){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Wrapping Up*/
System.out.println("Overall, you got " + correctOutOf() + " out of 3 correct.");
System.out.println("Thanks for playing!");
}
/*not sure of which access modifier to use, but none have fixed it*/
private static int correctOutOf(int answer) {
return corrAns;
}
}
I'm feeling pretty positive that my if statement is going to feed the 'correctOutOf' method simply because it is the only part of the statement that can check for a correct answer with the code as-is. (just so everyone knows my train of thought.)
Edit - if this is something more than a beginner should be messing with, thanks for pointing it out. (Biting off more than I can chew?)
Don't do that, do this at the start of main:
byte correct = 0;
Or this if you ever need to use it outside of main:
private static byte correct = 0;
Then add this to each correct answer if statement:
correct++;
And print the variable "correct".
...also, you may wish to add this function to your program, to replace "key.nextInt()", to prevent the user from crashing your program:
import java.util.regex.*;
private static final int integer() {
boolean invalid = true;
int number = 0;
while (invalid) {
String input = key.next();
if (input.matches("\\d+")){
invalid = false;
try {
number = Int.parseInt(input);
} catch (java.lang.NumberFormatException e) {
invalid = true;
System.out.print("Are you trying to break the program? Try again: ");
}
} else {
System.out.println("That's not a whole number! ");
System.out.print("Try again: ");
}
}
return number;
}