I am trying to print from an ArrayList using an ListIterator, i'm pretty sure i'm doing it wrong because it's not working but I don't know how to fix it. All so the line that grabs the part number isn't working, not sure why ;P. Any help is always appreciated :).
package invoice;
import static java.lang.System.out;
import java.util.*;
public class InvoiceTest {
public static void print(){
}
public static void main (String args[]) {
Scanner imput = new Scanner (System.in);
ArrayList lInvoice = new ArrayList() ;
int counter = 0;
int partCounter;
out.println("Welcome to invoice storer 1.0!");
out.println("To start please enter the number of items: ");
partCounter = imput.nextInt();
while (counter < partCounter){
counter++;
out.println("Please enter the part number:");
Invoice invoice1 = new Invoice(); //Makes invoice 1 use the invoice class
String partNumber = imput.nextLine();// sets part number to the next imput
//invoice1.setPartNumber(partNumber);// Sets it to the private variable in invoice.java
lInvoice.add(partNumber);
out.println("Please enter in a discription of the part: ");
String partDis = imput.nextLine();
//invoice1.setPartDis(partDis);
lInvoice.add(partDis);
out.println ("Please enter the number of items purchased: ");
int quanity = imput.nextInt();
//invoice1.setQuanity(quanity);
lInvoice.add(quanity);
out.println ("Please enter the price of the item:");
double price = imput.nextDouble();
//invoice1.setPrice(price);
lInvoice.add(price);
}
ListIterator<String> ltr = lInvoice.listIterator();
while(ltr.hasNext());
out.println(ltr.next());
}
}
There is some other errors in your program.
First, you shoud add a type to your ArrayList. Since you're trying to add int, double and String, I recommend you to create an ArrayList<Object> lInvoice = new ArrayList<Object>() ;
Then just loop with your iterator :
ListIterator<Object> ltr = lInvoice.listIterator();
while(ltr.hasNext()){
out.println(ltr.next());
}
You actually don't print anything within the while loop, because your println() callback is out of the scope of the loop. Fix it like this:
ListIterator<String> ltr = lInvoice.listIterator();
while(ltr.hasNext()) {
out.println(ltr.next());
}
Putting on my psychic debugger hat, I'm guessing you meant to print out a line-item invoice. I'm making some assumptions about the contents of Invoice.java, but I'm guessing the below code is what you really wanted:
Scanner imput = new Scanner(System.in);
ArrayList<Invoice> lInvoice = new ArrayList<Invoice>();
int counter = 0;
int partCounter;
out.println("Welcome to invoice storer 1.0!");
out.println("To start please enter the number of items: ");
partCounter = imput.nextInt();
imput.nextLine();//skips the rest of the line (carriage return)
while (counter < partCounter) {
counter++;
out.println("Please enter the part number:");
Invoice invoice1 = new Invoice(); // Makes invoice 1 use the invoice
// class
String partNumber = imput.nextLine();// sets part number to the next
// imput
invoice1.setPartNumber(partNumber);// Sets it to the private
// variable in invoice.java
out.println("Please enter in a discription of the part: ");
String partDis = imput.nextLine();
invoice1.setPartDis(partDis);
out.println("Please enter the number of items purchased: ");
int quanity = imput.nextInt();
imput.nextLine();
invoice1.setQuanity(quanity);
out.println("Please enter the price of the item:");
double price = imput.nextDouble();
imput.nextLine();
invoice1.setPrice(price);
lInvoice.add(invoice1);
}
ListIterator<Invoice> ltr = lInvoice.listIterator();
while (ltr.hasNext()) {
Invoice next = (Invoice)ltr.next();
out.println(next.getPartNumber()+"\t"+next.getPartDis()+"\t"+next.getPrice()+"\t"+next.getQuanity());
}
Interesting changes:
I'm using a list of Invoice instead a list of strings, and then printing out each one
Scanner.nextInt() will leave the carriage return from its input, so you have to call nextLine() to clear it, or you'll miss the input you really wanted.
Related
My program uses an array: collection[] to hold information on cars. user input is used to add a car to the array using the console. So the user would enter the car's name, year of make, etc. However when it gets added to the array it goes straight into collection[0]. So if there is anything already in collection[0] it will replace it.
I want the user input to be but into the the next null cell in the array to avoid this problem. I have tried to write code that goes through each cell of the array and once it finds a cell which is null it then adds the information into it. However it is not working.
public void addCarInput1()
{
for (int i = 0; i < 1; i++)
if (this.collection[i] = null)
{
this.collection[i].addCarInput();
}
}
Here is a shortened version of addCarInput:
Scanner sin = new Scanner(System.in);
System.out.print("Enter car make: ");
Cmake = sin.nextLine();
System.out.print("Enter car model : ");
Mname = sin.nextLine();
You can try something like this if you want more cars
String shouldContinue = null;
while(true) {
if (shouldContinue.equals("no")) break;
Scanner sc = new Scanner(System.in);
System.out.print("Enter car make: ");
String make = sc.nextLine();
System.out.print("Enter car model : ");
String model = sc.nextLine();
//add car info
addCarInput(make, model);
System.out.print("Enter info for another car? : ");
shouldContinue = sc.nextLine()
}
Why don't you use a LinkedList or an ArrayList object instead of an array?
the add() method will add the elements at the end of the list & not replace the old values
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
http://examples.javacodegeeks.com/core-java/util/arraylist/arraylist-in-java-example-how-to-use-arraylist/
im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}
For my homework, I had to write a program that prompts the cashier to enter all prices and names, adds them to two arrays lists, calls the method that I implemented, and displays the result and use 0 as the sentinel value. I am having difficulty coming up with a for loop in the method, I believe I have the condition right but I am having trouble with the statements. Any help would be greatly appreciated! Thanks.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
System.out.print("Enter Number of Customers");
double salesAmount;
System.out.print("Enter Sales for First Customers");
salesAmount = in.nextDouble();
while(salesAmount != 0)
{
sales.add(salesAmount);
System.out.println("Enter Name of Customer: ");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales, ArrayList<String> customers)
{
String name = "";
double maxSales;
for (int i = 0; i < sales.size(); i++)
{
sales.size(name.get); <== it keeps saying "cannot find the symbol variable get"
}
return name;
}
Don't use maxSales as the maximum in your loop. Use the count of number of customers. Inside the loop, check if sales.get(i) is greater than your current maxSales, and if it is...
(I will edit this and more if you still need. But this should go a long way.)
There are a couple possible issues here, but I'll stick to answering what I think is the question that you've asked.
In your nameOfBestCustomer method, you'll want to loop from 0 to the end of either of your ArrayLists (as they both should be the same size).
for (int i = 0; i < sales.size(); i++)
{
...
}
I'm trying to make a program that will ask for a number of people to go into an ArrayList and then pick a name out of it randomly. The code is working fine but the string asking for name input displays itself twice the first time you run it. Any clue why this happens?
What I want it to display:
Enter a name: ......
What it displays:
Enter a name:
Enter a name: ......
import java.util.*;
class RandomNumGen
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random random = new Random();
ArrayList<String> names = new ArrayList<String>();
int a, b;
System.out.print("\nEnter the number of people: ");
a = input.nextInt();
System.out.println();
for (int i = 0; i <= a; i++)
{
System.out.print("Enter a name: ");
names.add(input.nextLine());
}
b = random.nextInt(a);
System.out.print("\nRandom name: " +names.get(b)+ "\n");
}
}
The issue is that nextInt() just consumes an integer, but not the new-line character inputted when you press Enter.
To solve this you can add
input.nextLine();
after the call to nextInt() so it consumes the new-line character.
Another option would be reading a whole line, and then parsing its content (String) to a int:
a = Integer.parseInt(input.nextLine());
I hate Arrays
So I've been doing some coding and I've come up with an error (out of bounds exception) that I just can't seem to fix. I believe where I am saying 'array1[counter2][counter] = input2.nextLine();' is the problem but I don't know what is wrong! Help, I can't stand these Out of Bounds exceptions
The Idea for the program is an online phone book that you can add contacts, view them, and search by their first name, surname, and phone number.
Here's the code I'm using:
import java.util.Scanner;
import java.awt.*;
public class testMattWalker {
//
public static void main (String[] args){
//Declare all your variables here. Make sure to provide a comment explaining the purpose of each variable
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
boolean go = true;
//Temp VAriables for entry
String firstNameOfEntry = "";
String lastNameOfEntry = "";
String personPhoneNumber = "";
//
//create array
String [][] array1 = new String[5][3];
while (go) {
String choice = "";
System.err.println("\n\n\n\n\n\n\n\n\nDIDGITAL PHONE BOOK 2013");
System.out.println("1- Create phone book\n2- Display phone book\n3- Find person(s) by last name\n4- Find person(s) by first name\n5- Find person(s) by phone number\n6- Exit application");
choice = input.nextLine();
if (choice.equals("1") && counter2 != 6) {
System.err.println("\n\n\n\n\nPHONE BOOK ENTRY CREATOR:");
System.out.println("Please enter the first name of the person you wish to enter: ");
array1[counter2][counter] = input2.nextLine();
counter++;
System.out.println("Please enter the last name of the person you wish to enter: ");
array1[counter2][counter] = input3.nextLine();
counter++;
System.out.println("Please enter the phone number of this person: example:9057773344");
array1[counter2][counter] = input4.nextLine();
counter++;
counter2++;
}else if (choice.equals("2")) {
}else if (choice.equals("3")) {
}else if (choice.equals("4")) {
}else if (choice.equals("5")) {
}else if (choice.equals("6")) {
}
}
}// end of main
}// end of class
I know it's not close to done but I'm the kind of guy who likes to fix everything before moving on so any help would be appreciated! (:
You set the second dimension of your array as 3, but in your code you add 1 to counter 3 times, meaning it goes out of bounds of the array after the first iteration of the code.
As ljgw said array indexes start at 0, so a dimension of 3 means the corresponding indexes are 0,1 and 2.
Remember that array indexes start with 0. So: 5 is already out-of-bounds for counter2.