so I am currently having difficult trying to fix this. In short, I'm trying to create a banking application for a class. I'm writing a method to print and get user's inputs but the print lines print out both lines before I can get inputs. Here is my implementation.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
What I expected it to do was to print out "Input your username" then after I get the user's input for it then to print the next line. However, what happening right now is that both lines get print before I can put in anything.
Thank you in advanced.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
This should work now. I have added a scanner.nextLine() after inputing choice
Related
I am brand new to coding and trying to get my second program working. It is pretty straight forward as to what it does, but it is throwing an error on line 24 "Duplicate local variable confirm". Can't quite work out why it doesn't like what I'm doing.
Scanner userInput = new Scanner(System.in);
char confirm;
do{
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is" + name + ", you are" + age + "years old and you would like to visit" + country + "?");
System.out.println("Press Y to continue or N to start over");
char confirm = userInput.next().charAt(0);
if (confirm !='y' || confirm !='n'){
System.out.println("Sorry that input is not valid, please try again");
}
else {
System.out.println(name + "landed in" + country + "at the age of" + age + ".");
}
} while(confirm == 'Y'|| confirm == 'y');
You're declaring confirm twice. Change the second declaration to just assigning to it and you should be OK:
confirm = userInput.next().charAt(0);
// No datatype, so you aren't declaring confirm, just assigning to it
Because your "confirm" variable already defined in the scope (second row). If you want to assign a value, just write confirm = userInput.next().charAt(0);
Another option to fix is to remove the unnecessary declaration char confirm;
And use it only when needed
char confirm = userInput.next().charAt(0);
As #ScaryWombat suggested, you will need to change scope of the variable (currently while is in different scope than do )
It seems apart from re-declaration of the variable confirm there are one or more issue -
Issue 1:
After int age = userInput.nextInt(). It won't prompt for country input and will prompt Press Y to continue or N to start over.
Cause of this issue:
Since you are using int age = userInput.nextInt(); the scanner will only take the integer value from the input and will skip the \n newline character.
Fix
As a workaround, I've added userInput.nextLine(); after int age = userInput.nextInt(); such that it will consume the \n character after nextInt().
Issue 2:
After the 1'st iteration, this line will cause issueconfirm = userInput.next().charAt(0);.
Cause of this issue:
In 2'nd iteration you won't get a prompt to enter the name as the line String name = userInput.nextLine(); will take \n from the last iteration as input and will skip and prompt for age How old are you?.
Fix
As a workaround, I've added userInput.nextLine(); after confirm = userInput.next().charAt(0); such that it will consume the \n character after userInput.next().charAt(0) and the next iteration will go as expected.
Issue 3:
This logic if (confirm !='y' || confirm !='n') expects only y and n in lowercase but here while(confirm == 'Y'|| confirm == 'y') you are expection y and Y both.
Fix - I've added the necessary changes in the code below but would recommend you do change it to a switch case.
NOTE:
It is not recommended to do userInput.nextLine() after every input and you could simply parse it. See here for further information.
I'm not recommending it but this will get you program working
Scanner userInput = new Scanner(System.in);
char confirm;
do {
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
userInput.nextLine(); //adding this to retrieve the \n from nextint()
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is " + name + ", you are " + age
+ "years old and you would like to visit " + country + " ?");
System.out.println("Press Y to continue or N to start over");
confirm = userInput.next().charAt(0);
userInput.nextLine(); //adding this to retrieve the \n this will help in next iteration
System.out.println(name + " landed in " + country + " at the age of " + age + ".");
if (confirm == 'y' || confirm == 'Y') {
continue; // keep executing, won't break the loop
} else if (confirm == 'n' || confirm == 'N') {
break; // breaks the loop and program exits.
} else {
System.out.println("Sorry that input is not valid, please try again");
// the program will exit
}
} while (confirm == 'Y' || confirm == 'y');
}
Recommending that you use switch case instead of if comparasion of confirmation and parse the character and integer input and remove the arbitary userInput.nextLine() added as workaround.
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));
I have never taken a programming class before so I am very new to all of this and am having a bit of a challenge trying to get my answers to be displayed in writing. For example: if the user enters the numbers 2 and 5 and *, the answer should be displayed as two multiplied by five is 10.
Here is my program:
import java.util.Scanner;
public class CalculatorProjectCH
{//begin class
public static void main(String[] args)
{//begin main
//This program will ask the user to input two digits from 0-9 and then input a method of operation.
System.out.println("This program will act as a simple calculator. ");
System.out.println("It will ask you to enter two numbers from 0-9 and a method of operation "
+"(+, -, *, /, ^.) ");
//Declare variables input1, input2, result1, result2, result3, result4, and result5, as doubles.
double input1, input2, result1, result2, result3, result4, result5;
String text;
//Create scanner object to allow for input
Scanner input = new Scanner (System.in);
//Ask the user to enter the first number
System.out.print("\nEnter your first number: ");
input1 = input. nextDouble();
//Ask the user to enter the operation
System.out.println("Please enter the operation you would like to execute: ");
text = input.next();
//Ask the user to enter the second number
System.out.println("Enter your second number: ");
input2 = input.nextDouble();
result1= input1+input2;
result2= input1-input2;
result3= input1*input2;
result4= input1/input2;
result5= Math.pow(input1,input2);
switch (text)
{
case "+" :
System.out.println(result1);
break;
case "-" :
System.out.println(result2);
break;
case "*" :
System.out.println(result3);
break;
case "/" :
System.out.println(result4);
break;
case "^" :
System.out.println(result5);
break;
//If the user did not enter a valid method of operation
default :
System.out.println("Your operation was not recognized.");
}
}//end main
}//end class
You need to link the int value to the String version of the word somehow. I would suggest using an array:
String[] wordNumbers = new String[]{"zero","one", "two", "three"..."nine"};
Now when you need to print the String version of a number, just do this:
System.out.println(wordNumbers[0]);
Output:
zero
case "*" :
System.out.println(input1 + " multiplied by " + input2 + " is " + result3);
break;
case "/" :
System.out.println(input1 + " devided by " + input2 + " is " + result4);
break;
So I didn't change your code, just added this little part as an example to make sure what your question is about, is this what you are looking for?? And if this is it, you can just add + and - on your own with this principle.
there are another answers in stackoverflow, if you want this in your program than just tell me I can help you make it, I am just not sure what exactly you need
here I found a youtube video if you are into videos
My program basically allows the user to enter grades (elements) which are stored in a Gradebook (array). The user also has the option to change the grades (elements) in the Gradebook (array).
My issue is that once the while loop loops and the user is asked "Make more changes? Enter Yes or No" If I enter yes, then the user asked which grade to change, is allowed to replace the grade, and the modified gradebook prints. However, if I enter "no" just the gradebook prints. Is there a way I can get the program to print "Good bye!" (signaling the end of the program) if the user enters no? I believe I'm supposed reorganize my code and set a while-loop with boolean = false? But I'm not sure how to get started...
Any help would be greatly appreciated. Thank you.
System.out.println("Make changes? Enter Yes or No");
String makeChanges = input.next();
if (makeChanges.equals("no")) {
System.out.println("Good bye!");
}
while (makeChanges.equalsIgnoreCase("Yes")) {
// Ask user if what grade they would like to change
//int index = NumberReader.readPositiveInt(input, "Enter the index of the grade to be changed: (1 to " + grades + ") : ", "Invalid index input", index);
int index = NumberReader.readCappedPositiveInt(input, "Enter the index of the grade to be changed: (1 to " + grades + ") : ", "Invalid index input", numOfGrades);
System.out.println("Enter grade (limit to two decimal places)" + ": ");
// offset the index by one
mogrades[index - 1] = NumberReader.readPositiveDouble(input, "Enter grade " + index + " :",
"Invalid data entered");
System.out.println("The Grade book contains: ");
printArray(mogrades);
System.out.println("Make more changes? Enter Yes or No");
makeChanges = input.next();
System.out.println(makeChanges);
System.out.println("The Grade book contains: ");
printArray(mogrades);
}
}
Break statements are used to exit loops. You could try this in the while loop:
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
break;
}
If you want to exit the entire program, use System.exit(0);
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
System.exit(0);
}
Here is a simple program demonstrating how this would work:
import java.util.Scanner;
public class Simple {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String makeChanges = "Yes";
while (makeChanges.equalsIgnoreCase("Yes")) {
System.out.println("Make more changes? Enter Yes or No:");
makeChanges = input.next();
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
System.exit(0);
}
}
}
}
And here is the output from the command line:
daniel#4.3:StackOverflow$ javac Simple.java
daniel#4.3:StackOverflow$ java Simple
Make more changes? Enter Yes or No:
Yes
Make more changes? Enter Yes or No:
Yes
Make more changes? Enter Yes or No:
No
Good Bye!
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.