I am trying to implement the insertion sort and I only get the first element correct in the sorted newArray. All others become 0's.
I use the occupancy variable to keep track of the number of elements in the newArray.
package nisarg;
import java.util.Scanner;
public class InsertionSort {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int size,i,j,k=0;
int occupancy = 1;
System.out.println("How many elements? ");
size = input.nextInt();
int[] array = new int[size];
int[] newArray = new int[size];
for(i=0;i<size;i++){
System.out.println("Enter element at " +(i+1) );
array[i] = input.nextInt();
//System.out.println(array[i]);
}
newArray[0] = array[0];
for(i=1;i<size;i++){
for(j=0;j<occupancy;j++){
if(array[i] <= newArray[j]){
for(k=occupancy-1;k>j;k--){
newArray[k] = newArray[k-1];
}
newArray[k] = array[i];
occupancy++;
System.out.println(occupancy +" occupancy");
break;
}
else if(j==occupancy-1){
newArray[occupancy-1] = array[i];
occupancy++;
}
}
}
for(i=0;i<size;i++){
System.out.println(newArray[i]);
}
}
}
Related
I am working on a java code to get an array of integers from the user and then remove the integer in a selected index by the user. My code is already done but I don't know how to get array input from the user.
import java.util.*;
public class Test11 {
public static int[] removeTheElement(int[] arr, int index) {
if (arr == null || index < 0 || index >= arr.length) {
return arr;
}
int[] anotherArray = new int[arr.length - 1];
for (int i = 0, k = 0; i < arr.length; i++) {
if (i == index) {
continue;
}
anotherArray[k++] = arr[i];
}
return anotherArray;
}
public static void main(String[] args) {
Scanner adnan = new Scanner(System.in);
int[] arr = { 1, 2, 3, 4, 5 };
System.out.println("Original Array: " + Arrays.toString(arr));
System.out.println("Index to be removed: ");
int index = adnan.nextInt();
arr = removeTheElement(arr, index);
System.out.println("New Array: " + Arrays.toString(arr));
}
}
Any help would be really appreciated.
I have modified your code in the main() to make it work for accepting arrays input from user.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of array: ");
final int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Enter the elements to array: ");
for (int loop = 0; loop < size; loop++) {
array[loop] = scanner.nextInt();
}
System.out.println("Original Array: " + Arrays.toString(array));
System.out.println("Index to be removed: ");
int index = scanner.nextInt();
array = removeTheElement(array, index);
System.out.println("New Array: " + Arrays.toString(array));
}
You can read the array as a string like : 1 2 3 4 ..., and then extract and cast the values. Or you can ask the user for the size of the array (number of elements that the user wants to insert ) and then loop to scan and save each element.
The first case :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] stringArray = scanner.nextLine().split(" ");
int[] parsedValues = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
parsedValues[i] = Integer.parseInt(stringArray[i]);
}
System.out.println(Arrays.toString(parsedValues));
}
The second case :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] parsedValues = new int[size];
for (int i = 0; i < size && scanner.hasNextInt(); i++) {
parsedValues[i] = scanner.nextInt();
}
System.out.println(Arrays.toString(parsedValues));
}
This program is supposed to take a series of numbers, that is put into an array by the user. Not sure on how to do the calculation correctly when using the elements from the array inside of the method that I had made.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//****Sentinel****
int s;
//****Do...While Statement****
do{
//****User Input****
System.out.println("Welcome! Please enter a 1 to continue, or 2 to exit.");
s = sc.nextInt();
System.out.println();
switch(s){
case 1:
//****Array****
ArrayList<Integer> nums;
nums = new ArrayList<>();
//****User Input****
System.out.println("Please enter 4 integers: ");
System.out.println("*************************************************");
for(int i = 0; i < 4; i++){
nums.add(sc.nextInt());//****User adds to Array****
}
System.out.println("*************************************************");
//****Call Method****
Product();
break;
}
}while(s != 2);//****end Do...While****
}
//****Product Method****
public static void Product(int... nums){
//****variables****
int result;
int sum = 0;
//****iterate through array****
for(int n : nums){
sum += n;
}
//****Multiply****
int product = (sum * nums.length);
result = product;
//****User Output****
System.out.println("The product of the numbers is: " + result);
System.out.println();
System.out.println("*************************************************");
}
The only thing I get for output is a 0.
You are not passing the array to your method.
//****Call Method****
Product();
You should be passing the array there.
In my program the user determines the size on an array, then the user inputs values that are stored in descending order in the array as 'high scores'. The user then gets the option to update values in the array, although for my function which performs this task (insertScore) it doesnt print out the right values.
If:
240
110
50
is stored, and the user decides to update the values, by inserting 150, the array should update to be
240
150
110
and 50 will be removed, although for some reason when i run my code i keep getting '[Ljava.lang.Integer;#55f96302'? I have no idea why this is happening, and I have searched everywhere to find a way to fix this although i cant seem to find anyone else who has had that problem...
I know my error is mainly persisting in the insertScore function, but i cant find a reason why?
this is my code, thanks for any and all help:
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class HighScores {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many values would you like to set the High Score list too?:");
int userInput = input.nextInt();
Integer[] zeroSet = {};
Integer[] setScores = intialisingHighScores(userInput, zeroSet);
System.out.println("Now Enter the high scores you wish to display:");
Integer[] highScores = printHighScores(setScores, userInput);
System.out.println("The high scores are:");
for (int i=0; i<=(userInput-1); i++){
System.out.println((i+1) + ". " + highScores[i]);
}
while (userInput > 0){
setScores = insertScore(userInput, setScores);
}
}
public static Integer[] intialisingHighScores(int userInput, Integer[] zeroSet){
zeroSet = new Integer [userInput];
for (int index=0; index<=(userInput-1); index++){
zeroSet[index] = 0;
}
return zeroSet;
}
public static Integer[] printHighScores(Integer[] setScores, int userInput) {
Scanner inputNo = new Scanner(System.in);
for (int i=0; i<=(userInput-1); i++){
int scores = inputNo.nextInt();
if(scores<0){
System.out.println("No player can be that bad, please enter positive high scores only");
scores = inputNo.nextInt();
setScores[i] = scores;
}
else{
setScores[i] = scores;
}
}
Arrays.sort(setScores, Collections.reverseOrder());
return setScores;
}
public static int higherThan(Integer[] setScores){
Scanner inputNo = new Scanner(System.in);
System.out.println("Please enter any updated scores");
int newScore = inputNo.nextInt();
return newScore;
}
public static Integer[] insertScore(int userInput, Integer[] setScores){
int newScore = higherThan(setScores);
for (int i=0; i<=(userInput-1); i++){
if(setScores[i] < newScore ){
for (int n=(userInput-2); n>i; n--){
setScores[n+1] = setScores[n];
}
setScores[i] = newScore;
for(int loop=0; loop<=(userInput-1); loop++){
System.out.println(setScores);
}
}
}
return setScores;
}
}
When you use System.out.println(setScores);, you're calling the toString method of an array. By default, toString returns a String formatted as class name # hex hashcode. If you want a more readable representation of the array, use Arrays#toString:
System.out.println(Arrays.toString(setScores));
You are printing the array directly which uses the toString and gives you className#hashCode.
As you are looping thru the list you might want to use the following:
public static Integer[] insertScore(int userInput, Integer[] setScores){
int newScore = higherThan(setScores);
for (int i=0; i<=(userInput-1); i++){
if(setScores[i] < newScore ){
for (int n=(userInput-2); n>i; n--){
setScores[n+1] = setScores[n];
}
setScores[i] = newScore;
for(int loop=0; loop<=(userInput-1); loop++){
System.out.println(setScores[loop]); //***EDITED***//
}
}
}
return setScores;
}
I can't figure out why is the array out of its borders, eclipes says the problem is at line 15
int d = array[1] - array[0];
import java.util.*;
public class Arrays1 {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
int N = reader.nextInt();
int[] array = new int[N];
boolean right = true;
for (int i=0; i<array.length; i++)
{
System.out.println("Enter number for array");
array[i] = reader.nextInt();
}
int d = array[1] - array[0];
if ((array[N]-1)%d !=0)
{
right = false;
}
}
}
You probably want something like that:
public class Main {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
int N = reader.nextInt();
int[] array = new int[N];
boolean right = true;
for (int i=0; i<array.length; i++)
{
System.out.println("Enter number for array");
array[i] = reader.nextInt();
}
int d = array[1] - array[0];
if ((array[N-1])%d !=0)
{
right = false;
}
}
}
Have a look at this part:
if ((array[N-1])%d !=0)
You were doing: if ((array[N]-1)%d !=0)
Btw, is aways a problem to trust the scan, you will need several validations.
Since you read the bounds of your array from the reader, it may be 0 or 1. To ensure it is big enough, you can try something like:
if(N > 1) {
int d = array[1] - array[0];
if ((array[N]-1)%d !=0)
{
right = false;
}
}
If it has to be bigger than 1 for you application to work, you could enforse this contraint right at the beginning:
int N = reader.nextInt();
if(N <= 1) {
System.out.println("N must be bigger than 1");
System.exit(1); // exit with error code
}
Try to validate the user input before you read your Array items, as the user may enter 1 for example when he is prompted for the array size thus there well be only one item in the array and accessing the item in second index (1 as it 0 based) will result in an ArrayOutOfBoundsException:
import java.util.*;
public class Arrays1 {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
int N = reader.nextInt();
while (N < 2) {
System.out.println("Enter a valid size for the array");
N = reader.nextInt();
}
int[] array = new int[N];
boolean right = true;
for (int i=0; i<array.length; i++)
{
System.out.println("Enter number for array");
array[i] = reader.nextInt();
}
int d = array[1] - array[0];
if ((array[N]-1)%d !=0)
{
right = false;
}
}
}
As a side note, pay attention to follow Java naming conventions as of the camelCase,so identifiers may begin with lowercase character not upper ones such as for int N which should be int n.
I am working on a program that needs to calculate the sum of 2 large integers without using the biginteger class in java. I am stuck on my for loop which calculates the sum. I am getting an extra 0 so 30 + 30 = 600.
I am pretty sure it is because I am looping through the arrays the wrong way. I need to go the opposite way (starting from the right side like you would when adding numbers) but I can't seem to fix it without getting an out of array index error.
here is my code:
main:
import java.util.Scanner;
public class testLargeInteger
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1;
String string2;
int exp =0;
System.out.print("Enter the first integer: ");
//Store up the input string “string1” entered by the user from the keyboard.
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.print("Enter the second integer: ");
string2 = input.next();
//Store up the input string “string2” entered by the user from the keyboard.
LargeInteger secondInt = new LargeInteger(string2);
System.out.print("Enter the exponential integer: ");
//Store up the input integer “exp” entered by the user from the keyboard.
exp = input.nextInt();
LargeInteger sum = firstInt.add(secondInt);
System.out.printf ("First integer: %s \n", firstInt.display());
System.out.println("Second integer: " + secondInt.display());
System.out.println(" Exponent: " + exp);
System.out.printf (" Sum = %s \n", sum.display());
}
}
Large integer:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
public LargeInteger( int[] array ) {
intArray = array;
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
//get first array
public int[] getIntArray() {
return intArray;
}
//ADD method to add 2 arrays together
public LargeInteger add(LargeInteger secondInt){
int[] otherValues = secondInt.getIntArray();
int maxIterations = Math.min(intArray.length, otherValues.length);
int currentResult; //to store result
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) +1 ];
int needToAdd = 0; //to store result should be added next step
for(int i = 0; i < maxIterations; i++) {
currentResult = intArray[i] + otherValues[i];
resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer
needToAdd = currentResult / 10; //this is what you need to add on next step
}
resultArray[Math.max(intArray.length, otherValues.length) ] = needToAdd;
return new LargeInteger( resultArray );
}
}
I have tried changing the for loop in sum to something like this:
for(int i = maxIterations; i >= 0; i--)
That for loop is only one of your problems.
1] you are not adding the carry properly.
2] a stack is more appropriate here than an array.
With a stack (place code inside your method):
Note: You are calling the function with number.add(num2);
public class LargeInt{
private String number;
public LargeInt(String num){
this.number = num;
}
public String add(String num2){
Stack<Integer> adder = toIntegerStack(this.number);//UPDATE
Stack<Integer> addend = toIntegerStack(num2);//UPDATE
Stack<Integer> result = new Stack<Integer>();
int carry =0;
int tmp = 0;
while(!.adder.isEmpty && !addend.isEmpty()){
tmp = adder.pop()+addend.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
while(!adder.isEmpty){
tmp = adder.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
while(!addend.isEmpty){
tmp = addend.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
//beyond this point the result is your answer
//here convert your stack to string before returning
}
}
UPDATE TO ANSWER COMMENT:
I am also editing above to call this function to fill stacks.
private Stack<Integer> toIntegerStack(String n){
Stack<Integer> stack = new Stack<Integer>();
for(char c: n.toCharArray())
stack.push(c-48);//ASCII
return stack;
}//toStack(String)
If you insist on using array, you must follow the same pattern with your array.
int indexA=0;
int indexB=0;
int[] result = new int[1+A.length>B.length?A.length:B.length];
int indexResult=result.length-1;
while(indexA < A.length && indexB <B.length){//inside is same idea
tmp = A[indexA++] + B[indexB++] + carry;
//... do here as for stacks for tmp and carry
result[indexResult--];
}
while(indexA < A.length){
//do as in stack version
}
while(indexB < B.length){
//do as in stack version
}
Your adding code assumes that the least significant digit is in array[0], but your reading code puts the most significant digit there. You should reverse the array after reading.