First off I am aware of ArrayLists and do not want to use them for this program. I am working on a program for a local zoo (very beginning stages and will not be the final version). It takes user input and allows them to enter animals and the foods they eat. My program works fine if I enter one food at a time, but what I am struggling with is figuring out how to handle user input where they add more than one food. (Prompts will guide them to enter food separated by commas, however some users may just use spaces in between and I need to account for that either by an error message or simply accepting it and CSV.) Is there a way to do this and later retrieve the values adding commas back in? Sorry I am pretty new to Java, thanks for any help!
Code for the user input:
//create array
static String[][] animalFood;
String[][] addArray(int x) {
animalFood = new String[x][2];
Scanner in = new Scanner(System.in);
//loop through array and add amount of items user chose
for (int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the food the animal eats: ");
animalFood[row][1] = in.nextLine();
}
System.out.println("Thank you for adding information to the zoo!");
System.out.println("You entered the following information: ");
//loop through and print the informationa added
for(int i = 0; i < animalFood.length; i++)
{
for(int j = 0; j < animalFood[i].length; j++)
{
System.out.print(animalFood[i][j]);
if(j < animalFood[i].length - 1) System.out.print(" - ");
}
System.out.println();
}
Code for the search function:
String[][] searchArray(String name) {
String matchResult = "There was no " + name + " found in the zoo!";
String itemToMatch = name.toUpperCase();
String arrayItem = "";
String food = "";
for (int i = 0; i < animalFood.length; i++) {
arrayItem = animalFood[i][0];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[i][1];
}
else {
//nothing found
}
}
System.out.println(matchResult);
if (food != null) {
System.out.println(food);
}
return animalFood;
}
You can use the split() method of String to break it into an array of strings separated by a given delimiter.
for(int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the foods the animal eats: ");
//all of the foods separated by commas
String[] foods = in.nextLine().split(",");
for(int i = 0; i < foods.length; i++) {
animalFood[row][i + 1] = foods[i];
}
}
You would have to increase the max index of the second dimension of animalFood, though, to account for multiple foods (or, although this is more complicated, you could dynamically resize the array by copying it into an array with a greater max index).
For the search, you would have to nest another loop to list all of the items.
for (int i = 0; i < animalFood.length; i++) {
arrayItem = animalFood[i][0];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats ";
//Iterates over the foods it eats
for(int j = 1; j < animalFood[i].length; j++) {
//If this is the last food in the list
if(j == animalFood[i].length - 1) {
matchResult += "and " + animalFood[i][j] + ".";
}
else {
matchResult += animalFood[i][j] + ", ";
}
}
}
else {
//nothing found
}
}
Related
import java.util.Scanner;
public class Search {
static Scanner scanner = new Scanner(System.in);
static Scanner kb = new Scanner(System.in);
static Scanner kb2 = new Scanner(System.in);
public static void main (String[] args)
{
int choice;
System.out.print("Choose a number of students: ");
int n = scanner.nextInt();
String name[] = new String[n+1];
String course[] = new String[n+1];
int ID[] = new int[n+1];
for(int i=1;i <= n; i++)
{
System.out.print("Enter ID number " + i + ": ");
ID[i] = scanner.nextInt();
System.out.print("Enter Student name " + i + ": ");
name[i] = kb.nextLine();
System.out.print("Enter Student course " + i + ": ");
course[i] = kb2.nextLine();
System.out.println("----------------------------------------");
}
do
{
choice = menu();
if(choice == 1)
{
sortID(ID);
printValues(ID);
}else if(choice == 2)
{
nameSort(name,n);
printName(name,n);
}else if(choice == 3)
{
}
}while(choice !=0);
}
public static int menu()
{
System.out.print("\n1. Sort by ID\n2. Sort by Name\n3. Search by ID\n4. Search by Name\n5. Search by Course\n6. Display Records In table Form.\nYour Choice: ");
return scanner.nextInt();
}
public static void sortID(int []id)
{
int temp;
int index, counter;
for (counter=0; counter < id.length -1; counter++) {
for (index=0; index < id.length - 1 - counter; index++) {
if (id[index] > id[index+1]) {
temp = id[index];
id[index]=id[index+1];
id[index+1]=temp;
}
}
}
}
public static void printValues (int[]array) {
System.out.println ("\nSorted Id Number: ");
for(int i = 1; i < array.length; i++){
System.out.print ("\n" + array[i]);
}
}
public static void printName (String[]array,int a) {
for (int i = 0; i <= a - 1; i++)
{
System.out.print(array[i] + ", ");
}
}
public static void nameSort(String[] name,int a)
{
String temp;
for (int i = 0; i < a; i++)
{
for (int j = i + 1; j < a; j++) {
if (name[i].compareTo(name[j])>0)
{
temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
}
}
The sorting works on the id but i have problems in my names it wont push through the bubble sort and say its null, im just starting learning this language and it would be a great help. Ive been working on this since last night and ive tried transffering it under the if else(choice == 2) still it says null.
Choose a number of students: 2
Enter ID number 1: 123
Enter Student name 1: Mark JAw
Enter Student course 1: JSJS
----------------------------------------
Enter ID number 2: 221
Enter Student name 2: Ak akw
Enter Student course 2: jdj
----------------------------------------
1. Sort by ID
2. Sort by Name
3. Search by ID
4. Search by Name
5. Search by Course
6. Display Records In table Form.
Your Choice: 1
Sorted Id Number:
123
221
1. Sort by ID
2. Sort by Name
3. Search by ID
4. Search by Name
5. Search by Course
6. Display Records In table Form.
Your Choice: 2
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.compareTo(String)" because "name[i]" is null
at Search.nameSort(Search.java:95)
at Search.main(Search.java:41)
PS C:\Users\Bingus\Documents\Projects>
String name[] = new String[n+1];
Suppose for example that you read in a value of 3 for n. This code means that you will allocate 3+1 = 4 elements in name (and likewise in the other arrays). You do not want to allocate 4 elements. You will read 3 names, so you want to allocate 3 elements.
The valid indices for your array will be 0, 1, 2 and 3. You do not want 3 to be a valid index for your array. You want only 0, 1 and 2 to be valid indices, which if you count, you will notice makes 3 different indices.
for(int i=1;i <= n; i++)
In this loop, you will use values of 1, 2 and 3 for i, and thus assign to indices 1, 2 and 3 of name (as well as the other arrays). You do not want to do this. The result is that name[0] will remain null. You want to start the loop at 0 so that you use every element of the arrays. You want to use i < n as your loop condition, because once you correctly only have n elements in the array, n is no longer a valid index.
for (int i = 0; i < a; i++)
{
for (int j = i + 1; j < a; j++) {
if (name[i].compareTo(name[j])>0)
When the exception happens, it happens because you correctly start scanning the array from the beginning, but have incorrectly filled (and sized) the array. You pull a null value out of the array (that shouldn't be there) and try to .compareTo another value (which doesn't work, because you can't call a method on a null). A similar problem would occur (if you got that far) in your other sorting method.
(Unless it is for an assignment, you should not implement sorting yourself. You should use java.util.Arrays.sort.)
I keep getting an error with my code specifically at
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
the error tells me "; expected" what am I doing wrong here?
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = 0;
numLines = scnr.nextInt();
System.out.println();
ArrayList lines = new ArrayList();
scnr.nextLine();
int i = 0;
do{
System.out.println("Enter your text: ");
String text = scnr.nextLine();
ArrayList<String> input = new ArrayList<String>();
i++;
for (i = 0; i < numLines; i++)
{
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
}
for (String element: ArrayList<String> Lines)
{
System.out.println(element);
}
} while(i != 0);
As you have
ArrayList<String> input = new ArrayList<String>();
within your loop, it means that it will get re-declared and initialised for every iteration of that loop, so move this declaration to before your do
Next, to add to this loop, use add method
String text = scnr.nextLine();
input.add (text);
To simplify, you do not need a do as you have a number of times that you want to loop
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = scnr.nextInt();
System.out.println();
scnr.nextLine();
ArrayList <String> lines = new ArrayList <> ();
for (int i = 0; i < numLines; i++) {
System.out.println("Enter word...");
String text = scnr.nextLine();
lines.add(text);
}
To print your list, you can then do
for (int x = 0; x < lines.size(); x++) {
System.out.println (lines.get(x));
}
output
how many lines of text do you want to enter
5
Enter word...
one
Enter word...
two
Enter word...
three
Enter word...
four
Enter word...
five
one
two
three
four
five
I want to make an ArrayList of a list of characters.
Right now I have this code:
Scanner scannerMcScannersonTM = new Scanner(System.in); //This is trademarked.
String[] inputs = new String[5];
List<List<char>> list = new ArrayList<List<char>>();
for(int i =0; i < inputs.length; i++){
System.out.println("Enter pair number " + (i+1) + " separated by a space");
inputs[i] = scannerMcScannersonTM.nextLine();
for(int j = 0; j < inputs[i].length(); i++){
list[i] = inputs[i].toChar(); //it is clear that I don't know what I am doing lol
}
}
Thanks for your help! :D
Scanner scannerMcScannersonTM = new Scanner(System.in); //This is trademarked.
//you do not need this if you know the size and not using inputs afterwards.
String[] inputs = new String[5];
// java collections can only contain non-primitive types, hence, use Character instead of char
List<List<Character>> list = new ArrayList<>();
for(int i=0; i < inputs.length; i++) {
System.out.println("Enter pair number " + (i+1) + " separated by a space");
String inputs[i] = scannerMcScannersonTM.nextLine();
// .toCharArray() method on string does exactly what it says.
// and Arrays.asList(.. an array ..) will convert the array to a List!
list.add(Arrays.asList(inputs[i].toCharArray()));
}
Problem:
How do I reprint the for-loops output, outside the loop? Need help to figure it out. what seems to be the error?
Research effort:
**import java.util.*;
public class Admin {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList <String> title = new ArrayList<>();
String n = in.nextLine();
int i = 0;
int j = 0;
while(!n.equals(" ")){
System.out.println("Enter a movie title");
title.add(n);
n = in.nextLine();
}
for(;i < title.size(); i++){
System.out.println("[" + i +"]" +title.get(i));
}
int [] price = new int [title.size()];
for(;j < price.length; j++ ){
System.out.println("Enter price for");
price[j] = in.nextInt();
System.out.println("Price for ["+j+"] is "+ price[j] );
}
//the problem
System.out.println("["+ i+"]"+title.get(i)+" Price: "+price[j] );
}
}
every time I run it after the loops, error shows up
Expected Result: is that it will print the "i" and "title[i]" together with the "j" and "price[j]" both outside it's loops
If I understood you correctly you want to see something like this:
[0]MovieTitle1 Price: MoviePrice1
[1]MovieTitle2 Price: MoviePrice2
There are some Problems: At first, you are going to get an IndexOutOfBoundsException,
because i and j have been increased to title.size(). This is because of the two for-Loops.
In my example this means that i == 2 and j == 2 are true after execution of both for-Loops has happened.
The title ArrayList and the price Array know the Entrys 0 and 1 (in my example) - you are trying to access Entry 2 which is out of bounds.
A possible solution would be to change this:
System.out.println("["+ i+"]"+title.get(i)+" Price: "+price[j] );
to something like this:
for(int n = 0; n < title.size(); n++) {
System.out.println("[" + n + "]" + title.get(n) + " Price: " + price[n]);
}
So the problem that I am currently running into is that the statement "Enter your command (reverse, replace first, replace last, remove all, remove)" is printing twice after I go through all the steps.
What I believe is happening is the loop is executing twice but I don't know why. Any help would be appreciated in solving this problem. Sorry in advance if my code formatting is bad still learning how to properly format.
import java.util.Scanner;
public class StringChangerenter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
// While loop
while (!command.equalsIgnoreCase("quit")) {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
// Bracket for while loop
}
}
}
The reason you are getting two entries after you've processed a character, is that you have not fully read the line containing the character.
Specifically, you use keyboard.nextInt(); in the upper branch, and keyboard.next(); in the lower branch. While these read the next integer and character, respectively, they do not process the end of line marker.
Then when you reach the top of the loop, you call keyboard.nextLine() which processes whatever characters occurred after the int (or character, in the remove all case) until the end of line marker. With the expected user input, that's just an empty string.
To fix this, you need to ensure you read all the way through the keyboard.nextLine() in the cases where you are reading only integers, or a single character.
what is happening is, the condition for you while loop is
while (!command.equalsIgnoreCase("quit"))
which in english mean, as long as command is not equal to "quit" then run this loop.
Inside the loop, command is never actually set to "quit". ex if I give input string as "abcde" and ask to remove "c" at position 1.
Then your logic sets command to "remove" here
command = keyboard.nextLine();
and then prints the final value as "abde". Now when the loop ends, command is still "remove" and hence the loop executes again.
A possible solution is to explicitly ask the user if he wants to retry using a do while loop. Also just a tip, i see you have used nextInt. It is advisable to use a nextLine immediately after next int. see this for the reason why: Java Scanner doesn't wait for user input
this is what you code would be if you explicitly took user consent if you want to run any more commands:
public static void main (String[] args) throws java.lang.Exception
{
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
String retry = "";
// While loop
do {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
keyboard.nextLine();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
System.out.println("Do you want to go again?");
retry = keyboard.nextLine();
// Bracket for while loop
}while("yes".equalsIgnoreCase(retry));
}