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]);
}
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 have a program that is supposed to simulate a game of poker in java. I have a method class called Poker and a check class called CheckPoker which calls the methods in the method class. I haven't even been able to check if the algorithmic part works because while asking if the user would like to switch out any cards. The loop should quit after 5 cards have been entered or if the user enters "1" but in running the program, the for loop doesn't quit until 5 card values have been entered and then throws a "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 56" error. I have tried a for loop, a while loop, a do-while loop, but none have seemed to work thus far.
import java.util.*;
public class Poker {
private String[] deck = {
"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA",
"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ", "CQ","CK","CA",
"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ", "HQ","HK","HA",
"S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ", "SQ","SK","SA"};
private List<String> hand = new ArrayList<>();
public Poker(){
Collections.shuffle(Arrays.asList(deck));
}
public void playGame(){
System.out.print("The first five cards are: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
}
System.out.println(" ");
int k = 0;
String j;
List<String> discard = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.next();
if(!j.equals("1")){
j = in.next();
discard.add(j);
k++;
}else{
break;
}
}
List deckList = Arrays.asList(deck);
String[] discard1 = discard.toArray(new String[0]);
for(int l = 0; l<k; l++){
int m = deckList.indexOf(discard1[l]);
String n = deck[m];
deck[m] = deck[l+5];
deck[l+5] = n;
}
System.out.print("Your new hand is: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
hand.add(deck[i]);
}
System.out.println(" ");
}
Try the code below. It seems you were grabbing two cards per iteration and not capturing them all in the ArrayList.
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.nextLine();
if(j.equals("1") {
break;
}
discard.add(j);
k++;
}
Can someone point out what is wrong with my program?
I have done most of it but I can't seem to find what's wrong with it.
It doesn't ask the user for the "enter your grade" prompt for each course.
This is for an array assignment for school. Here is my code.
I am having difficulties figuring out what is wrong with the for loop I made specifically the for loop.
This program is supposed to ask the user for their courses and then the user enters their grades for that course.
If possible, please provide me hints on what I am doing wrong.
import java.io.*;
public class StudentMarks {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
i++;
System.out.println("Please enter course name " + i);
course = br.readLine();
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
}//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
Instead of i++ use
System.out.println("Please enter course name " + (i+1));
you do not need any nested loop
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
instead use
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
HERE is the Full code if you still having trouble understanding it let me know .
import java.io.*;
public class sort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
System.out.println("Please enter course name " + (i+1));
course = br.readLine();
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
}
I think you didnt intend to have the i++ / j++ in your for loops (first statement).
The third “parameter” of the loop head actually tells the program what to do, when it reaches the end of the loop. Therefore you increment twice each time.
Your inner loop (with int j = i--) has a condition that is always false, and so it's body is never executed.
The line of code:
j = i--
isn't as simple as it seems and can be broken down into two lines:
j = i;
i = i - 1;
Note that j is set to the value of i, and only after that does i get decremented. So if j is set to i, and then i becomes i - 1, i will be one less than j. So the condition of the for loop i.e. j < i, will always be false, and so the body of the loop will never be executed.
Example:
i = 5;
j = i--;
this boils down to
i = 5;
j = i; //j is 5
i = i - 1; //i is 4
j < i; //5 < 4 is false, inner for loop not executed
Hope this helps!
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
}
}
I have been working on this for several days and I'm super frustrated. This is my first course in Java so please bear with me on lack of knowledge still. I'm supposed to write a program that contains an array of 10 grades entered by the user and I calculate the average. In particular I'm having problems with what is down below.
You should not read doubles numbers from the user, you should read a string. Here is the process:
Read a string from the user
trim the string and get the length
if the length <1 then the user hit and you get out
if the length is >0 then you convert the string into a double using
d =Double.parseDouble(S);
So far I just have this. I have been adding and deleting a lot of coding to this for the past week. And I still cant seem to get it to work. Any help would be much appreciated!
import java.util.*;
import java.io.*;
public class Arrays {
public static void main(String[] args) {
double d = 0;
final int SIZE = 10;
Scanner reader = new Scanner(System.in);
String[ ] grades = new String[SIZE];
System.out.println("Please enter up to 10 grades.");
for (int i = 0; i < grades.length; i++){
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine( );
}
System.out.println("\nNumber of valid grades entered: " + grades.length);
}
}
Try this
for (int i = 0; i < grades.length; ){
System.out.print("Grade " + (i + 1) + ": ");
String str = reader.nextLine();
if(str.trim().length() > 0){
try{
grades[i] = Double.parseDouble(str);
i++;
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
System.out.println("\nNumber of valid grades entered: " + i);
IMHO i think grades should be an array of double ie
double[] grades=new double[SIZE];
You can try it in following way
int correctGrades=0;
double[] grades=new double[SIZE]; //Create array of double instead of String
for (int i = 0; i < SIZE; i++){
System.out.print("Grade " + (i + 1) + ": ");
String str=reader.nextLine();
if(str.length() > 0){ // If length is greater than 0 then its correct grade
grades[i]=Double.parseDouble(str);
correctGrades++;
}
}
System.out.println("\nNumber of valid grades entered: " + correctGrades);
As per my understanding this should be your for loop
for (int i = 0; true; i++) {
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine();
if (grades[i].equals("")) {
break;
}
//check for number format exception if user enters invalid input
try {
d = Double.parseDouble(grades[i]);
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
}
System.out.println("The value of double entered is : " + d);
}
Here you run the loop for infinite number of times but with every loop you check the user input.
Now if the user enters an empty string you exit the loop using the break statement