I am new in Java. I'm taking my first java class. I am trying to create a fixed size array ( for example: the array with a size is 10) and I use JOptionPane to let the user input data. My question is how can I let the user stop their input whenever they want. (For example: They just input 3 data instead of 10 and they want to finish it). This is my first post, I'm sorry if the format is not correct. Thank you guys.
import java.util.Arrays;
import javax.swing.JOptionPane;
public class TestArray {
/**
* #param args
*/
public static void main(String[] args) {
String[] lastName = new String[10];
for (int i = 0; i < lastName.length; i++)
{
lastName[i] = JOptionPane.showInputDialog(null,"Please Enter Tutor Last Names: " );
}
JOptionPane.showMessageDialog(null, lastName);
Just break out of the loop when you encounter a null value or empty String. Click cancel or enter an empty String to break from the loop.
for (int i = 0; i < lastName.length; i++) {
lastName[i] =
JOptionPane.showInputDialog(null, "Please Enter Tutor Last Names:");
if (lastName[i] == null || lastName[i].isEmpty()) {
break;
}
}
just put a check using certain variable and prompt user at end of every cycle to continue or not...if user wants to quit simply use break;
but it is good practice that to get the no of iteration prior to rotating loop...ask user that for how much no of time they want to execute the steps...store it in variable and use that as exit condition...
Related
all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.
I'm currently working on an assignment for school and I am almost done but I just have one large problem I need to fix before I can add the final bit.
I need to create a program that prompts you to enter either 1 or 2, Afterwards it asks you to enter three words/names and saves them into an array.
Then, depending on whether you picked 1 or 2, it prints them in alphabetical order or flips around the lowercase and uppercase letters. I didn't add that part yet because I'm trying to fix a problem related to the very first input.
When you input a number other than 1 or 2, I am instructed to display an error message and ask for input again. I am pretty sure what I need to do is get the entire program to go back to the beginning because copy/pasting the entire program again would be bad, lol
A big problem is probably that I'm using if/else statements with for loops inside when I might need to put the entire thing inside a loop? But I'm not sure what condition I would use to start the loop if I put the entire code in it. I must be missing something here.
With what I have now, it gets stuck saying invalid input even if you put in a 1 or 2.
import java.util.Scanner;
public class IsabellaPiantoniLab5 {
public static void main (String[]args) {
//Ask for input
Scanner input = new Scanner(System.in);
System.out.print("Please choose either a number 1 or number 2.");
int numChoice = input.nextInt();
//if choice is 1 or 2
if (numChoice == 1 || numChoice == 2) {
System.out.println("Please enter three names: ");
String nameInput[] = new String[4];
//input loop
for (int i= 0; i < nameInput.length; i++) {
nameInput[i] = input.nextLine();
}
System.out.println("Values are:");
//display values if 1
if (numChoice == 1) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
//display values if 2
else if (numChoice == 2) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
}
//retry if invalid------i restart from the beginning if this happens
else if (numChoice != 1 || numChoice != 2) {
System.out.println("Invalid value. Please try again.");
//continue;
}
}
}
System.exit(0);
This will terminate the app, thus you can start it again using command line ( START [your app path])
Or
RunTime.getRuntime().exec(“Your app”);
System.exit(0);
Edit I misunderstood the question, I thought you wanted to restart the whole app
After discussing the approach with #csm_dev
It is way either to ask for the user input one more time by emptying the field and showing a message “please enter a valid input” with a clarification message
package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.
in my program I want the user to be able to print an element from an array. This is how far I've and I can't think of what to put next?
public void viewClub() {
System.out.println("Please enter the name of the country whose details you would like to see");
String Name = input.next();
for (int i = 0; i < countryList.size(); i++) {
Country x = countryList.get(i);
if (Name.equalsIgnoreCase(x.getName())) {
}
You anyways have x.getName in which x points to ith element of the array. So even if you just do a sys out for
x.getName()
you will get the value.
Hope this be of some help
Happy Learning :)
You want to output the details of a country that the user inputs. To do this, you will need a function in your country class that returns a string containing the details of that country:
System.out.println(x.getCountryDetails());
You don't want to output the name, because the user already knows that.
After you find the country, you should break out of your loop, to stop further processing:
for (int i = 0; i < countryList.size(); i++)
{
if (name.equalsIgnoreCase(countryList.get(i).getname()))
{
System.out.println(countryList.get(i).getCountryDetails());
break; //Exit the for loop because you found the specified country
}
}
firstly you take a array in your program, then by using buffered input streams or any other take the input from the user, store it into the array and then print the array index which contain the values
I need to write a program that will have a user enter a list of tutor names. Only up to 10 peer tutors may be hired. Then, the program will present each name, based on a list alphabetized by last name. This is what I have so far, but it does not work and I don't know what to do. I need it to continue to run until I stop it and continue with more of the program.
import javax.swing.JOptionPane;
import java.util.Arrays;
public class Report {
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames();
}
public static String[] getTutorNames() {
String firstName;
String lastName;
String[] listNames = new String[10];
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals("")) && lastName.equals("")) {
break; // loop end
}
listNames[x] = lastName + ", " + firstName;
}
return listNames;
}
}
Well, this is a first. IntelliJ didn't format the code correctly when I edited it, and I soon discovered this hit-list of errors. Just bear in mind - the code won't even compile, let alone run, until these are fixed.
int numTutors comes out of nowhere. If you want to define it, then do so outside of the method call and set it to an appropriate value.
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames(numTutors);
}
These declarations are invalid:
String = firstName;
String = lastName;
You need some sort of variable name in between String and =.
You're also not matching the contract for what you're passing in to getTutorNames - either what you pass in or what you accept must change. I'm thinking that it's the latter.
You can't use == to compare String. You have to use .equals(). Which leads me to...
Your break is outside of your loop. Move it inside of the loop.
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals(" "))&&lastName.equals(" ")){
break; // loop end
}
}
..and that leads me to...
You don't put the values anywhere through the loop! You're just running the same code ten times! Place them into the array.
// after you check to see if the firstName and lastName are blank
listNames[x] = firstName + lastName; // I don't know what you want to do with them from here.
There is no .add() for an array. The above is how you enter elements into an array.
Your return is outside of your method block entirely. Move it into your method.
Now, these are the issues that I could find. Work on the compilation issues first, then one may talk about errors in code logic. If you can, snag a quiet moment and ensure you understand variable declaration and String comparison. I would strongly recommend the reading material found in the Java wiki tag.
So sorry for making an answer for something this small but your
If (firstName.equals("")) && lastName.equals("")) {
Should be replaced by
If ((firstName.equals("")) && lastName.equals(""))) {