this is my current code and I am having troubles removing the name and the net and gross information included with the name. Any help would be greatly appreciated
public static int removeName(String[] nameArray,
int[] grossArray, int[] netArray, int counter) {
Scanner keyboard = new Scanner(System.in);
String name;
int nameSearch;
System.out.println("Please enter the name you would like to remove.");
name = keyboard.nextLine();
nameSearch = searchArray(nameArray, name);
if (nameSearch != -1) {
nameArray[nameSearch] = name;
counter--;
} else {
System.out.println("That name is not on the list");
}
return counter;
}
Code runs and gives no errors. When the code runs it just edits the name I type in depending on the case format I use (uppercase/lowercase). I need this code to remove the name and the information associated with it. When removing I also need the list to move up so if I delete Bob for example and Jen is below Bob Jen takes Bob's place since he is deleted. I am not allowed to use array lists.
if (nameSearch != -1) {
nameArray[nameSearch] = name;
counter--;
} else {
System.out.println("That name is not on the list");
}
return counter;
Why are you setting nameArray[nameSearch] to name? Don't you want to remove what's in nameArray[nameSearch]?
If that's what you want to do you could temporarily convert nameArray into an ArrayList and remove what's at the index of nameSearch. Something like this:
List<String> nameArrayList = new ArrayList<String>(Arrays.asList(nameArray));
nameArrayList.remove(nameSearch);
nameArray = nameArrayList.toArray();
If you do this you might as well consider keeping nameArray as an arrayList throughout your function.
Related
I am fairly new to Java and was trying to make a username check for profanities.
I have made an Array with 4 profanities and now I wanted to check the user's input for the bad words, however, I don't know how to form the if statement to check all items from the array.
public static void main(String[] args) {
Scanner character = new Scanner(System.in);
String[] profanities = {"asshole", "ass", "idiot", "stupid"};
System.out.println("What is your name");
String userName = character.next();
if (userName.contains(profanities[])) { //This Part is what i dont understand
System.out.println("Invalid name");
}
else {
System.out.println("Valid Name!");
}
}
Use a Set instead of an ArrayList and then profanities.contains(userName). Mind you, the user should have inputted the exact profanity as in the profanities Set, in order for the if statement to evaluate to true. If the user inputs something like 'userjackass', it will not be classed as profanity.
Without the need of creating further Collections, just your original array. As the set of invalid names would be previously set/known, the sort operation could only be performed once, when the program is started.
Once sorted, just call binarySearch on it for every input:
Arrays.sort(profanities); //--> if profanities is a static set, call this just once.
if (Arrays.binarySearch(profanities,username)>=0)
System.out.println("Invalid name");
else
System.out.println("Valid Name!");
//binarySearch will return >=0 if the value is found
This avoids the creation of sets, lists, or the implementation of loops.
If the set of invalid names may change (adding new ones, for example), this would require a second sort operation. In this scenario, the other answers provided would be a better approach. Use this method if the invalid names set is known and won't be altered during your program's execution.
I would do it like this..
import java.util.Scanner;
public class Profanities {
public static void main(String[] args) {
boolean allow = false;
Scanner scan = new Scanner(System.in);
String[] profanity_list = {"asshole", "ass", "idiot", "stupid"};
String test_input = "";
// do while until allow equals true..
while (!allow) {
System.out.println("What is your name?");
test_input = scan.nextLine();
byte memory = 0;
// compare the input with the elements of the array..
for (int pos = 0; pos < profanity_list.length; pos++) {
if (test_input.contains(profanity_list[pos]) == true) {
System.out.println("Invalid name. Let's start again..");
memory = 1;
break;
}
}
// if memory equals 1, it means that a profanity was found..
if(memory == 0){allow = true;}
}
String name = test_input;
System.out.println("That is a valid name. Thanks.");
}
}
Instead of using Array of String, use List of String from which you can easily use contains method. I modified you're code with List, refer below
public static void main(String[] args) {
Scanner character = new Scanner(System.in);
//String[] profanities = {"asshole", "ass", "idiot", "stupid"};
ArrayList<String> profanities = new ArrayList<String>();
profanities.add("asshole");
profanities.add("ass");
System.out.println("What is your name");
String userName = character.next();
if (profanities.contains(userName)) { //This Part is what i dont understand
System.out.println("Invalid name");
}
else {
System.out.println("Valid Name!");
}
}
One more advantage of using List is, it's dynamic, you can add elements to it in future without any issues
Try:
for(String string : profanities)
if(userName.contains(string))System.out.println("invalid name");
else System.out.println("valid name");
Note: the for loop iterates through every entry in the array and checks to see if the entry is contained within userName
I have the following code that gets a user input:
456589 maths 7.8 english 8.6 end
654564 literature 7.5 physics 5.5 chemistry 9.5 end
and stores the code at the beginning of the sentence in an array called grades and the code in another array called person. I need to use these two arrays in order to display later each person's average grade in each lesson.
My code is the following
import java.util.Scanner;
public class Student
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String currentAnswer = "";
String userWords = "";
String am = "";
String subj = "";
float grad;
float[] grades = new float[100];
String[] person = new String[100];
System.out.println("Enter your a.m. as well as the subjects which you sat in finals");
while(!currentAnswer.equals("end"))
{
currentAnswer = s.nextLine(); // reads the number or word
userWords += currentAnswer + " ";
if(currentAnswer.equals("000000"))
{
System.out.println("The sequence of numbers you entered is: "+userWords);
System.out.println("Exiting...");
System.exit(0);
}
String[] wordsplit = currentAnswer.split(" ");
for (String str : wordsplit)
{
try
{
grade = Float.parseFloat(str);
}
catch(NumberFormatException ex)
{
person = str;
}
}
}
System.out.println("Enter your a.m. as well as the subjects which you sat in finals");
}
}
The error message concers the lines
grades = Float.parseFloat(str);
person = str` --> `String cannot be converted to String[]`<br>
Seems that converting a String into a String array is prohibited. What can I do in order to avoid this?
thank you!!
Look again on the code
grade = Float.parseFloat(str); and vars declaration
float grad; float[] grades = new float[100]
Cannot see any grade !
This cannot compile for sure !
Well, the error message speaks for itself, you are trying to assign String into String[], since it is an array, you want to call something like person[0] = str, same thing with grade, you want to call grade[0] = Float.parseFloat(str)
... but ofc you probably want to store number of persons inserted into the array, so you create an int inserted = 0 and then call grade[inserted] = Float.parseFloat(str) and also call inserted++ after that (or simply call grade[inserted++] = Float.parseFloat(str).. I assume you will need one integer for persons and one for grades
Try using ArrayLists, there are more forgiving than arrays, and simple to learn. You can see more about them here:
https://www.w3schools.com/java/java_arraylist.asp
If you want to use ArrayList, you must include this in begging of your file.
import java.util.ArrayList;
You defined grad and used grade
Initially when you defined you used the variable name grad
float grad;
But you used grade here
grade = Float.parseFloat(str);
Also try to use ArrayList instead of String array
When I run this program, it does not return anything yet no errors occur. I'm trying to create a method that will return the number of words I previously entered into the array once I enter "".
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayCounter {
public static int CountItems(ArrayList<String> list ) {
int i = list.size();
return i;
}
public static void main (String args[]) {
ArrayList<String> Names = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("Hey gimme a word");
String word = input.nextLine();
if (word.equals("")) {
System.out.println("The number of values entered were:");
break;
} else {
Names.add(word);
}
}
CountItems(Names);
input.close();
}
}
You're ignoring the result returned from CountItems.
The println should be:
System.out.println("The number of values entered were: " + CountItems(Names));
As an aside, methods names in Java should start with a lowercase, so CountItems should instead be countItems.
Your CountItems method returns the item count, but you are ignoring the result. You need some kind of System.out.println(CountItems(Names)) to print the result to the console.
Also, please consider renaming CountItems to countItems and Names to names to follow the naming conventions for Java.
I cannot seem to get my saved accounts stored inside my ArrayList. I think the latest one overwrites the oldest one, but I need them all to stack up in the ArrayList.
When I run the program, I create (add to ArrayList) a new Account, say Greg. Then I go on using that account and later on, add another account, say Bob. Then I click on "search for account" and type in Greg, it doesn't find it, but it finds Bob. HOWEVER, if I search for Greg BEFORE I create Bob, it FINDS IT!
Here are the relevant parts of my code:
////////// DECLARATIONS /////////
public static ArrayList dataStore;
public static int index;
dataStore = new ArrayList(10);
index = 0;
/////////////////////////////// ADD NEW ACCOUNT ////////////////////////////////
else if(source.equals("Add new account")) {
//************* Output
accountName = JOptionPane.showInputDialog("Enter the account name: ");
account.setName(accountName);
String strInitialBalance = JOptionPane.showInputDialog("Enter your initial
balance: ");
initialBalance = Double.parseDouble(strInitialBalance);
account.setBalance(initialBalance);
account = new CheckingAccount(initialBalance, accountName);
dataStore.add(index++, account);
}
//////////////////////////////// FIND ACCOUNT /////////////////////////////////
else if(source.equals("Find an account")) {
String str, name;
str = JOptionPane.showInputDialog("Enter the Account name: ");
for (int index = 0; index < dataStore.size(); index++) {
Account datum = (Account)dataStore.get(index);
if (str.equals(datum.getName())) {
name = datum.getName();
textArea.setText("Found Account for " + name);
}
else
textArea.setText("No Accounts found!");
} // for
}
This "account" object they are referring to is a class I have where all the data gets stored. Here is its header:
public class CheckingAccount extends Account implements Serializable {
// ...
// Methods
// ...
}
Here is your original chunk of code.
for (int index = 0; index < dataStore.size(); index++) {
Account datum = (Account)dataStore.get(index);
if (str.equals(datum.getName())) {
name = datum.getName();
textArea.setText("Found Account for " + name);
}
else
textArea.setText("No Accounts found!");
}
I dont think it makes sense to have the else statement inside your for loop, try the code below instead...
boolean found = false;
for (int index = 0; index < dataStore.size(); index++) {
Account datum = (Account)dataStore.get(index);
if (str.equals(datum.getName())) {
name = datum.getName();
textArea.setText("Found Account for " + name);
found = true;
}
}
if(!found){
textArea.setText("No Accounts found!");
}
I think that you don't want the else{} inside the for(...) loop because as you navigate through your data structure, many times, your initial if (str.equals(datum.getName())) statement will fail as you have not found the account yet. However, if you eventually find it, you will meet the if(...) condition and tell the user via textArea that you found the account. Then you set a boolean to true that you found it. If you go through the ENTIRE data structure and have not found it, the boolean will still equal false, and you will meet the condition for the second if which is if(!found) after the for loop, and will tell the user that you have searched the entire data structure and have not found the account.
Also, I think your first else if should look more like the code below (I don't know what the method signatures look like for CheckingAccount so some of this is a guess on actual syntax)
else if(source.equals("Add new account")) {
//************* Output
//use constructor below if you have a default constructor aka no paramaters
CheckingAccount account = new CheckingAccount();
//now that you have object linked to account, you can use setters
accountName = JOptionPane.showInputDialog("Enter the account name: ");
//set the name
account.setName(accountName);
String strInitialBalance = JOptionPane.showInputDialog("Enter your initial
balance: ");
initialBalance = Double.parseDouble(strInitialBalance);
//set the balance
account.setBalance(initialBalance);
//dont make a new object now as you did before..just add the object to your arraylist
dataStore.add(index++, account);
}
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(""))) {