Problems with my for loops printing out my arrays - java

can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;
import java.util.Scanner;
/**
*
* #author Anders
*/
public class Assignment91 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String studName = "Anders";
int counter = 1;// i think the problem is here
int answer = 1; // same
System.out.println(" welcome to student database, show informations about student" + studName);
Scanner courseScan = new Scanner(System.in);
Scanner gradeScan = new Scanner(System.in);
Scanner answerScan = new Scanner(System.in);
System.out.println(" Enter the name of courses");
String[] courseArray = new String[counter];
int[] gradeArray = new int[counter];
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
int n = gradeArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (gradeArray[j - 1] > gradeArray[j]) {
//swap the elements!
temp = gradeArray[j - 1];
gradeArray[j - 1] = gradeArray[j];
gradeArray[j] = temp;
// Swap the course array
String gradeArrayTemp;
gradeArrayTemp = courseArray[j - 1];
courseArray[j - 1] = courseArray[j];
courseArray[j] = gradeArrayTemp;
}
}
}
for (int l = 0; l < courseArray.length; l++) {
System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
}
Scanner request = new Scanner(System.in);
System.out.println(" what do you want to do. Enter 1 to rename a course");
System.out.println(" enter 2 to change a grade ");
int regNumber = request.nextInt();
switch (regNumber) {
case 1: // rename a course
Scanner search = new Scanner(System.in);
System.out.println("Enter the name of the course you want to rename");
String searchCourse = search.nextLine();
for (int i = 0; i < courseArray.length; i++) {
if (searchCourse.equals(courseArray[i])) {
System.out.println("Yes there is a course named " + courseArray[i]);
System.out.println(" to change coursename insert new name");
// here i change the coursename
Scanner newName = new Scanner(System.in);
courseArray[i] = newName.nextLine();
} else {
System.out.println(" no record of this course");
}
System.out.println(" you have chosen to rename course into " + courseArray[i]);
}
}
}
}

In this section of the code:
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
int k = 0;
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
k++;
}
} else {
System.out.println("Sorry, there is no more memory");
}
And
for (int i = 0; i < courseArray.length; i++) {
if(courseArray[i] != null)
System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
}
I have assumed that you take only 20 records depending on the loop. So i initiated arrays
String[] courseArray = new String[20];
int[] gradeArray = new int[20];

Related

IDK why my code keeps crashing taking the input only one time in this loop

The question is taking input of names of students and their score and declaring the topper but the output ain't working.
Here, I am looking for the highest mark with always keeping the value of the current highest mark, please help me if I am missing something.
import java.util. * ;
public class Topper {
public static void main(String args[]) {
Scanner sc = new Scanner(System. in );
String studentTemp = "";
String students[] = new String[100];
int i = 0,
j = 0,
temp = 0,
n = 0;
int score[] = new int[100];
do {
System.out.println("Enter the Name");
students[i] = sc.nextLine();
System.out.println("Enter the Score");
score[i] = sc.nextInt();
n++;
i++;
} while ( students [ i ] != "Alldone");
for (i = 0; i < n; i++) {
for (j = i + 1; j < n - 1; j++) {
if (score[j] > score[i]) {
temp = score[j];
score[j] = score[i];
score[i] = temp;
studentTemp = students[i];
students[i] = students[j];
students[j] = studentTemp;
}
}
}
System.out.println("The Student with Highest score : " + students[n - 1] + " with score : " + score[n - 1]);
System.out.println("The Students performance list : ");
for (i = n - 1; i >= 0; i++)
System.out.println(students[i] + " " + score[i]);
}
}
Try this
import java.util.*;
public class Topper
{
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String studentTemp="";
String students[]=new String[100];
int i=0,j=0,temp=0,n=0,stop=0;
int score[]=new int[100];
do
{
System.out.println("Enter the Name");
students[i]=sc.next();
System.out.println("Enter the Score");
score[i]=sc.nextInt();
System.out.println("Do you wish to continue \n Press 0 to continue \n Press 1 to exit");
stop=sc.nextInt();
n++;
i++;
}
while(stop!=1);
temp=score[0];
studentTemp=students[0];
for(i=1;i<n;i++)
{
if(score[i]>temp)
{
temp=score[i];
studentTemp=students[i];
}
}
System.out.println("The Student with Highest score : "+ studentTemp +" with score : "+temp);
System.out.println("The Students performance list : ");
for(i=0;i<n;i++)
System.out.println(students[i]+" "+score[i]);
}
}```

I am unable to delete elements from within my array when i ask for user input

When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.

Comparing an element of an array to an integer

Here is my assignment:
create an array of N random integers in the range of 1 to 100 (you can use the Java random class for this). Get the value of N from the user. Next ask the user to input a number in this range (1 to 100) and then search the array to locate all occurrences of the search number. For each occurrence, print out the number and the position at which it was found.
Then sort the array and search again, displaying all occurrences of the search number. If the search number is not found, then display a message to that effect.
Finally, print the sum of all of the numbers in the array.
I cannot figure out to how compare elements of the array to an integer. Please help! Here is what I have so far
public class Array {
public static void main(String[] args)
{
int num;
int searchNum;
int position = 0;
Scanner in= new Scanner(System.in);
System.out.println("How many random integers you want to create in range (1, 100)");
num = in.nextInt();
int[] myList = new int[num];
for (int i = 0; i < num; i++)
{
Random r = new Random();
int j = r.nextInt(101);
myList[i] = j;
}
System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found at location: " + (position+1));
}
else
{
position += 1;
}
}
}
}
System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
if (searchNum == myList[i])
System.out.println(searchNum + " found at location: " + (i+1));
You was nearly done, I believe.
public class Array {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("How many random integers you want to create in range (1, 100)");
final int num = in.nextInt();
int[] myList = new int[num];
Random r = new Random();
for (int i = 0; i < num; i++)
{
myList[i] = r.nextInt(101);
}
System.out.println("Enter a number from 1-100 to search");
final int searchNum = in.nextInt();
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found at location: " + i);
}
}
Arrays.sort(myList);
boolean any = false;
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found ");
any = true;
}
else if (searchNum > myList[i])
{
break;
}
}
if (!any)
{
System.out.println("the search number is not found");
}
}
}

how to display the position of array

Your program should display whether the inputted integer value is found in list, how many of it is in list, and what are their locations in list?
sample
List : 1 3 2 5 7 8 5 6 9 4
Input value to search in List: 9
The value 9 is in List!
There are 4 of it in List.
Located at: list[4], list[5], list[6], list[8]
this is my code
import java.io.*;
public class List{
public static void main(String[] args){
int list[] = new int[10];
int i, num = 0, num1=0;
String input = " ";
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
for(i = 0; i < 10; i++){
list[i] = 0;
}
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
try{
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
returnvalue = b;
break;
}
}
System.out.print("Input value for list");
input = in.readLine();
num1 = Integer.parseInt(input);
}catch(IOException e){}
System.out.println("the position is" + returnvalue);
}
}
}
I think the position that is returning is not accurate can you help me?
This will do what you want... Modify the System.out.println(); part according to your need.
public static void main(String[] args) throws IOException {
int list[] = new int[10];
int i, num = 0, num1 = 0;
int returnvalue = 0;
String input = " ";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (i = 0; i < 10; i++) {
list[i] = 0;
}
for (i = 0; i < 10; i++) {
System.out.print("Input value for list[" + i + "] = ");
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
}
for (i = 0; i < 10; i++) {
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.print("Input value for checking in list ");
input = in.readLine();
num1 = Integer.parseInt(input);
boolean flag = false;
int[] arr = new int[10];
int count= 0;
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
flag = true;
arr[count]=b;
count++;
}
}
if(flag)
{
System.out.println("The value "+num1+" is in List!");
System.out.println("There are "+count+" of it in List");
System.out.print("Located at: ");
for(int j=0; j<count;j++)
{
System.out.print(" List["+arr[j]+"]");
}
}
else {
System.out.print(" Element Not found");
}
}
The Console Part for input output is...
Input value for list[0] = 4
Input value for list[1] = 5
Input value for list[2] = 6
Input value for list[3] = 4
Input value for list[4] = 5
Input value for list[5] = 6
Input value for list[6] = 5
Input value for list[7] = 4
Input value for list[8] = 4
Input value for list[9] = 6
list[0] = 4
list[1] = 5
list[2] = 6
list[3] = 4
list[4] = 5
list[5] = 6
list[6] = 5
list[7] = 4
list[8] = 4
list[9] = 6
Input value for checking in list 4
The value 4 is in List!
There are 4 of it in List.
Located at:List[0] List[3] List[7] List[8]
Fixes in your code
A try block is either with a catch block or with a finally block or both.
Having two same variables in inner and outer loop is not good. In your case the outer loop will iterate just once. I think which is not needed.
There are two nested for loop where the loop control variable is same:
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
...
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
...
So, the outer for loop will never iterate what you are expecting. Use a different loop control variable for the inside for loop.
here is my solution for your problem. no need to use that much of loops. you want to use only one foreach - How does the Java 'for each' loop work? (if you don't need to ask question again and agian). I was unable to test this lot :). But, I hope this will work.
import java.util.*;
class MyList{
public static void main(String arga[]){
int array[] = {1,3,2,5,7,8,5,6,9,4};
Scanner input = new Scanner(System.in);
// recursively ask the question
while(true){
System.out.print("Enter the value to search in list: ");
int value = input.nextInt();
System.out.println();
int i = 0;// to get the array index
int count = 0; // to get how many
String list = "Located at: ";
boolean isTrue = false; // to get entered value is in the list or not
for(int a: array){
if(a == value){
isTrue = true;
list += "list[" + i + "],";
count++;
}
i++;
}
if(isTrue){
//remove the last "," from the string
list = list.substring(0, list.length() - 1);
System.out.println("The value " + value +" is in List!");
System.out.println("There are " + count +" of it in List.");
System.out.println(list);
}else{
System.out.println("this value is not in the list");
}
}
}
}

this block of code going straight to break in java

I have this block in a switch case statement that when selected, just breaks and presents me with the main menu again.
System.out.println("Choose a competitor surname");
String competitorChoice2 = input.nextLine();
int lowestSpeed = Integer.MAX_VALUE;
int highestSpeed = 0;
for(int j = 0; j < clipArray.length; j++) {
if(clipArray[j] != null) {
if(competitorChoice2.equals(clipArray[j].getSurname())) {
if(clipArray[j].getSpeed() > clipArray[highestSpeed].getSpeed()) {
highestSpeed = j;
}
}
}
}
for(int i = 0; i < clipArray.length; i++) {
if(clipArray[i] != null) {
if(competitorChoice2.equals(clipArray[i].getSurname())) {
if(clipArray[i].getSpeed() < clipArray[lowestSpeed].getSpeed()) {
lowestSpeed = i;
}
}
}
}
for(int h = lowestSpeed; h < highestSpeed; h++ ) {
System.out.println(""+clipArray[h].getLength());
}
I have an array of objects and each object has a surname and a speed.
I want the user to choose a surname and display the speeds of all of their clips from lowest to highest.
when I select this option it just breaks and brings me back to the main menu
The speeds are also originally entered as floats.
here is the menu:
while (true) {
System.out.println("Please select one of the following options by entering a number: \n"
+ "1) Quit\n"
+ "2) Add a new clip to the records\n"
+ "3) View information about a clip via an index number\n"
+ "4) Change information about a clip via an index number\n"
+ "5) List all competitors which have a clip recorded\n"
+ "6) Choose a competitor and display their longest clip\n"
+ "7) Choose a competitor and display their clips arranged by speed\n"
+ "8) display elements of array in alphabetical order");
choice = input.nextInt();
input.nextLine();
switch (choice) {
switch (choice) {
case (1):
System.out.println("You have quit the program");
System.exit(0);
case (2):
Clip c = new Clip();
System.out.println("Set an index number between 1-1000");
int setIndexNumber = input.nextInt();
c.setIndexNumber(setIndexNumber);
System.out.println("What is the given name of the competitor?");
String givenName = input.next();
c.setGivenName(givenName);
System.out.println("What is the surname of the competitor?");
String surname = input.next();
c.setSurname(surname);
System.out.println("What is the length of the clip?");
float setLength = input.nextFloat();
c.setLength(setLength);
System.out.println("What is the speed of the competitor?");
float setSpeed = input.nextFloat();
c.setSpeed(setSpeed);
System.out.println("What what time was this recorded? (24 hour)");
System.out.println("Enter hour: ");
int setHour = input.nextInt();
System.out.println("Enter minute: ");
int setMin = input.nextInt();
c.setTime(setHour, setMin);
clipArray[firstAvailableIndex()] = c;
counter++;
break;
case (3):
System.out.println("Which clip do you want to view?\n"
+ "Select from index 0-1000:");
int indexNo = input.nextInt();
for (int j = 0; j < clipArray.length; j++) {
if (j == indexNo) {
System.out.println("Index Number: " + clipArray[j].getIndexNumber());
System.out.println("Given Name: " + clipArray[j].getGivenName());
System.out.println("Surname: " + clipArray[j].getSurname());
System.out.println("Length: " + clipArray[j].getLength());
System.out.println("Speed: " + clipArray[j].getSpeed());
System.out.println("Time: " + clipArray[j].getHour() + ":" + clipArray[j].getMinute());
break;
}
}
break;
case (4):
System.out.println("Which clip do you want to change? choose and index number: ");
int clipIndex = input.nextInt();
input.nextLine();
System.out.println("What do want to set this given name to?");
String editGivenName = input.nextLine();
clipArray[clipIndex].setGivenName(editGivenName);
System.out.println("What do you want to set this surname to?");
String editSurname = input.nextLine();
clipArray[clipIndex].setSurname(editSurname);
System.out.println("What do you want to set this length to?");
float editLength = input.nextFloat();
clipArray[clipIndex].setLength(editLength);
System.out.println("What do you want to set this speed to?");
float editSpeed = input.nextFloat();
clipArray[clipIndex].setSpeed(editSpeed);
System.out.println("What do you want to set this hour to?");
int editHour = input.nextInt();
System.out.println("What do you want to set this minute to?");
int editMin = input.nextInt();
clipArray[clipIndex].setTime(editHour, editMin);
break;
case (5):
for (int g = 0; g < clipArray.length; g++) {
if (clipArray[g] != null) {
System.out.println(""+clipArray[g].getSurname());
}
}
break;
case (6):
System.out.println("Choose a competitor by surname");
String competitorChoice = input.nextLine();
int longestClip = 0;
for(int i = 0; i < clipArray.length; i++) {
if(clipArray[i] != null) {
if (competitorChoice.equals(clipArray[i].getSurname())) {
if(clipArray[i].getLength() > clipArray[longestClip].getLength()) {
longestClip = i;
}
}
}
}
System.out.println(""+clipArray[longestClip].getLength()+", at Index: "+clipArray[longestClip].getIndexNumber());
break;
case (7):
System.out.println("Choose a competitor surname");
String competitorChoice2 = input.nextLine();
int lowestSpeed = Integer.MAX_VALUE;
int highestSpeed = 0;
for(int j = 0; j < clipArray.length; j++) {
if(clipArray[j] != null) {
if(competitorChoice2.equals(clipArray[j].getSurname())) {
if(clipArray[j].getSpeed() > clipArray[highestSpeed].getSpeed()) {
highestSpeed = j;
}
}
}
}
for(int i = 0; i < clipArray.length; i++) {
if(clipArray[i] != null) {
if(competitorChoice2.equals(clipArray[i].getSurname())) {
if(clipArray[i].getSpeed() < clipArray[lowestSpeed].getSpeed()) {
lowestSpeed = i;
}
}
}
}
for(int h = lowestSpeed; h < highestSpeed; h++ ) {
System.out.println(""+clipArray[h].getLength());
}
break;
case (8):
for(int i = 1; i < counter; i++) {
for(int j = 0; j < counter - 1; j++) {
if(((clipArray[j].getSurname()).compareToIgnoreCase((clipArray[j+1].getSurname()))) > 0) {
Clip temp = clipArray[j];
clipArray[j] = clipArray[j+1];
clipArray[j+1] = temp;
}
}
}
for(int g = 0; g < counter; g++) {
System.out.println(clipArray[g].getSurname());
}
break;
default:
System.out.println("you have not selected a valid option");
break;
}//end of switch case
EDIT: out of bounds exceptions at the if statement for the lowest speed
When lowestSpeed is Integer.MAX_VALUE, that's out of bounds for the clipArray. Change the initialization for lowestSpeed to:
int lowestSpeed = 0;
Initializing a variable to the maximum before doing a loop that searches for the minimum is appropriate when the variable is used to store the minimum value itself, but in this case it's not: it's storing the index of the element having the minimum value, so start with the first valid index (Er, I think).

Categories

Resources