So in class we follow the lab manual instructions. I was able to do step one and two, I just need help with step three.
Lab Manuel Instructions:
Add a method void removeFirst(int newVal) to the IntegerList class that removes the first occurrence of a value from the list. If the value does not appear in the list, it should do nothing (but it’s not an error). Removing an item should not change the size of the array, but note that the array values do need to remain contiguous, so when you remove a value you will have to shift everything after it down to fill up its space. Also remember to decrement the variable that keeps track of the number of elements.
Add an option to the menu in IntegerListTest to test your new method.
IntegerList
public class IntegerList
{
private int count;
private double totalInt;
int[] list; //values in the list
//-------------------------------------------------------
//create a list of the given size
//-------------------------------------------------------
void addElement(int newVal)
{
if (count == list.length)
increaseSize();
list[count] = newVal;
count++;
}
void removeFirst(int newVal2)
{
for (int i = 0; i < list.length-1; i++)
{
if (newVal2 == list[i])
{
list[list.length] = (Integer) null;
list[i] = list [i-1];
}
}
}
public IntegerList(int size)
{
list = new int[size];
count = 0;
}
public void randomize()
{
for (int i=0; i<list.length; i++)
{
list[i] = (int)(Math.random() * 100) + 1;
count++;
}
}
public void print()
{
for (int i=0; i<count; i++)
System.out.println(i + ":\t" + list[i]);
}
private void increaseSize()
{
int[] temp = new int[list.length * 2];
for (int lst = 0; lst < list.length; lst++)
temp[lst] = list[lst];
list = temp;
}
}
IntegerListTest
import java.util.Scanner;
public class IntegerListTest
{
static IntegerList list = new IntegerList(10);
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
printMenu();
int choice = scan.nextInt();
while (choice != 0)
{
dispatch(choice);
printMenu();
choice = scan.nextInt();
}
}
public static void dispatch(int choice)
{
int loc;
switch(choice)
{
case 0:
System.out.println("Bye! ") ;
break;
case 1:
System.out.println("How big should the list be?");
int size = scan.nextInt();
list = new IntegerList(size);
list.randomize();
break;
case 2:
list.print();
break;
case 3:
System.out.println("What number would you like to add?");
int newVal = scan.nextInt();
list.addElement(newVal);
break;
case 4:
System.out.println("What number do you want to remove? (Removes first occurance.)");
int newVal2 = scan.nextInt();
list.removeFirst(newVal2);
default:
System.out.println("Sorry, invalid choice");
}
}
public static void printMenu()
{
System.out.println("\n Menu ");
System.out.println(" ====");
System.out.println("0: Quit");
System.out.println("1: Create a new list (** do this first!! **)");
System.out.println("2: Print the list");
System.out.println("3: Add to the list");
System.out.println("4: Remove Integer");
System.out.print("\nEnter your choice: ");
}
}
Any help is greatly appreciated. It would be cool if you could also explain why so I can learn from this. Thanks! :D
So you can loop the array to find the first element that matches a given value.
If it is found, save its position to index and shift all elements after it by one position:
void removeFirst(int newVal2) {
int index = -1;
for (int i = 0; i < count; i++) {
if (index == -1 && newVal2 == list[i]) {
// element found - save index
index = i;
}
if (index != -1) {
// this code handles after found case
if (i == count-1) {
// zero-out last element
list[i] = 0;
count--;
}
else {
// shift value
list[i] = list[i+1];
}
}
}
}
public void removeFirst(int val){
//the position at which the algorithm currently is
int i = 0;
boolean found = false;
//search for the first occurence of val in the array
for(; i < count && list[i] != val ; i++);
//i is now the index of the first value equal to val in list
//if a match was found, the index must be smaller than the array-size
found = (i < count);
//shift all elements that are right of the value to the left
//to leave no empty space. Since the value at i is the searched value
//it's left out (i += 1)
i += 1;
for(; i < count ; i++)
list[i - 1] = list[i];//move the current element one to the left
//check if a match was found and decrement the sizecounter, if one was found
if(found)
--count;
}
i don't really have time to give u much details and i know this is not really an efficient way, but what u could do is to always create a new array of "size-1" and then take note of the index of the array element you want to remove, then copy everything before and after that array element into your new array, once all of this is done you could copy it back into the original array like this oldArray = newArray.
Related
//I need to ask the user for the size of the list they want, then generate random numbers with an array list for the size list they want, and output the list. These steps I have done but then I have to output the number of odd numbers in the list using an enhanced for loop and then reprint the list without even numbers.//
import java.util.Scanner;
import java.util.ArrayList;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How big would you like your list?");
int decision = scan.nextInt();
ArrayList<Integer> Rando = new ArrayList<Integer>();
for (int i = 1; i <= decision; i++)
{
Rando.add((int)(Math.random()*100 + 1));
}
System.out.println();
System.out.println(Rando);
ArrayList<Integer> evens = Rando;
for (int i = 0; i < evens.size(); i++)
{
if (evens.get(i)%2 != 0)
{
evens.remove(i);
}
}
ArrayList<Integer> odds = Rando;
for (int i = 0; i < odds.size(); i++)
{
if (odds.get(i)%2 != 0)
{
evens.remove(i);
}
}
System.out.println();
System.out.println(odds);
for(Integer number: Rando)
{
System.out.println();
System.out.println("# of Odd Numbers: "+ odds.size());
System.out.println();
break;
}
System.out.println("List Without Evens: " + evens.remove);
System.out.println();
}
}
The way you are doing it now you won't have anything left in the list.
ArrayList<Integer> evens = Rando;
...
ArrayList<Integer> odds = Rando;
This will modify the original list. You won't have anything left in the list after the first two loops, which remove the even numbers and then the odd. I think instead you should create a new list.
ArrayList<Integer> evens = new ArrayList<>();
for (int i = 0; i < Rando.size(); i++)
{
if (Rando.get(i)%2 == 0)
{
evens.add(Rando.get(i));
}
}
Now using the for-each loop becomes easier.
ArrayList<Integer> evens = new ArrayList<>();
for (int x : Rando )
{
if (x%2 == 0)
{
evens.add(x);
}
}
Remember you need to modify the loops you have now. Rando will contain no elements at all the way you have it, so you have to change the existing code or re-create the random number list each time.
In this code I have an array with 5 elements and each element contains a value. Below in the while loop, I'm trying to give the user 3 attempts to guess what number is contained in the array (the user enters their guesses). My problem is that I don't know how to make match the user's guess (stored in a variable choose) with the array values caja[i] to print whether the user won or lost depending on a correct or incorrect guess respectively.
public static void main(String[] args)
{
int[] caja = new int [5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++)
{
System.out.println(caja[i]);
}
System.out.println();
int electionGame = 3;
int o = 0;
while(electionGame > 0)
{
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length; i++)
{
o = o + 1;
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
}
electionGame--;
}
}
}
Your problem is that you break out of your loop in every case:
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
Instead of doing this (and printing the result after only the first comparison), you should have a Boolean indicating whether the number was found in the array:
int electionGame = 3;
boolean found = false; //indicates whether user has found right number
while (electionGame > 0 && !found) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length && !found; i++) {
if (choose == caja[i]) {
found = true;
}
}
electionGame--;
if (found) {
System.out.println("you won");
} else {
System.out.println("nope");
}
}
This way, you can check the variable and tell the user whether he won or lost.
Here are some additional suggestions. The answer by Alex (https://stackoverflow.com/a/36133864/6077352) is good. Please note the comments in the code.
import java.util.Scanner;
/** https://stackoverflow.com/q/36133524/6077352 */
public class GuessNumber {
public static void main(String[] args) {
int[] caja = new int[5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++) {
System.out.println(caja[i]);
}
System.out.println();
int tries = 3;
Scanner sc = new Scanner(System.in);// no need to create scanners in loop
while (tries-- > 0) {// count down tries
System.out.print("Please guess a number... ");
int guess = sc.nextInt();
boolean win = false;// flag to determine if won
for (int i : caja) {// iterate through array and check if guess is inside
win |= (i == guess);// when inside: win=true
}
System.out.println("Answer right? " + win);
System.out.println();
}
}
}
So if the user can attempt to get any of the values of the array you might to change your while loop to this one:
while (electionGame > 0) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
boolean ganaste = false;
for (int i = 0; i < caja.length; i++) {
o = o + 1;
if (choose == caja[i]) {
ganaste = true;
break;
}
}
if (ganaste)
System.out.println("Ganastes");
else
System.out.println("Perdiestes");
electionGame--;
}
I am practicing object orientation here entering in basketball player names and how many points scored and rebounds grabbed.
How would I go through each element in an array of objects to find the last player with an even amount of points?
This is the code I have so far to enter the information. What do I need to do in my second forloop to examine each element and then display the last element that fits my criteria?
class basketballObj
{
public static void main (String[]args)
{
Basketball bbArray[];
String theName;
int thePoints;
int theRebounds;
int index;
int noOfElements = 0;
bbArray = new Basketball[3];
for(index = 0; index < bbArray.length; index++)
{
System.out.println("Enter a name ");
theName = EasyIn.getString();
System.out.println("Enter points scored ");
thePoints = EasyIn.getInt();
System.out.println("Enter rebounds grabbed ");
theRebounds = EasyIn.getInt();
bbArray[index] = new Basketball(theName, thePoints, theRebounds);
noOfElements++;
}
for(index = 0; index < bbArray.length; index++)
{
if(bbArray[index].getPoints() % 2 == 0)
{
}
}
}
}
Well if you want to find the last player with an even amount of points, you don't actually want to go through each element ;-). Try:
for(index = bbArray.length-1; index >= 0; index--)
{
if(bbArray[index].getPoints() % 2 == 0)
{
//add whatever relevant code here.
break; //this line breaks the for loop (because you've found a player with an even amount of score
}
}
we start at bbArray.length-1 because while you array contains 3 elements, arrays are zero-indexed. Meaning that to get the first element, you will have to call bbArray[0]. Similarly call bbArray[2] for the last element.
Simple. Iterated your array backwards.
boolean found = false;
for(int index=array.length-1; index>-1 && !found; index--) {
if(array[index].getPoints()%2 == 0) {
// found element. Break out of for loop
found=true;
}
}
You've pretty much got it.
Create a temporary, uninitialized variable Basketball temp; before the for loop that iterates through the bbArray and then set it equal to the bbArray[index] if the if condition is met.
If you want to save the index it was found at then create an int indexFound; as well.
Looping through it backwards as user2651804 suggested yields this:
public class basketballObj
{
public static void main(String[] args)
{
...
Basketball temp;
int indexFound = -1;
...
for(index = bbArray.length - 1; index >= 0; index++)
{
if(bbArray[index].getPoints() % 2 == 0)
{
temp = bbArray[index];
indexFound = index;
break;
}
}
//note temp will be null if no scores were even
//if (temp != null)
//you can use the above if statement if you don't want to use indexFound
//you can also just check if indexFound == -1
if (indexFound != -1)
{
System.out.println("Found at index: " + indexFound);
//
}
}
}
I'm pretty new to java, and I'm trying to create a simple method that sorts inputted numbers, either ascending or descending. However, there's a problem that I can't put in repeated values. Is there a way to get the key of a certain item of an array??
My code:
import java.io.Console;
public class TestSort {
public static void main(String args[]) {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
System.out.println("TESTSORT.java");
System.out.println("-------------");
System.out.println("Type in a set of numbers here:");
String in = c.readLine();
System.out.println("(A)scending or (D)escending");
String ad = c.readLine();
boolean d = false;
if(ad.equals("a")) d = false;
else if(ad.equals("d")) d = true;
else {
System.out.println("Invalid Input.");
System.exit(1);
}
String[] in2 = in.split(" ");
int[] x = new int[in2.length];
int count1 = 0;
for(String val : in2)
x[count1++] = Integer.parseInt(val);
int[] a = new int[x.length];
int count = 0;
for(int y : x) {
for(int z : x) {
// if index of y equals index of z continue
if(z < y) count++;
}
a[count] = y;
count = 0;
}
if(d) {
int[] arr3 = new int[a.length];
int length = a.length;
for(int b : a) arr3[--length] = b;
for(int b : arr3) System.out.println(b);
} else
for(int b : a)
System.out.println(b);
}
}
This program just counts up the number of other numbers smaller than itself, but not including itself. However, it doesn't differentiate itself from other numbers with the same value.
Help would be appreciated.
Thanks.
To get the index of a certain value for an array you will have to loop through the array. However if there is multiple entries with the same value this approach wouldn't work (without modification)
int indexVal = -1;
int inputValue; // This is your input vlaue you are trying to find
for(int i = 0; i < array.length ; i++)
{
if (array[i] == inputValue)
{
indexVal = i;
break;
}
}
You may also want to look at Array.sort for built in array sorrting
If you want an index you should not be using for each loops. You will have to use a regular for loop to get at an index in the array.
A SortedSet is perfect for this. As a set, it does not allow duplicate values, and it is sorted automatically for you!
Just add your elements to the set, e.g:
SortedSet<Integer> set = new SortedSet<Integer>();
for(String value : in2.split(" ")){
set.add(Integer.parseInt(value));
}
To reverse the order of the set do something like this:
SortedSet<Integer> descending = set.descendingSet();
You can iterate through sets just like arrays too:
for(Integer i : set){
//Do something
}
Good luck!
Here im required to Write a method printArray that displays the contents of the array num and Display the contents of the array with each
number separated by a space. and i have to start a new line after every 20 elements.
i wrote this code but whenever i try to execute it, it shows the array without the new line
public class project2 {
public static void main(String[] args) {
int num []= new int [100];
for (int i=0;i<num.length;i++){
num[i]=-1;
num[7]=7;
}
printArray(num);
System.out.println(num);
}
public static void printArray (int array1[]){
int count =20;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (array1[x]==count){
System.out.println(" ");
count=array1[x]+count;
}
}
}
}
import java.util.Arrays;
import java.util.Random;
public class project2 {
public static void main(String[] args) {
int num[] = new int[100];
Random random = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = random.nextInt(100);
}
printArray(num);
System.out.println('\n' + Arrays.toString(num));
}
public static void printArray(int array1[]) {
int count = 20;
for (int i = 0; i < array1.length; i++) {
System.out.printf("%2d ", array1[i]);
if ((i + 1) % count == 0) {
System.out.println("");
}
}
}
}
You should use the modulo (or remainder) operator (%), that suits your usage much better:
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (x>0 && (x%count)==0){
System.out.println(" ");
}
}
This way, you will get a new line every count characters, and the first line will not have it (that is why the x>0 check is there).
Also, in the original post, this line is frankly totally bad:
count=array1[x]+count;
Just what would it do? Why do you add the value stored in the array to the fixed counter? Considering this line, I advise that you should really sit back a bit, and try to think about how things work in the background... There is no magic!
Take a closer look at your if-statement:
if (array1[x]==count)
According to your array values, this will never return true
i have to start a new line after every 20 elements.
Change to following code:
if (x%20 == 0)
{
System.out.println();
}
in place of
if (array1[x]==count)
{
System.out.println(" ");
count=array1[x]+count;
}
Problem is with
if (array1[x]==count)
You are comparing count with value present in array. Instead compare it with desired count ie 20 or Use modulo operator as suggested in other answers / comments .
int count = 1;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (count == 20){ // Check if its 20th element
System.out.println(" ");
count=1; // reset count
}
count++;
}