I think I may be misunderstanding how to store my information into my array and then to call it for later use.
The following code is to ask a user for how many Cd's they have and allow them to enter the Genre, Artist, and Title. Then it is to go back into the loop if there is more than one cd. I believe that I have everything mostly correct but my output is not right. Whenever entering in for 2 Cd's I will be allowed to enter the first three items in for CD 1 but it will then print CD 2 and just go straight to the end of the program.
-I have posted the code along with what happens when entering 1 CD vs 2 CDs
import java.util.Scanner;
public class RiverCDs
{
public static void main (String args[])
{
Scanner scnr = new Scanner (System.in);
int cdTotal = 0; // user controlled, controls the number of rows.
int col = 3; // constant that controls array col.
String value = " "; // holds input for array.
int intervals = 1;
String [][] list = new String [cdTotal][col];
System.out.println("The River Catalog:\n");
System.out.print("How many CD's do you have: ");
cdTotal = scnr.nextInt();
do
{
if (cdTotal <= 0) // checking for bad data.
{
System.out.print("Must be a number greater than 0.\n");
System.out.print("How many CD's do you have: ");
cdTotal = scnr.nextInt();
}
}while(cdTotal <= 0); // set up to catch more bad data.
System.out.print("\nFor each CD, enter the genre, then the artist, then the title.\n");
for (int i = 1; i <= cdTotal; i++) // incrementing cd based on user input.
{
System.out.print("\nFor CD " + i + ":\n");
while (intervals <= 3)// condition to exit while loop for next cd.
{
System.out.print("Enter: "); // outside of for-loop to Enter three items.
value = scnr.nextLine();
scnr.next(); // clearing buffer so as to to print a double Enter.
for (int r = 0; r < list.length ; r++) // enters row according to how many cdTotal equals.
{
for (int c = 0; c < list[col].length; c++) // enters col in each row up to three.
{
list[r][c] = value;// storing array in value for later use.
}
}
intervals++; // incrementing so as to break loop and print next cd statement.
}
}
System.out.print("\nHere is your catalog:\n");
System.out.printf("\n%-20s" + "%-20s" + "%-20s\n","Genre","Artist","Title");
System.out.println();
for (int r = 0; r < list.length; r++)// accessing list rows
{
for (int c = 0; c < list[r].length; c++)// accessing list col to pull out individual parts of data.
{
System.out.printf("%-20s","%-20s","%-20s",list[r][c],list[r][c],list[r][c]); // constant to check for data in array-
//not working
//System.out.printf("%-20s","%-20s","%-20s",list[1][0],list[1][1],list[1][2]);
}
}
scnr.close(); // turning off scanner to allow no more input.
}
}
1CD-
The River Catalog:
How many CD's do you have: 1
For each CD, enter the genre, then the artist, then the title.
For CD 1:
Enter: top
Enter: cami
Enter: havana
Here is your catalog:
Genre Artist Title
2CD-
The River Catalog:
How many CD's do you have: 2
For each CD, enter the genre, then the artist, then the title.
For CD 1:
Enter: top
Enter: cami
Enter: havana
For CD 2:
Here is your catalog:
Genre Artist Title
It looks like this code is a problem:
for (int r = 0; r < i ; r++) // enters row according to how many cdTotal equals.
{
for (int c = 0; c <= col-1; c++) // enters col in each row up to three.
{
list[r][c] = value; // storing array in value for later use.
}
}
This code sets every value in the array to value, if i is large. And you aren't changing value inside the loop, so everything in your array will be exactly the same thing.
Related
I need help with my java code regarding ascending order display, which I'm receiving error on the temp assignment ..specifically these two assignments listed
Customer1Purchase[i].getProductId() = Customer1Product[j].getProductId();
Customer1Purchase[i].getProductId() = temp;
error reads__[The left-hand side of an assignment must be a variable]
below is my code when, part when user choose option 3:
please let me know if I need to provide more information
I'm new to stalk over flow..... Thanks
c1_pNumber relates to number of purchase by customer1
Condition when Customer Invoice Number is Entered
[c1_pNumber] is size or number of elements in array
Customer1Purchase[i].getProductId() Position of FirstElement
// user option 3 ..... using switch case
case 3:
// allow user input
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Invoice Number: ");
int invoice = scan.nextInt();
// if condition is true it should loop to display arranged data in ascending order
// condition where user input = invoice number in record
if(invoice == c1_InvoiceNumber) {
for(int i=0; i<c1_pNumber; i++) {
for(int j=i+1; j<c1_pNumber; j++) {
if(Customer1Purchase[i].getProductId() > Customer1Purchase[j].getProductId()) {
int temp = Customer1Purchase[i].getProductId();
Customer1Purchase[i].getProductId() = Customer1Product[j].getProductId();
Customer1Purchase[i].getProductId() = temp;
}
}
}
System.out.print("Ascending Order: ");
for(int i=0; i<c1_pNumber-1; i++) {
System.out.println(Customer1Purchase[i]);
}
System.out.print(Customer1Purchase[c1_pNumber-1]);
}
The CEMC is organizing a workshop with an activity involving pairs of students. They decided to assign
partners ahead of time. You need to determine if they did this consistently. That is, whenever A is a partner
of B, then B is also a partner of A, and no one is a partner of themselves.
Input
The input consists of three lines. The first line consists of an integer N (1 < N ≤ 30), which is the number of
students in the class. The second line contains the first names of the N students separated by single
spaces. (Names contain only uppercase or lowercase letters, and no two students have the same first
name). The third line contains the same N names in some order, separated by single spaces.
The positions of the names in the last two lines indicate the assignment of partners: the i-th name on the
second line is the assigned partner of the i-th name on the third line.
Output
The output will be good if the two lists of names are arranged consistently, and bad if the arrangement of
partners is not consistent.
Sample Input 1
4
Ada Alan Grace John
John Grace Alan Ada
Sample Output 1
good
Explanation for Sample 1
Ada and John are partners, and Alan and Grace are partners. This arrangement is consistent.
Sample Input 2
7
Rich Graeme Michelle Sandy Vlado Ron Jacob
Ron Vlado Sandy Michelle Rich Graeme Jacob
Sample Output 2
bad
Explanation for Sample 1
Graeme is partnered with Vlado, but Vlado is partnered with Rich. This is not consistent. It is also
inconsistent because Jacob is partnered with himself.
Here is my work, I wonder why it doesn't work???
import java.util.Scanner;
public class CCCHW4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt(); //how many names
String [][] combo = new String [2][n];
double value = 0;
combo [0] [0] = reader.nextLine();
for (int i = 0; i < n; i++) { //input the names
combo [0] [i] = reader.nextLine();
}
combo [1] [0] = reader.nextLine();
for (int j = 0; j < 4; ++j) { //input the names
combo [1] [j] = reader.nextLine();
}
for (int i = 0; i < n++; ++i) {
if ((combo [0][i]).equals(combo [1][i])) { //check if partner with himself/herself
System.out.println(" same " + combo [0][i] + combo [1][i]);
System.exit(0);
}
}
for (int i = 0; i < n; ++i) { //each combo
for (int j = 0; j < n; ++j) { // each column
int determineValue = 0; //determine if any guy partnered with more than one person
if ((combo [0] [i]+combo [1] [i]).equals(combo [0] [j]+combo [1] [j]) || //check, if partner with two person
(combo [0] [i]+combo [1] [i]).equals(combo [1] [j]+combo [0] [j])) {
determineValue += 1;
}
if (determineValue != 2) { //same combo one time, reversed combo one time, so two.
value += 1;
System.out.println("yes2");
}
}
}
if (value == 0) {
System.out.print("good");
} else {
System.out.print("bad");}
}
}
Below is my solution to your homework exercise.
I first ran a few tests by hand and realized that the program output can never be GOOD if there are an odd number of students, so I added a condition that the entered number of students must be an even number.
My algorithm is to use two, separate, one dimensional arrays rather a single, two dimensional array. I loop through the second array (partners in the below code) and for each "partner", I search the first array (students in the code below) for that "partner". If I find the "partner" in the students array then I check whether the pairs are the same. As soon as I fail to find a matching pair, I exit the loop and the program prints BAD.
Note that I only need to search half of the partners array since if I find matches for all the students in the first half of the array, then the second half must all have matches also.
Also note that I added a lot of checks for valid input, including ensuring that the entered number of students is a positive integer, i.e. not a number with a decimal point or a minus sign. I also check that the correct number of names are entered and that each list of names contains only unique names, i.e. the same name cannot appear more than once in a list. The user is asked to re-enter invalid data, repeatedly, until [s]he enters valid data, i.e. a correct number of students and correct lists of names.
Lastly note that I check the validity of the parameters in methods getNames() and getNumberOfStudents(). I feel it is important since I always remind myself that the Ariane 5 rocket failed because the software did not check the validity of method parameters.
import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;
public class Pairings {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int numberOfStudents = getNumberOfStudents(stdin);
String[] students = getNames(stdin, numberOfStudents);
String[] partners = getNames(stdin, numberOfStudents);
int limit = numberOfStudents / 2;
boolean bad = false;
for (int i = 0; i < limit; i++) {
boolean found = false;
for (int j = 0; j < numberOfStudents; j++) {
if (i != j) {
if (students[j].equals(partners[i])) {
if (partners[j].equals(students[i])) {
found = true;
break;
}
}
}
}
if (!found) {
bad = true;
break;
}
}
if (bad) {
System.out.println("BAD");
}
else {
System.out.println("GOOD");
}
}
private static String[] getNames(Scanner stdin, int number) {
if (number <= 0) {
throw new IllegalArgumentException("Not positive: " + number);
}
Objects.requireNonNull(stdin, "Null scanner.");
String[] names = new String[0];
int count = 0;
do {
System.out.printf("Enter %d unique names (separated by single space)%n", number);
String str = stdin.nextLine();
names = str.split("\\s+");
count = names.length;
if (count != number) {
System.out.printf("You entered %d names and not %d%n", count, number);
}
else {
Set<String> nameSet = new HashSet<String>(number);
for (String name : names) {
if (nameSet.contains(name)) {
System.out.printf("%s appears more than once%n", name);
count = 0;
break;
}
else {
nameSet.add(name);
}
}
}
} while (count != number);
return names;
}
private static int getNumberOfStudents(Scanner stdin) {
Objects.requireNonNull(stdin, "Null scanner.");
String str;
int numberOfStudents;
do {
System.out.print("Enter number of students (even number between 2 & 30): ");
str = stdin.nextLine();
try {
numberOfStudents = Integer.parseInt(str);
if (numberOfStudents < 0) {
System.out.printf("%d is a negative number%n", numberOfStudents);
}
else if (numberOfStudents % 2 == 1) {
System.out.printf("%d is not an event number%n", numberOfStudents);
}
}
catch (NumberFormatException xNumFmt) {
System.out.printf("%s is not a whole number%n", str);
numberOfStudents = 1;
}
} while (numberOfStudents % 2 == 1);
return numberOfStudents;
}
}
So I am writing a program that will allow you to book a seat on a flight. It asks the user how many rows are available, then it makes a 2d array with 4 columns and how ever many rows the user specifies. Then my program prompts the user to choose how man seats he wants and then what row and column he wants those seats to be. then it will change the value of the position in the array form "-" to "X". That all works beautifuly, but I'm running into issues when I am trying to use a method to cancel the reserved seating. I have it so it props the user, if he wants to cancel a seat and how many, then I get the row and column that he wants to cancle. So then it checks to see if that spot in the array has a value of "-" or "X" if it has a "-" it displays a message saying that they need to input a seat that is reserved and if it has a "X" the it changes it to "-" to show that its open. But for some reason if i put in a position that is take or has "X" as a value it says that there isn't, what did i do wrong?
Here is my code:
This is my cancle method
public void CancleSeat(String[][] SC, String can, int c, int r, int Seats, int an){
FillArray(SC);
if (can.equals("No")){
System.out.println("OK, no cancelations for you!");
}
else if (can.equals("Yes")){
System.out.println("How many seats would you like to cancel?");
an = scanner.nextInt();
for (int i = 0; i < an; i++){
System.out.println("What row is your seat in that you would like to cancle?");
r = scanner.nextInt();
r = r - 1;
System.out.println("What colum is your seat in that you would like to cancle?");
c = scanner.nextInt();
c = c -1;
if (SC[r][c].equals("-")){
System.out.println("That seat isn't researved pleas pick a different seat");
System.out.println("What row is your seat in that you would like to cancle?");
r = scanner.nextInt();
r = r - 1;
System.out.println("What colum is your seat in that you would like to cancle?");
c = scanner.nextInt();
c = c - 1;
}
else if (SC[r][c].equals("X") || SC[r][c].equals("x")){
SC[r][c] = "-";
}
}
}
}
and this is what i am using to call it in the driver class.
System.out.println("Would you like to canlce any reservations?");
cancle = scanner.next();
Seeting cancler = new Seeting(numSeatsBooking, row, colum, cancle, openSeats, answer);
cancler.CancleSeat(SeetingChart, cancle, colum, row, numSeatsBooking, answer);
Any help would be greatly appreciated!
Thanks
I'm trying to make a basic program that allows the use to input and remove up to 10 contacts (a [10][4] array supposed to be filled with First Name, Last Name, Phone #, and age). However when I try to input the 5th contact eclipse gives me an error message. I'd like to know why I'm receiving an error message. (I assume it's something to do with the columns since it's whenever i'm inputting something >4, but i'm not sure what exactly.)
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args){
new Lab2 ();
}
// This will act as our program switchboard
public Lab2 (){
Scanner input = new Scanner(System.in);
String[][] personalInfo = new String[10][4];
System.out.println("Welcome to the contacts database.");
System.out.println("Please select a number from the options below");
System.out.println("");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("0: Exit the database.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContact(personalInfo);
break;
case 2:
removeContact(personalInfo);
break;
case 0:
System.out.println("Thank you for using the contact database.");
System.exit(0);
}
}
}
private void addContact(String personalInfo[][])
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println( " Hello user, please enter your contact info. (I.E. First and Last Names, Phone #, and Age. Max 10 Contacts)");
String addedContact = input.nextLine();
int j;
for(int i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j] == null)
{
personalInfo[i][j] = addedContact;
break;
}
}
}
}
private void removeContact(String personalInfo[][]) {
Scanner input = new Scanner(System.in);
System.out.print( " Please enter an existing contact that you would like to remove. ");
String deleteContact = input.nextLine();
int i , j;
for(i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j].equals(deleteContact))
{
personalInfo[i][j] = null;
break;
}
}
}
}
}
Try like this for(j = 0; j < personalInfo[i].length; j++){
First things first:
String[][] personalInfo = new String[10][4];
This statement creates a 2dimensional array of Strings, thus creating an array that is capable of holding an array that is capable of holding strings. (in this case 10 arrays that keep 4 strings each)
Now the error:
String addedContact = input.nextLine();
This line puts the entire line you added in a single string.
Now the loops:
1. The outer loop loops correctly through the 10 arrays of strings.
2. The inner loop does not loop through the '2nd dimension', that is the actual array which will hold your contact. This loop should be as #Kannan Thangadurai described:
for(j = 0; j < personalInfo[i].length; j++){
(add relevant code here)
}
The last error you made is more of a bug, and is in the way you read out the user input. You actually only ever put a string in the first array and so your four contacts that you saved will all be under personalinfo[1] then you try to add another contact in the fifth place of the array that does not exist, thus raising your error.
You're working with jagged array (or array of arrays)
String[][] personalInfo = new String[10][4];
so in order to itterate it you should use different lengths for dimensions (in general case the
required length is personalInfo[i].length):
for (int i = 0; i < personalInfo.length; ++i) // <- outer array
for (int j = 0; j < personalInfo[i].length; ++j) // <- inner length depends on i
if (personalInfo[i][j] == null) {
personalInfo[i][j] = addedContact;
break;
}
This is the code I have right now
for (int i = 0; i <= listOfPeople.length; i++){
String name = scnr.nextLine();
System.out.println("Person " + (i + 1) + ": ");
listOfPeople[i] = name;
}
List of people is a properly declared list of Strings with the length of a value the user sends in. The error that is happening is that when I run the program, I get this:
Person 1:
Jordan
Person 2:
Jordan
Person 3:
Jordan
Person 4:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at RGG.main(RGG.java:20)
I am not quite sure what is wrong, but I have tried removing the = in the for loop declaration, then I get this output:
Person 1:
Jordan
Person 2:
Jordan
Person 3:
After the third prompt, the code moves on and I cant type in anything there.
Does anyone know what might be happening? Thanks in advance!
Remove the = in this expression i <= listOfPeople.length;. Its causing you to access an element of the array that does not exist.
for (int i = 0; i < listOfPeople.length; i++){
String name = scnr.nextLine();
System.out.println("Person " + (i) + ": ");
listOfPeople[i] = name;
}
Full Example:
public class PersonArrayTest {
public static void main(String[] args) {
String[] listOfPeople = new String[5];
assign(listOfPeople);
System.out.println(Arrays.toString(listOfPeople));
}
public static void assign(String[] listOfPeople) {
Scanner scnr = new Scanner(System.in);
for (int i = 0; i < listOfPeople.length; i++) {
String name = scnr.nextLine();
System.out.println("Person " + (i) + ": ");
listOfPeople[i] = name;
}
}
}
With this line
for (int i = 0; i <= listOfPeople.length; i++){
You are advancing one beyond the end of the array, length 3, which has valid indices 0-2. 3 is an invalid index.
When you remove the =, you get the corrected version:
for (int i = 0; i < listOfPeople.length; i++){
which stops after the 2 iteration, which is the end of the array, before you run off the end of the array.
change this the <= sign in forloop
for (int i = 0; i < listOfPeople.length; i++)
I am make an educated guess that you are using Scanner#nextInt to get the input for the length of the array. Something along the lines of this:
String[] listOfPeople = new String[scnr.nextInt()];
I've garnered this because your loop code looks like this:
take input for i == 0
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
But your output shows this:
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
So what actually must be happening is this:
silently advance past whatever scnr is still retaining for i == 0
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
nextInt orphans a new line character. (So will any calls to next_ besides nextLine.) That's why your first input is skipped. Calling scnr.nextLine in the first iteration of the loop just advances the Scanner past the last line.
Change the loop to this:
// skip the last new line
scnr.nextLine();
// < not <=
for (int i = 0; i < listOfPeople.length; i++) {
// prompt before input
System.out.println("Person " + (i + 1) + ": ");
// you don't need that extra String
listOfPeople[i] = scnr.nextLine();
}