How do I populate an array with palindromes using a loop? - java

First time on this site and first java class ever. I am stuck trying to populate an array with palindromes. I have tried the everything with no luck. What am I doing wrong?
Here's what I've coded so far.
public class PalindromeListArray
{
public static void main(String[] args)
{
//Declare variables.
int digit1, digit2, digit3, digit4, digit5;
final int MAX = 10;
int x=0;
//Create an array of size 25.
String[] palindromeList = new String[25];
//Generate numbers.
for (digit1 = 1; digit1 < MAX; digit1++)
for (digit2 = 0; digit2 < MAX; digit2++)
for (digit3 = 0; digit3 < MAX; digit3++)
for (digit4 = 0; digit4 < MAX; digit4++)
for (digit5 = 0; digit5 < MAX; digit5++)
if (digit1 == digit5 && digit2 == digit4)
for(x=0; x < palindromeList.length; ++x){
//Populate array with palindromes.
palindromeList[x] = String.valueOf(digit1) + String.valueOf(digit2) + String.valueOf(digit3) + String.valueOf(digit4) + String.valueOf(digit5);
System.out.println(x + "\t" + palindromeList[x]);
}
}
}

Along these lines:
...
if(x == palindromeList.length) break;
palindromeList[x++] = String.valueOf(digit1) + String.valueOf(digit2) + ...
}
for(int i = 0; i < x; i++)
System.out.println(i + "\t" + palindromeList[i]);
...
You were in the ball park.

Related

java.util.NoSuchElementException reading user input

I'm getting an error message (java.util.NoSuchElementException) in thread main when attempting to compile the following code with the input 3, then 4, 5, and 7. I've tried to tweak the code, but there's something I'm missing. I was thinking it may be due to my use of arrays since I am just learning how to use those, but I've tried to look closely at them and I didn't see anything I did wrong, but I definitely missed something. Any help would be appreciated. Thanks!
import java.util.Scanner;
public class ArrayMethods2 {
public static int[] findMinAndMax(int[] x) {
int i;
int min = x[0];
int max = x[0];
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
int [] minAndMax = new int[2];
minAndMax[0] = min;
minAndMax [1] = max;
return minAndMax;
}
public static double averageWithDrop(int[] x) {
int i;
int min = x[0];
int minIndex1 = 0;
int minIndex2 = 0;
int sum = 0;
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
minIndex1 = i;
}
}
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
if (i != minIndex1)
minIndex2 = i;
}
}
for (i = 0; i < x.length; i++) {
if (i == minIndex1) {
sum = sum + 0;
}
else if (i == minIndex2) {
sum = sum + 0;
}
else {
sum = sum + x[i];
}
}
double average = sum / (x.length - 2);
return average;
}
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? (must be at least 3) ");
int userValue = scnr.nextInt();
System.out.println(userValue);
while (userValue < 3) {
System.out.println("Invalid value, must be at least 3. Please try again ");
userValue = scnr.nextInt();
System.out.println(userValue);
}
int x = 0;
int indexVal;
int [] userArray = new int [userValue];
while (x <= userValue) {
System.out.print("Enter value for index " + x + ": ");
indexVal = scnr.nextInt();
System.out.println(indexVal);
userArray[x] = indexVal;
x++;
}
int [] minAndMaxVal = new int [2];
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
double avg = averageWithDrop(userArray);
System.out.println("Average excluding two lowest values: " + avg);
}
}
Running your code, I did not get any NoSuchElementException, however I got IndexOutOfBoundsException. Check the class your are running.
Please remember arrays are 0 based.
In the main method change while (x <= userValue)to while (x < userValue)
Again, arrays are 0 based, change:
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
to
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);
There are few problems in the code :
Update this (x <= userValue) to (x<userValue) , else it will give array index out of bounds exception
Start the for loop in minMaxFunction from 1 , since you have already stored the value of arr[0] to min and max like below . This is just an optimization in the code.
for (i = 1; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
This line in main method should have index 0 and index 1 . There is no index 2 since you have declared the array of length 2 , else it will give array index out of bounds exception
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);

How do I rewrite my code so that the value of 0 does not give me a out of bounds error in java?

package problems;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Single {
public static void main(String[] args) {
//create the array of random integers
int[] values = new int[10];
//Assign random values to each space in the array
for(int x = 0; x <values.length; x++) {
int y;
y = (int) (Math.random() * 10);
values[x] = y;
}
System.out.println(Arrays.toString(values));
//The digits array is an array with 10 random integers
//Create an array that holds the 10 digits (0-9)
int[] digits = new int[10];
for(int x = 0; x <= values.length; x++) {
digits[values[x] -1]++;
}
//display each count of the numbers
for(int x = 0; x <values.length; x++)
if ((x + 1) % 5 == 0)
System.out.println(digits[x] + " " + (int)(x + 1));
else
System.out.print(digits[x] + " " + (int)(x + 1) + "'s ");
}
try to change this:
for(int x = 0; x <= values.length; x++) {
digits[values[x] -1]++;
}
to this:
for (int x = 0; x < values.length ; x++) {
digits[values[x]]++;
}

Issues when taking Dice one and Dice two with the same value and adding it to an integer

I am currently trying to get the number of times the two dice have identical values. This is what I have so far.
public static void main(String [] args)
{
System.out.print("Enter the amount of rolls you want to do: ");
Scanner scan = new Scanner(System.in);
int r = scan.nextInt();
final int FACES = 6, ROLLS = r;
int [] rollCount = new int [FACES];
int [] rolCount = new int [FACES];
Die d1 = new Die();
Die d2 = new Die();
int myRoll = 0;
int myRollTwo = 0;
int Ident = 0;
int i = 0;
while (i <= 1)
{
int ii = 0;
int iii = 0;
for (ii = 1; ii <= ROLLS; ii++)
{
myRoll = d1.roll();
rollCount[myRoll - 1]++;
}
for (ii = 1; ii <= ROLLS; ii++)
{
myRollTwo = d2.roll();
rolCount[myRollTwo - 1]++;
iii++;
}
if (myRoll == myRollTwo)
{
Ident++;
}
if (iii == ROLLS)
{
i++;
}
}
System.out.println("Die Number\tDie One\tDie Two\tTotal\t Amount of Identical Rolls");
for (i = 0; i < rollCount.length; i++)
{
System.out.println((i + 1) + "\t\t\t" + rollCount[i] + "\t\t" + rolCount[i] + "\t\t" + ((rollCount[i] + rolCount[i])*(i + 1)) + "\t\t" + Ident);
}
}
I know that the if statement near the end of the while loop wouldn't work because it would only do it once, so how exactly would I go about getting the number of times the two dice were the same?

string multiplication using a big integer class

I'm trying to write a code that multiplies two strings of integers. I'm not too sure where it's going wrong... It works for some numbers, but is horribly wrong for others. I'm not asking for a full solution, but just a hint (I seriously appreciate any help possible) as to where I'm making the obviously silly mistake. Thanks in advance.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a big integer. ");
String t = scan.nextLine();
System.out.print("And another. ");
String s = scan.nextLine();
BigInt a = new BigInt(t);
BigInt b = new BigInt(s);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
System.out.println(a + " * " + b + " = " + a.mul(b));
System.out.println(a + " / " + b + " = " + a.div(b));
}
}
class BigInt {
public BigInt() {
n = new int[1];
}
public BigInt(String s) {
n = new int[s.length()];
for (int i = 0; i < n.length; ++i) {
n[n.length - i - 1] = s.charAt(i) - '0' ;
}
}
private BigInt(int[] n) {
this.n = new int[n.length];
for (int i = 0; i < n.length; ++i) {
this.n[i] = n[i];
}
}
public String toString() {
String s = "";
for (int i : n) {
s = i + s;
}
return s;
}
public BigInt mul(BigInt o) {
int carry = 0;
int s = 0;
int digit;
int subtotal = 0;
int total = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[n.length + o.n.length];
for (int i = 0; i < o.n.length; ++i) {
int bottom = i <= o.n.length ? o.n[i] : 0;
for (s = 0; s <= n.length; ++s){
int top = s < n.length ? n[s] : 0;
int prod = (top * bottom + carry);
if (s == (max-1)) {
total = Integer.valueOf((String.valueOf(prod) + String.valueOf(subtotal)));
carry = 0;
digit = 0;
subtotal = 0;
break;
}
if (prod < 10) {
digit = prod;
subtotal += digit;
carry = 0;
}
if (prod >= 10); {
digit = prod % 10;
carry = prod / 10;
subtotal += digit;
}
}
result[i] = total;
}
return new BigInt(trim(result));
}
private int[] trim(int[] nums) {
int size = nums.length;
for (int i = nums.length - 1; i > 0; --i) {
if (nums[i] != 0) {
break;
}
--size;
}
int[] res = new int[size];
for (int i = 0; i < size; ++i) {
res[i] = nums[i];
}
return res;
}
private int[] n;
}
A quick test using:
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
System.out.println(x + " * " + y + " = " + new BigInt(Integer.toString(x)).mul(new BigInt(Integer.toString(y))));
}
}
demonstrates that somehow your multiply of x * y is actually multiplying by 10x * y. That should give you a clear hint to the problem.

Sorting an array and using binary search

I've already gotten this program to run and it almost gives me the answer I want. After running the whole program, it's supposed to print out the index of the key and what the key is equal too. I cannot for the life of me figure out how to get the index into the final message in the console. For example, if you have an array of {0,1,2,3,4,5,6,7,8,9} and your key is 0, it's supposed to return: list[0] = 0. I labeled the part I think where my problem lies with "(index???)"
import java.util.Scanner;
public class PartA {
public static void main(String[] args){
System.out.println("Please enter 10 double values:");
double [] array = inputArray();
selectionSort(array);
printArray(array);
System.out.println("Please enter a search key:");
Scanner input = new Scanner(System.in);
double key = input.nextDouble();
double x = binarySearch(array,key);
if (x != -1)
System.out.println("list[" + (index???) + "] = " + key);
else
System.out.println(key + " is not on the list");
}
public static double[] inputArray(){
Scanner array = new Scanner(System.in);
double [] list = new double[10];
for(int i = 0; i < list.length; i++){
array.hasNextDouble();
list[i] = array.nextDouble();
}
return list;
}
public static void selectionSort(double[] list){
double array[] = new double [list.length];
for(int i = 0; i < list.length; i++){
for(int j = 0; j < list.length; j++){
if (list[i] < list[j]){
double x = list[i];
list[i] = list[j];
list[j] = x;
}
}
}
}
public static void printArray(double[] list){
for (int i = 0; i < list.length; i++){
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.println();
}
public static int binarySearch(double []list, double key){
int low = 0, high = list.length - 1;
while(high >= low){
int mid = (low + high)/2;
if(key < list[mid])
high = mid - 1;
else if(key == list[mid])
return mid;
else low = mid + 1;
}
return -1;
}
}
I also mentioned already in the comments of the Question the solution, but for the sake of completeness i post this answer.
public class Main {
public static void main(String[] args){
System.out.println("10 double values:");
double [] array = {0,1,2,3,4,5,6,7,8,9};
selectionSort(array);
printArray(array);
double key = 4;
System.out.println("Searched Key: " + key);
int idx = binarySearch(array,key); //use int instead of double
if (idx != -1)
//use the variable identifier to print the index
System.out.println("list[" + idx + "] = " + key);
else
System.out.println(key + " is not on the list");
}
public static void selectionSort(double[] list){
double array[] = new double [list.length];
for(int i = 0; i < list.length; i++){
for(int j = 0; j < list.length; j++){
if (list[i] < list[j]){
double x = list[i];
list[i] = list[j];
list[j] = x;
}
}
}
}
public static void printArray(double[] list){
for (int i = 0; i < list.length; i++){
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.println();
}
public static int binarySearch(double []list, double key){
int low = 0, high = list.length - 1;
while(high >= low){
int mid = (low + high)/2;
if(key < list[mid])
high = mid - 1;
else if(key == list[mid])
return mid;
else low = mid + 1;
}
return -1;
}
}
Working example with Ideone:
http://ideone.com/WXrJPi
I think your code works perfect. You just have to replace (index???) with x and change the type of x from double to int so that is does not print the the value as a double value.
int x = binarySearch(array,key);
if (x != -1)
System.out.println("list[" + (x) + "] = " + key);
else
System.out.println(key + " is not on the list");
}
Output:
Please enter 10 double values:
0
1
2
3
4
5
6
7
8
9
list[0] = 0.0
list[1] = 1.0
list[2] = 2.0
list[3] = 3.0
list[4] = 4.0
list[5] = 5.0
list[6] = 6.0
list[7] = 7.0
list[8] = 8.0
list[9] = 9.0
Please enter a search key:
5
list[5] = 5.0

Categories

Resources