Working on a program dealing with encapsulation having trouble adding the user input to the array. And most likely there are other problems in here as well. One being the displaying the output when the user enters option 3. Also, I have no idea how to tell the user that they can't add any more to the bag unless they remove an item. I was just gonna work on figuring out adding and display before I even worry about removing.
import java.util.ArrayList;
import java.util.Scanner;
class Bag {
private String[] bag = new String[5];
public String[] bag() {
return bag;
}
public void add(String bag) {
for (int i = 0; i < bag.length(); i++) {
//...
}
return;
}
public void remove(String bag) {
return;
}
void display() {
System.out.println("The contents are: " + this.bag());
}
}
Here is the second class:
import java.util.ArrayList;
import java.util.Scanner;
public class testBag {
public static void main(String[] args) {
cart obj = new cart();
int menu;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList<testcart> cart = new ArrayList<>();
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while (menu != 4) {
switch (menu) {
case 1:
while (choice != 2) {
System.out.println("What do you want to enter: ");
String bag = input.next();
obj.add(bag);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
break;
case 2:
System.out.println("Enter item to Remove: ");
friends.remove(input.next());
break;
case 3:
for (int i = 0; i < obj.bag().length; i++) {
obj.display();
}
break;
}
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All items ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
}
}
Your Bag class has to have a counter for how many bags it already has, and store a new bag in the corresponding position and increment it.
To display the bags you cannot System.out.println the array directly
To remove you need to loop through all the bags and shift them left from the point where you found the one to remove.
Implementing all of this in your Bag class:
public class Bag {
private String[] bag = new String[5];
private int count = 0; //the new count here
public void add(String bagToStore) {
if (count < bag.length){
bag[count] = bagToStore; //store the new bag in the current position
count++; //then increment it
}
}
//the remove has more logic because it has to shift the bags if it removes one,
//not to leave wholes in the array
public void remove(String bagToRemove) {
boolean found = false;
for (int i=0;i < count; ++i){
if (bag[i].equals(bagToRemove)){ //to compare Strings you must use equals
found = true;
}
if (found && count < bag.length){
bag[i] = bag[i+1];
}
}
if (found) count--;
}
void display() {
for (int i = 0; i < count; ++i) //the display has to be done with a for
System.out.println("The contents are: " + bag[i]);
}
}
Your main class would now have to be adjusted as well:
public static void main(String[] args) {
Bag obj = new Bag();
int menu, choice = 0;
Scanner input = new Scanner(System.in);
do {
//only print the menu once, you can use a do while for that
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All");
System.out.println(" 4. Exit ");
menu = input.nextInt();
switch (menu) {
case 1:
while (choice != 2) {
System.out.println("What do you want to enter: ");
obj.add(input.next()); //you call add with input.next as well if you want
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
break;
case 2:
System.out.println("What do you want to remove: ");
obj.remove(input.next()); //just call the remove method on Bag
break;
case 3: obj.display(); break; //call the display you already implemented!
}
} while (menu != 4);
}
There are few issues in your implementation of Bag class
You have named String array to store your elements as bad and parameter of add method also as bag, so within add function bag is treated as String rather than String array.
you are not checking the current size of bag before adding elements into bag, you can create a variable named bag and increment it, whenever you add element and decrement it whenever you remove element.
In display method you are printing string array directly instead of elements of array.
I have updated your class by correcting these mistakes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class Bag
{
private String bag[] = new String[5];
int size = 0;
Scanner scanner = new Scanner(System.in);
String[] array = new String[2];
public String[] bag(){
return bag;
}
public void add(String item)
{
if( size < bag.length)
{
bag[size] = item;
size++;
}
else
{
System.out.println("Bag is full remove item before new insertion");
}
return;
}
public void remove(String item)
{
}
void display(){
System.out.println("The contents are: " + Arrays.toString(bag));
}
}
Related
I've checked everything but still duplicate the last array for some reason.
What seems to be the problem?
In the Program, the first thing is to ask a user to input array size, then input numbers to that size.
Next, the code shall remove the duplicate number that a user inputted.
Lastly, the output will display the elements of the array without any duplicate.
Below is the program/code for the same:-
import java.util.Scanner;
public class Finals
{
private static Scanner sc;
public static void main(String[] args)
{
int tao, hayop, counter, bilang = 1, result, taonghayop;
sc = new Scanner(System.in);
System.out.print("Enter array size: ");
int userInput = sc.nextInt();
int userInput1 = userInput;
int[] userDatabase = new int[userInput];
for(counter=0;counter<userInput;++counter)
{
System.out.print("Enter array elements of index " +bilang +": ");
userDatabase[counter] = sc.nextInt();
bilang++;
}
for(tao=0;tao<userInput;++tao)
{
for(hayop=tao+1;hayop<userInput;)
{
if(userDatabase[tao] == userDatabase[hayop])
{
for(taonghayop = hayop; taonghayop<userInput;taonghayop++)
{
userDatabase[taonghayop] = userDatabase[taonghayop+1];
}
userInput = userInput-1;
}
else
hayop++;
}
}
System.out.print("The number(s) are: " + userDatabase[counter]);
for (result=0; result<=userInput1; result++)
{
if (result<userInput1)
{
System.out.print(" ");
System.out.print(userDatabase[result]);
System.out.print(",");
}
else if(result==userInput1)
{
System.out.print(" and ");
System.out.print(userDatabase[result]);
System.out.print(".");
break;
}
}
}
}
This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 6 years ago.
I'm trying to write a simple program using an ArrayList that adds values, removes values, and prints values. However, I'm having an issue with removing values that the user inputs. The user should input a designated amount of values (determined by the user) and then the program should remove those values (if there are duplicates then it should just remove the first instance of the number which is fine). It's not removing the values and in some cases removes one value. I'm a bit confused as to where my code is bugged. Here is my code for remove values:
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
And here is my full code:
public class Main {
private static ArrayList<Integer> arrayList = new ArrayList<Integer>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
printOptions();
int option = scanner.nextInt();
while (option != 0) {
switch(option) {
case 1:
addVals();
printOptions();
option = scanner.nextInt();
break;
case 2:
removeVals();
printOptions();
option = scanner.nextInt();
break;
case 3:
printVals();
printOptions();
option = scanner.nextInt();
break;
case 4:
printOptions();
printOptions();
option = scanner.nextInt();
break;
default:
System.out.println("Not a valid option, please enter again:");
option = scanner.nextInt();
break;
}
}
}
private static void addVals() {
System.out.println("How many values would you like to add?");
int amountToAdd = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToAdd + " values:");
for(int i = 0; i < amountToAdd; i++) {
int vals = scanner.nextInt();
arrayList.add(vals);
}
}
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
private static void printVals() {
for(int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i) + " ");
}
System.out.println();
}
private static void printOptions() {
System.out.println();
System.out.println("Program options: ");
System.out.println("1. Add values\n2. Remove values\n3. Print values\n4. Print options\n0. Exit\n");
System.out.println("\nWhat would you like to do? (enter an option):");
}
}
arrayList.remove(i) removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
that is the bug your code
for more details refer below link
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int) ,
I am not able to read and add student records from an input file into an existing array.
The original array size is 10. When the array is full, its size is to be doubled.
If the input file contains 25 records, my array shows only the last 5 records. I know my array expansion coding is incorrect, and I am unable to resolve. Here are my classes:
import java.util.*;
public class ClassPeriod {
private int myNumStudents;
private Student[] myStudents;
private String myClassName;
int N = 10;
public ClassPeriod(String classname){
myClassName = classname;
myNumStudents = 0;
myStudents = new Student[N];
}
// add the Student to the myStudents array. If the array is full, create a new
// one twice the size of the current one. Update myNumStudents accordingly.
public void addStudent(Student st){
for (int i=0; i<1; i++){
if (myNumStudents == 10 || myNumStudents == 20) {//student array size is 10, if 10 is reached, double its size
N = 2*myNumStudents;
myStudents = new Student[N];
}
switch (myNumStudents)
{
case 0: myStudents[0] = st; break;
...
...
case 24: myStudents[24] = st; break;
default: break;
}
myNumStudents++;//increment myNumStudents by 1
}
for (int j=0;j<N;j++){
System.out.println("Students: " + myStudents[j]);
}
}
public Student[] getStudents(){
System.out.println("myNumStudents: " + myNumStudents);
Student temp[] = new Student[myNumStudents];
for (int i=0; i<myNumStudents; i++){
temp[i] = myStudents[i];
}
System.out.println("temp: " + temp.length);
return temp;
}
public String toString(){
String s = new String(myClassName + "\n");
int i;
for (i=0; i<myNumStudents-1; i++)
s += myStudents[i].toString() + "\n";
s += myStudents[myNumStudents-1];
return s;
}
}
and
import chn.util.*;
import java.util.Properties;
import java.util.Enumeration;
import java.util.*;
public class ArrayRecordsSortSearchApplication {
private static final String STUDENT_FILENAME = "students25.txt";
public static void main(String args[]) {
Student[] sortedStudents = null;
ClassPeriod p1 = new ClassPeriod("PERIOD 1");
readClass(p1);
ConsoleIO console = new ConsoleIO();
char choice;
do {
showMenu();
choice = console.readLine().charAt(0);
System.out.println();
switch (choice) {
case '1':
showStudents(p1.getStudents());
case '2':
break;
default:
System.out.println("That's not a choice");
break;
}
} while (choice != '2');
}
public static void showMenu() {
System.out.println();
System.out.println("1) Show students in original order");
System.out.println("2) Quit?");
System.out.print("choice: ");
}
public static void showStudents(Student[] studs){
System.out.print("studs.length: " +studs.length +"\n");
for (int i=0; i<studs.length; i++)
System.out.println(studs[i]);
}
public static void readClass(ClassPeriod p1){
System.out.println("Please wait while data file loads...");
FileInput infile = new FileInput(STUDENT_FILENAME);
do {
int id = infile.readInt();
double gpa = infile.readDouble();
String name = infile.readLine();
Student s = new Student(name,id,gpa);
p1.addStudent(s);
} while ( infile.hasMoreLines() );
infile.close();
}
}
This assignment looks like the implementation of ArrayList. As soon as the size of the old array is exceeded, the new array needs to be created of double size and copy the elements of the old array into a new array and then add the new element to be inserted.
In your code:
if (myNumStudents == 10 || myNumStudents == 20) {//student array size is 10, if 10 is reached, double its size
N = 2*myNumStudents;
myStudents = new Student[N];
....somewhere here you should actually copy all the elements from the old array as first elements of the new array and then insert the new element to be inserted in array.
}
Basically I have to prompt a user to enter 10 string values, and then in another loop print them in ascending order, then in a final loop, print them in descending order. My array is bringing back null, obviously because I am not prompting users to enter actual information into the array object. I am really stuck on this. I know I need to somehow reference the "userStrings[]" array in my first while loop. I keep researching and keep getting integer loops questions and For loops. This has to be a while loop. I just can no figure out how to get the userStrings[] to actually fill up when the user enters the values. How do I get it linked in the loop?
public class HomeWork10
{
public static void main(String[] args)
{
String[] userStrings = new String[10];
int count = 0;
int count2 = 0;
while (count < 10)
{
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
count++;
}
while (count2 < 1)
{
System.out.println(Arrays.asList(userStrings));
count2++;
}
}
}
You are not putting the values in the String[]
Do it like this:
while (count < 10) {
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
userStrings[count] = userInput;
count++;
}
Also, declare Scanner input = new Scanner(System.in) outside your while() {...}
See below code snippet may solve your problem.
package com.suresh;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class HomeWork10 {
public static void main(String[] args) {
String[] userStrings = new String[10];
int count = 0;
System.out.println("\t Reading Array Elements ");
while (count < 10) {
System.out.print("\t Please enter a string value : ");
Scanner input = new Scanner(System.in);
userStrings[count] = input.next();
count++;
}
System.out.println("\t PRINTING ORIGINAL ARRAY OF ELEMENTS ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
Collections.sort(Arrays.asList(userStrings), new StringAscComparator());
System.out.println("\t ASCENDING ORDER ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
System.out.println("\t DESCENDING ORDER ");
Collections.sort(Arrays.asList(userStrings), new StringDescComparator());
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
}
static class StringAscComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
static class StringDescComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
}
You created the array with 'String[] userStrings = new String[10];' and inside your while loop to access it you need to do something like this 'userStrings[0] = input.next()' This says the first item in the array userStrings will be set to input.next(). I'm not great at java so I'm not sure what input.next() will do though.
I'm having problems on how and where to put arrays.
I figured out how and where to put a loop so it will keep on gathering multiple user data that will be stored inside the arrays but I don't know where to put arrays. There will be an array for product numbers, an array for product name, and an array for price.
import java.io.*;
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static void main(String args[])throws Exception
{
int y = 0;
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code =
Integer.parseInt(a.readLine());
System.out.println("");
if(code==l)
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices")
System.out.print("Enter product number:
") ;
int prodnum
Integer.parseInt(a.readLine());
System.out.println("")
}
if(code==3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}}}}
First of all, where do you get this l (lowercase L) value in your for loop? Shouldn't this be 1 (number one)? Furthermore, it would be even better if it is 0 (zero) so you can use it as an index for your array.
Second thing, what's the point of int y = 0'? You are not using y anywhere in your program.
int y = 0;
for(int x = l; x <= 100; x++)
Change it to:
for(int x = 0; x < 100; x++)
Since you want to have 3 separate arrays, you should have 3 separate indexes to keep track of them.
Now let's see how to initialize an array to store the data. You should declare the size as a variable at the top of your class (or locally in your main()) to make it easier to change it later across your program. You can do the same with your array. Declare it inside your class or locally inside the main(). I will show you how to declare both outside of the class, but you should try it the other way too for practice.
Now remember, when using arrays you have to know the size of the array in advance as soon as you create it and you cannot change that size after. This means only that many elements can fit inside the array. If you want variable size structures, check out some of the answers with ArrayLists.
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static int size = 100; // now you only change this number and everything works
public static int[] productNumbers = new int[size];
public static String[] productNames = new String[size];
public static int[] productPrices = new int[size];
public static void main(String args[]) throws Exception
{
int prodnumIndex = 0; // index for tracking product numbers
int prodnameIndex = 0; // index for tracking product names
int prodpriceIndex = 0; // index for tracking product prices
for(int x = 0; x < size; x++)
{
// ... your code...
// ...
int prodNum = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodnumIndex < productNumbers.length) {
productNumbers [prodnumIndex] = prodnum;
prodnumIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
String prodName = a.readLine();
// check if we didn't reach our maximum size
if(prodnameIndex < productNames.length) {
productNames [prodnameIndex] = prodName ;
prodnameIndex++; // increment
} else {
System.out.println("Cannot add product name. Reached maximum amount.");
}
// ...
int prodPrice = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodpriceIndex < productPrices.length) {
productPrices [prodpriceIndex] = prodPrice ;
prodpriceIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
}
Another way you can achieve this is to create an object called Product that will contain the properties you need and then have an array of that object.
class Product {
int num;
String name;
int price;
Product(int num, String name, int price) {
this.num = num;
this.name = name;
this.price = price;
}
}
// ...
// declare your array of `Product` objects...
Product[] products = new Product[size];
// ...
// then you can do something like
System.out.println("Enter product number:");
int prodNum = Integer.parseInt(a.readLine());
System.out.println("Enter product name:");
String prodName = a.readLine();
System.out.println("Enter product price:");
int prodPrice = Integer.parseInt(a.readLine());
products[INDEX] = new Product(prodNum, prodName, prodPrice);
// ...
Also, consider using a double of a float for the product price since it is more realistic representation of actual products.
Do you have to use an array and "if" statements?
Common practice is to use a List as switch statement:
int[] productArray = new int[100];
List<Integer> productList = new ArrayList<Integer>();
for(int x=1;x<=100;x++) {
switch (code){
case 1:
productArray[x-1] = Integer.parseInt(a.readLine());
productList.add(new Integer(a.readLine()) );
break;
default:
System.out.println("Invalid")
break;
}
}
You should use a List instead of an array, because you don't know a priori the length for them.
A List allows you to dinamically add an element as soon as you got it, so you should "put the array" under the user input.
List<String> names = new ArrayList<String>(); //<-- do the same for price(Integer) and product number (Integer)
public static void main(String args[]) throws Exception) {
//...
if(code==1) //<-- This was a l, check again your code.
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
names.add(prodname); //<-- add value to ArrayList
System.out.print("Price: ");
int price = Integer.parselnt(a.readLine());
System.out.println("");
}
//...
}
To print the array content you just need to iterate over the ArrayList:
for(String prodname: names)
System.out.println(prodname); //<-- This will print all your product names
public class DataInsideArrays {
public static DataInputStream a = new DataInputStream(System.in);
List<String> productname=new ArrayList<String>();
public static void main(String args[]) throws Exception {
// rest of your code...
if(code == 1) {
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
////////////////////////to store data place arraylist here/////////////////////////////
productname.add(prod);
///////////////////// //same way use arr to store price and product no
} else if(code == 2) {
System.out.println("Display List of Products-Prices") ;
System.out.print("Enter product number:") ;
int prodnum=Integer.parseInt(a.readLine());
System.out.println("");
}
if(code == 3) {
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
}
}
Here's the correct codes for the output I want. Maybe is there any other way I can get the same output of this with different coding?
import java.io.*;
import java.util.ArrayList;
public class DataArrays
{
public static DataInputStream a = new DataInputStream(System.in);
public static void main(String args[])throws Exception
{
ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
ArrayList<String> prodName = new ArrayList<String>(100);
ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
ArrayList<Integer> prodPay = new ArrayList<Integer>(100);
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code = Integer.parseInt(a.readLine());
System.out.println("");
int y = 1;
if(code==1)
{
System.out.print("") ;
System.out.println("Product number: "+ x);
prodNum.add(x); //this brings 1st input to array element #0 which is not needed
prodNum.add(x);
System.out.print("Product name: ");
String prodname = a.readLine();
prodName.add(prodname); //this brings 1st input to array element #0 which is not needed
prodName.add(prodname);
System.out.print("Price: ");
int prodprice = Integer.parseInt(a.readLine());
prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed
prodPrice.add(prodprice);
System.out.print("Payment: ");
int prodpay = Integer.parseInt(a.readLine());
prodPay.add(prodpay); //this brings 1st input to array element #0 which is not needed
prodPay.add(prodpay);
System.out.println("");
System.out.println("Start New Transaction:");
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices");
System.out.print("Enter product number: ");
int i = Integer.parseInt(a.readLine());
i = prodNum.get(i); //this gets the data stored in the arraylist. Assuming it starts with 1 and above
prodNum.set(1, i);
System.out.println("");
System.out.println("Product name: "+ prodName.get(i));
System.out.println("Product price: "+ prodPrice.get(i));
System.out.println("Product payment: "+ prodPay.get(i));
System.out.println("");
System.out.println("Start New Transaction:");
}
else if(code>=3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
else if(code==0)
{
System.out.println("Program will end");
break;
}}}}
Thank for helping me guys. Really appreciated it.