Build/Output Histograms using Arrays Where i'm wrong?
This code takes 5 inputs from user in array and show the number of stars for example if user enter 3 then *** would be shown and so on .Where i'm wrong ?
public class P20 {
public static void main(String[] args) {
int[] anArray;
int Number;
//setup variable value
anArray = new int [10];
System.out.println("Enter some numbers between 1 and 100.");
for (int i = 0; i < 10; i++) {
System.out.println(i);
anArray[0] = 1-9;
anArray[1] = 10-19;
anArray[2] = 20-29;
anArray[3] = 30-39;
anArray[4] = 40-49;
anArray[5] = 50-59;
anArray[6] = 60-69;
anArray[7] = 70-79;
anArray[8] = 80-89;
anArray[9] = 90-100;
if(anArray > 0) {
System.out.println("*"+Number );
else if(anArray > 20)
{
System.out.println("**"+Number );
}
else if (anArray > 30)
{
System.out.println("***"+Number );
}
else if (anArray > 40)
{
System.out.println("****"+Number );
}
else if (anArray > 50)
{
System.out.println("*****"+Number ); }
}}
This code takes 5 inputs from user in array and show the number of stars for example if user enter 3 then *** would be shown and so on .Where i'm wrong ?
This code doesn't take inputs from the user.
You want the user to input a value and then you print the number of stars he/she wrote. You could do this like that:
public class P20 //Why don't you try giving names that are easier to remember
{
public static void main(String[] args)
{
for (int i=0; i<args[0]; i++)
{
System.out.print("*");
}
}
Where args[0] is the first argument given to the program when called:
java P20 3
Anyway, let me try to point out what some of the mistakes of your code are:
When you wrote:
anArray[0] = 1-9;
Did you really want to write that wich means "Let the 0th element of the array be the number 1 minus 9" (=-8)?
Or did you intent to input an interval? (Meaning the numbers from 1 to 9).
Then later on you say
if(anArray > 0)
Which doesn't make sense to me since anArray is an int[] variable and not an int variable. This means that anArray is not a variable which points directly to a number, but one pointing to an array object which holds several int values.
if(anArray > 0) {
you always will be > 0 so you always get only 1 x *
you hve to modify your if clause like that:
if (anArray > 0 && anArray < 20){
and so on...
edit:-----------------------------------------------------------
like you requested:
public String stars(int n) {
if (n == 1){
return "*";
}else{
return "*" + stars(n-1);
}
}
Related
I'm currently working on an assignment for my programming class and I cannot figure out why my output is coming out wrong.
We are supposed to "Print the “Difference” of population from the previous year. (Of course, this value is blank for the first year in the list.)
Use format control to print the values for Year, Population value and Difference from previous year. "
And my teacher gave us what the output is supposed to look like:
Desired Output:
But I keep getting this:
My Output:
This is my code:
import java.util.Scanner;
import java.io.*;
public class AssignmentOne
{
public static void main(String[] args) throws IOException
{
// Array Version
ArrayVersion();
System.out.println("Finished Array Version of Assignment");
}
// Method for ArrayVersion
public static void ArrayVersion() throws IOException
{
// Year as variables
int year = 1950;
final int ARRAY_SIZE = 41;
// Array to use for Population data
int[] population = new int[40];
// Call the method to get data into array
population = getDataFromFile("USPopulation.txt");
if(population == null)
{
System.out.println("Error: Population did not load");
return;
}
// Output
System.out.println("This is the Simple Array Version of \nPopulation Data US");
System.out.println("\nYear \tPopulation \tDifference");
System.out.println("");
System.out.printf("%d \t%,d,000\n", year, population[0]);
for(int i = 1; i < population.length; i++)
{
System.out.printf("%d \t%,d,000 \t%,d,000 \n", ++year, population[i], Math.abs(population[i] - population[++i]));
}
// Calculating the average + displaying it
int sum = 0;
for(int g = 0; g < population.length; g++)
{
sum += population[g];
}
int average;
average = sum / population.length;
System.out.println("Average:" + average);
}
// Method to get data from specified "filename" into an array of ints
public static int[] getDataFromFile(String USPopulation) throws IOException
{
// Array to use for Population data
// Opening file
File file = new File("E:/Programming 2/Assignment 1/src/USPopulation.txt");
Scanner inputFile = new Scanner(file);
int fileSize = 0;
while(inputFile.hasNext())
{
inputFile.nextInt();
fileSize++;
}
Scanner input2 = new Scanner(file);
int[] fileData = new int[fileSize];
for(int i = 0; i < fileSize; i++)
{
fileData[i] = input2.nextInt();
}
// System.out.println(fileData[40]);
// return the array fileData
return fileData;
}
population[++i]
There's your problem.
The prefixed increment simply increments the value of i before it gets the value, where i++ gets the value then increments i.
Just change it to population[i+1] and you'll be good. :P
Edit:
for(int i = 1; i < population.length; i++)
{
System.out.printf("%d \t%,d,000 \t%,d,000 \n", ++year, population[i], population[i] - population[i-1]);
}
The whole problem is in this line:
System.out.printf("%d \t%,d,000 \t%,d,000 \n", ++year, population[i], Math.abs(population[i] - population[++i]));
First, using ++i bumps your loop counter i one extra time per iteration, so you're only looking at every other year. No doubt you were trying to find the difference between one year's population and that of the next year; the correct way to look at next year's population would have been population[i+1]. But, as you say, using population[i+1] eventually gives you IndexOutOfBoundsException. Well, that's because when i is pointing to the last year, i+1 points beyond the end of the array of population data.
The second problem, then, is that you really want to be finding the difference between each year's population and that of the previous year: population[i] - population[i - 1]. So now, when i points at the last year, i-1 will still be within the array bounds, and because your loop actually starts with i == 1, i - 1 will still be a valid index.
I was recently trying to build a program that takes two inputs and checks whether they are equally represented in other bases(bases are up till 20). But i keep getting the index out of bounds exception at line number 28...what to do?
For example: 12(base 10) = 5(base 3) [both are represented as '12' in their respective bases.]
import java.util.Scanner;
import java.util.Arrays;
class Bases
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two Numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Thank You for inputting the numbers!");
String basea[] = new String[20];
String baseb[] = new String[20];
int i=0 , j=0;
for( i=0;i<20;i++)
{
basea[i] = convert(a,i+1);
baseb[i] = convert(b,i+1);
}
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
if(i!=20){
if(i==0){
i=9;
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else System.out.println("Numbers dont match at all till base 20!!");
}
private static String convert(int number,int base)
{
return Integer.toString(number,base);
}
}
for(j=0;i<=19;j++)
This above loop should be j <= 19
for(j=0;j<=19;j++)
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
You can see in this original snippet of code you had a typo
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++) <---- the middle parameter is 'i' instead of 'j'
{
Simply fix this by fixing your typo, and if you want to you can make it <20 for some added neatness.
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
/*
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
*/
class Pro4
{
int palindrome(int x)
{
int n=x,rev=0;
while(n!=0)
{
rev=rev*10+n%10;
n=n/10;
}
if(x==rev)
return x;
else
return 0;
}
public static void main(String args[])
{
int lar=0,i=0,j=0,x,k=100,l=100;
Pro4 obj=new Pro4();
for(i=100;i<=999;i++)
for(j=100;j<=999;j++)
{
x=obj.palindrome(i*j);
if(x!=0)
{
lar=x;
k=i;
l=j;
}
}
System.out.println(lar+","+k+","+l);
}
}
please, do following change in your code,
if(x != 0 && x>lar)
{
lar=x;
k=i;
l=j;
}
Output :
906609,913,993
UPDATED :
into your previous code which is only contain x!=0 condition,
906609 palindrome become at i = 913, j = 993,
then again next 580085 palindrome appear into double digit range at i = 995, j = 583.
so, once 913,993(which gives 906609) processing answer getting but lake of proper condition it will replace by 995,583(which gives 580085) that's why tou were got 580085.
I'm making a card game, and I've arrived at the shufflin' time.
I've to shuffle a few cards (that are chosen before from the user, so they're not always the same amount) and then display them to the user one by one.
As I'm still developing the game's logic I'm displaying cards' name by changing a button text.
But I get stuck when I try to get the cards' name and set them as the button's text.
What happens is me gettin' a blank button or just with "Masons" or "Villager" String. Infact if I check the log I see that all the others cards(characters) get displayed as "null".
This is how I tried to achieve the goal (Yes I'm a newbie):
This is the head:
int demoniac;
int guard;
int masons;
int medium;
int mythomaniac;
int owl;
int villager;
int werehamster;
int all;
int i;
int t;
String[] characters = new String[24];
Button randomButton;
My method to addAll the cards(characters):
public void addAll(){
for(i = 0; i < all; i++){
add(demoniac, "Demoniac");
add(guard, "Guard");
add(medium, "Medium");
add(mythomaniac, "Mythomaniac");
add(owl, "Owl");
add(werehamster, "Werehamster");
add(villager, "Villager");
add(masons, "Masons");
}
}
My method to add and manage the various types of cards(characters):
public int add(int character, String name){
if(character != 0 && name == "Villager"){
for(t = 0; t < character; t++){
i+=t;
characters[i] = name;}
}
else if(character == 2 && name == "Masons"){
characters[i] = name;
i++;
characters[i] = name;
Toast.makeText(randomSelection.this, "works", Toast.LENGTH_SHORT).show();
}else if(character != 0){
characters[i] = name;
}
return i;
}
To randomize:
public void randomize(){
Collections.shuffle(Arrays.asList(characters));
for (int s = 1; s < characters.length; s++)
{
System.out.println(characters[s]);
}
}
The method to display a different card(character) each time the user clicks the button:
public void show(View view){
for (int s = 1; s < characters.length; s++)
{
randomButton.setText(characters[s]);
}
}
EDIT:
I've noticed the no sense for loop I've done, by the way you should know although most of the characters are only 1 of their kind (demoniac, guard, etc..) there are 2 Masons and from 5 to 12 Villagers, so We need to retrieve these ints and add as much Strings to the Array as much we're told from those ints.
Example: If I get 6 Villagers, I've to add the String "Villager" 6 times into the String Array.
Then I've set that s value to 1 'cause I've to display the first
String ([0]) as soon as the Activity gets started, so on the OnCreate() method.
Maybe I'm wrong, if so I please you to correct me!
Getting a blank button or just with "Masons" or "Villager" String
That is because you only set the Button's text with the last element of the list. Which is either null or "Masons" (not seeing how it could be "Villager").
for (int s = 1; s < characters.length; s++)
{
randomButton.setText(characters[s]);
}
If I check the log I see that all the others cards(characters) get displayed as "null"
You only set position 0 of your array. For example, you don't initialize the positions, so these int values default to 0.
int demoniac;
int guard;
int all;
Then
for(i = 0; i < all; i++){
add(demoniac, "Demoniac");
add(guard, "Guard");
Really, that loop shouldn't be entered because all equals 0.
Additionally
Collections are zero-indexed, so this doesn't print element 0. You need to set int s = 0;.
for (int s = 1; s < characters.length; s++)
It isn't clear to me what the add(int character, String name) method is returning, but if you explain it, I will update this answer.
I believe this code fulfills most of what you are trying to achieve
// Where the characters are stored
private ArrayList<String> characters;
public void initDeck() {
if (characters == null)
characters = new ArrayList<String>();
// Extract the numbers if you actually need them, otherwise, they just are constants
addCharacter("Demoniac", 1, characters);
addCharacter("Guard", 1, characters);
addCharacter("Medium", 1, characters);
addCharacter("Mythomaniac", 1, characters);
addCharacter("Owl", 1, characters);
addCharacter("Werehamster", 1, characters);
addCharacter("Villager", 5, characters);
addCharacter("Masons", 1, characters);
}
public void addCharacter(String name, int amount, ArrayList<String> cards) {
if (amount < 0) {
throw new IllegalArgumentException("Must add a non-negative number of characters for " + name);
}
// Don't use '==' for Strings
if (name.equals("Villager")) {
if (amount != 5 || amount != 12) {
throw new IllegalArgumentException("There can only be 5 or 12 " + name);
}
}
for (int i = 0; i < amount; i++) {
cards.add(name);
}
}
public int searchCharacters(String character, ArrayList<String> cards) {
return cards.indexOf(character);
}
public Map<String, Integer> getAllCharacterPositions() {
Map<String, Integer> allPositions = new LinkedHashMap<String, Integer>();
for (int i = 0; i < characters.size(); i++) {
allPositions.put(characters.get(i), i);
}
return allPositions;
}
void run() {
// initialize the characters
initDeck();
// shuffle them
Collections.shuffle(characters);
// print them all out
for (int i = 0; i < characters.size(); i++) {
System.out.printf("%d: %s\n", i, characters.get(i));
}
// Find the position of a character
System.out.println();
String findCharacter = "Owl";
// Option 1 -- always linear search lookup
System.out.printf("%d: %s\n", searchCharacters(findCharacter, characters), findCharacter);
// Option 2 -- one-time linear scan, constant lookup
Map<String, Integer> positions = getAllCharacterPositions();
System.out.printf("%d: %s\n", positions.get(findCharacter), findCharacter);
// Get a random character
System.out.println();
Random rand = new Random(System.currentTimeMillis());
int randPos = rand.nextInt(characters.size());
System.out.printf("%d: %s\n", randPos, characters.get(randPos));
// randomButton.setText(characters.get(randPos));
}
Given the array is already shuffled, just look at the first card:
public void show(View view){
randomButton.setText(characters[0]);
}
If you want to navigate that deck I suggest you put the shuffled list in to a Queue, where you can look at the next card (peek) or take the next card (poll):
private static Queue<string> buildNewShuffledDeck(String[] characters){
List<String> shuffledCharacterList = new ArrayList<String>(characters);
Collections.shuffle(shuffledCharacterList);
Queue<string> deck = new ArrayDeque(shuffledCharacterList);
return deck;
}
public void show(View view){
String nextCard = deck.peek();
if (nextCard != null)
randomButton.setText(nextCard);
else
//deck is empty...
}
Then to take from the deck, say on the random button click:
String nextCard = deck.poll();
General advice on arrays: Stop using them in favor of other data types that are far more useful and interchangeable.
Then next step advice, make a class that represents a Card and stop using Strings, the string you currently have is just one property of a card.
You are just displaying the last character name that you add
Replace with this
public void show(View view){
Random r = new Random(System.currentTimeMillis());
randomButton.setText(characters[r.nexInt(characters.length)])
}
I am processing elements of an ArrayList in random order, generally by printing them out. I would like to detect when the randomly selected index is 0 or 1 so as to perform special handling for those cases, where the handling for index 0 is partially dependent on whether index 1 has previously been processed. Specifically, nothing is immediately printed when index 1 is processed, but if it is processed then when index 0 is subsequently processed, both the index 1 and the index 0 values are printed. In any event, the loop is exited after ten iterations or after processing index 0, whichever comes first.
I tried to implement this using if statements, but there where obvious flaws with that one. I have searched everywhere for any examples but found none. I have begun to consider using sorting algorithms or threads to hold the first value found then continue looping until it sees the second the print it out. I would appreciate any help possible.
Here is my code:
public static void random_sortType(){
types = new ArrayList<String>();
types.add("Start");
types.add("Starting");
types.add("Load");
types.add("Loading");
types.add("End");
ran = new Random();
int listSize = types.size();
String tempEventType;//the temp variable intended to hold temporary values
for(int i = 0; i < 10; i++){ //the loop goes round the ArrayList 10 times
int index = ran.nextInt(listSize);//this produces the random selection of the elements within the list
if(index == 0){
out.println(types.get(index));
out.println();
break;
}
if(index == 1){
tempEventType = types.get(index);
if(index == 0){
tempEventType = types.get(0) + " " + types.get(1);
out.println(tempEventType);
break;
}
}/*if(index == 0){
tempEventType = types.get(0) + " " + types.get(1);
out.println(tempEventType);
break;
}*/
//out.print("Index is " + index + ": ");
//out.println(types.get(index));
}
}
You need to store the random generated index into a global variable and update it everytime a random number is generated. It should be something like this.
public static void random_sortType(){
types = new ArrayList<String>();
types.add("Start");
types.add("Starting");
types.add("Load");
types.add("Loading");
types.add("End");
` int previousIndex;
ran = new Random();
int listSize = types.size();
String tempEventType;//the temp variable intended to hold temporary values
for(int i = 0; i < 10; i++){ //the loop goes round the ArrayList 10 times
int index = ran.nextInt(listSize);//this produces the random selection of the elements within the list
previous_index =index;
if(index == 0){
out.println(types.get(index));
out.println();
break;
}
if(index == 1){
tempEventType = types.get(index);
if(previousIndex == 0){
temp EventType = types.get(0) + " " + types.get(1);
out.println(tempEventType);
break;
}
According to your description, these are the basic requirements for your application:
Process ArrayList in random order
Processing = printing value at randomly selected index
Make 10 attempts to process items in the list.
Detect when random index is 1 or 0.
if 1
don't process, but flag it was selected.
if 0 && 1 is flagged
process 0 and 1
exit
If these requirements are correct, here is the implementation I came up with:
import java.util.ArrayList;
import java.util.Random;
import static java.lang.System.*;
public class RandomSort {
private static final int MAX_ATTEMPTS = 10;
private static boolean wasOneSelected = false;
public static void main(String[] args) {
ArrayList<String> types = new ArrayList<>(5);
types.add("Start");
types.add("Starting");
types.add("Load");
types.add("Loading");
types.add("End");
random_sortType(types);
}
public static void random_sortType(ArrayList<String> types) {
Random ran = new Random();
int lastIndex = types.size() - 1; // index range is from 0 to 4
for (int i = 0; i < MAX_ATTEMPTS; i++) {
int index = ran.nextInt(lastIndex);
if ( (index == 0) && wasOneSelected) {
process(types.get(index) + " " + types.get(index + 1));
break;
} else if (index == 1) {
wasOneSelected = true;
} else {
process(types.get(index));
}
}
}
public static void process(String str) {
out.println("Processing: " + str);
}
}
The key here is the inclusion of the boolean wasOneSelected initialized to false. Once it is set to true, it will never be false again for the duration of the application. The if-else block handles all branching within the loop, and I favored wrapping the println call into a method called "process" for readability purposes to align it more closely with your description.
Feedback appreciated :)