I've created a program that allows a user to enter in Journal entries (up to 7 days) and then allows a person to call up one of those days after they enter in an entry. Unfortunately, this has left me with some weird string error that I'm not familiar with.
Code as follows:
public class eDiary{
public static void main (String args[]){
int[] days = new int[7];//get our days
days[0] = 1;//start with 1 and not 0
days[1] = 2;
days[2] = 3;
days[3] = 4;
days[4] = 5;
days[5] = 6;
days[6] = 7;
String [] events = new String[7];//events for the days
int i = 0;
//asks for input and counts
for(i=0; i<7; i++){
String event = Console.readString("Tell me the major event of day " + days[i] + "\n");
events[i] = event;
}
int journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
while (journal_entry != 0) {
System.out.println(events);
journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
//get r dun!
The input and output:
Tell me the major event of day 1
one
Tell me the major event of day 2
two
Tell me the major event of day 3
thre
Tell me the major event of day 4
four
Tell me the major event of day 5
five
Tell me the major event of day 6
six
Tell me the major event of day 7
seven
Enter what day you want to hear or Enter 0 to stop
1
[Ljava.lang.String;#10181f5b
Enter what day you want to hear or Enter 0 to stop
0
Howdy y'all!
Thanks a lot for the quick responses. One thing it seems to be doing now is when replacing
System.out.println(events);
with
System.out.println(events[journal_entry]);
Now gives me input such as this:
Tell me the major event of day 1
first day
Tell me the major event of day 2
second day
Tell me the major event of day 3
third day
Tell me the major event of day 4
fourth day
Tell me the major event of day 5
fifth day
Tell me the major event of day 6
sixth day
Tell me the major event of day 7
seventh day
Enter what day you want to hear or Enter 0 to stop
1//the day im asking for
second day//spitting out the next day's entry instead of the first day's entry
Enter what day you want to hear or Enter 0 to stop
0//this is me stopping it
It's not an error.
System.out.println(events);
In this line you are trying to print the array, but that statement doesn't print the array contents, it only prints the object class name followed by its hashcode.
To print the array content you have to use
System.out.println(Arrays.toString(events));
Or, if you want, loop through the array and print its values
The [Ljava.lang.String;#10181f5b stuff is what you get when you explicitly or implicitly call Object.toString() and the target object's class doesn't override toString(). In this case, the issue is that Java array types do not override toString().
If you want to output an array, use java.util.Arrays.toString(...) to convert it to a String, then output that.
But in this case, you actually need to output a specific entry, not the entire array. The fix is to change
System.out.println(events);
to
System.out.println(events[journal_entry]);
For the record, the stuff above consists of the classes internal name ("[Ljava.lang.String;") and the object's identity hashcode (in hexadecimal).
This is not a "weird error string".
The output you are getting is because:
In Java, each object has toString() method, the default is displaying the class name representation, then adding # and then the hashcode.
You should use Arrays#toString(), which is implemented this way:
3860 public static String toString(int[] a) { {
3861 if (a == null)
3862 return "null";
3863 int iMax = a.length - 1;
3864 if (iMax == -1)
3865 return "[]";
3866
3867 StringBuilder b = new StringBuilder();
3868 b.append('[');
3869 for (int i = 0; ; i++) {
3870 b.append(a[i]);
3871 if (i == iMax)
3872 return b.append(']').toString();
3873 b.append(", ");
3874 }
3875 }
This will help you to better understand arrays.
Of course you can manually loop on the array and print it:
for(String event: events) {
System.out.println(event);
}
There is nothing wrong and that's not an error message.
Instead, it's the string representation of an array. Consider this line:
System.out.println(events);
You are printing the whole array, so you get that representation -- which happens to be a bit ugly, indeed. You want to print only one element, the one corresponding to the selected day. Use:
System.out.println(events[journal_entry]);
And perform bound checks.
This is not an error. You want to print the value of variable events. [Ljava.lang.String;#10181f5b means that events is an array of type java.lang.String and 10181f5b is hashcode of this variable. What you want to println is event[i] where i is the number of a day.
In java array's are consider as object. you are printing the event array object that's not what you want.
You need to print name of the day in a week. You need to replace
System.out.println(events);
to
System.out.println(events[journal_entry]);
It won't print out the answer correctly because you just pointed System.out.println() to events which is supposed to be an array pointer and not the actual variable. You should just replace this line with
System.out.println(events[journal_entry]);
For it to make sense. Run it with the conmmand and see if it will run properly.
Thanks for all the responses! I was able to resolve the issue. Here's the code if anyone is curious:
public static void main (String args[]){
int[] days = new int[7];//get our days
days[0] = 1;//start with 1 and not 0
days[1] = 2;
days[2] = 3;
days[3] = 4;
days[4] = 5;
days[5] = 6;
days[6] = 7;
String [] events = new String[7];//events for the days
int i = 0;
//asks for input and counts
for(i=0; i<7; i++){
String event = Console.readString("Tell me the major event of day " + days[i] + "\n");
events[i] = event;
int journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
while (journal_entry != 0) {
System.out.println("On day " + days[i = 0] + " " + events[journal_entry - 1]);
journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
Related
I'm taking beginner's java course and I have this kind of task:
User inputs word + number, for example, "animal" + "age":
horse:3
dog:5
parrot:2
cat:7
I have to make the program to print out the age of the oldest animal.
For example like this:
The age of the oldest animal is: 7
Now, this is what I have written so far. My problem is that I don't know how to make the program compare the numbers...
while (true) {
String luettu = x.nextLine(); // user inputs animals and numbers
if (dataIn.equals("")) { // when inputs nothing program stops
break;
}
// Here I separate the animal and number with star symbol
String[] separatedData = dataIn.split(":");
// From now on, I'm supposed to focus on the numbers, create the rule for how to find the highest value
x = x Integer.valueOf(separatedData[1]); // Must target the values in the index 1 (the numbers) but how?
}
int maxNumber = separatedData.lenght;
int i = 0;
// I don't know how to loop and compare the numbers... and I thin "while" doesn't make sense here
while ( i < size of separatedData) {
if(maxNumber < separatedData) {
maxNumber = separatedData;
}
System.out.println("The age of the oldest animal is: " + maxNumber); // printing the result
So half of the code is a mess and I'm stuck.
Please help me and if you can give explanations, that would be great, thanks! :)
When finding the maximum of something, set the max to the smallest value possible. That would be
maxAge = Integer.MIN_VALUE
Then set a string variable like this.
String oldestAnimal = "";
Now as you loop thru the values, compare the current age to max. If age is larger, set
max to age and set oldestAnimal to the animal associated with that age.
The compare would be like:
if (age > max) {
// set appropriate values.
}
When you are done, you will have the results.
I'm having troubles figuring out how to increment a variable through an if statement, and allow it to be registered if called upon in a different if statement. I'm currently working on an assignment that mimics a menu for inputs. As shown, the user inputs a specific command, and on A, B, or C, they enter 3 scores/values. A separate input could be F, and on this input, it's supposed to show how many failures for each company, A, B, C has.
System.out.print("\nPlease enter a command:"); //Starts command prompt
String menuPrompt = scanner.next(); //Takes next input and uses one of the following if statements
if (menuPrompt.equals("a")) {
double aNum1;
double aNum2; //initializes a score inputs
double aNum3;
System.out.print("\nEnter number 1:");
aNum1 = scanner.nextDouble();
System.out.print("\nEnter number 2:");
aNum2 = scanner.nextDouble(); //asking for inputs of test values of company a
System.out.print("\nEnter number 3:");
aNum3 = scanner.nextDouble();
if(aNum1 < -6.0 || aNum1 > 12.3) {
aFailure = aFailure + 1;
}
if(aNum2 < -6.0 || aNum2 > 12.3) {
aFailure = aFailure + 1; //checks to see if inputted value is a failure, if so, failure ticks up 1.
}
if(aNum3 < -6.0 || aNum3 > 12.3) {
aFailure = aFailure + 1;
}
There are two other similar lines of code alike to this one just for "b" and "c". I initialized aFailure, bFailure, and cFailure at the top of the class and set their values to 0. After the if statements for the a, b, c prompts, I have this:
} else if (menuPrompt.equals("f")) {
System.out.print("\nAzuview Failures: " + aFailure);
System.out.print("\nBublon Failures: " + bFailure); //Lists total failures for each company
System.out.print("\nCryztal Failures: " + cFailure);
I'm not sure exactly how these variables are supposed to be defined, or if my formatting is even correct, help?
When you initialized a variable in a loop it is reinitialized every time the loop run again. When you initialized it outside of the loop it stays the same variable even in the loop. The concept behind a for loop is base on that.
In this example, the count is going to be incremented in every update of the while loop
So the count is going to be set to 0 and goes up by 1 until it reaches 9 when it will exit the loop
var count = 0;
while(count <10){
count++;
}
but in this one every time is going to loop in it. It reinitialized your variable count to 0 and increment it to 1. So every loop a new count is created and set to 1
while(true){
var count =0;
count++;
}
My first response on stack hope it helps you understand the concept a little better :)
I'm fairly sure I fixed this, instead of initializing within a while loop, I initialized it outside of the while loop and it seemed to fix this, any input on explaining the concepts behind this would be awesome!
I have code that has multiple methods and we're suppose to call said methods to help us format an image made from characters. The image is a cake and uses characters like "=", "\", "^" and "/" among others I have yet to get too. Anyways using odd user input between 3 and 9 (3,5,7,9), we're suppose to format it so it prints out the other method and then the one before it. So If one method prints out "[|_______||_______||_______|]" and the other one prints out "[|___||_______||_______|____|]" with it's size varying with user input. If input is 3 it's suppose to print out both methods once as the hint was that it uses half the user input to decide how often to print something. The problem goes when I go beyond 3 to 5 or 7 as I get something like
/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\
[|_______||_______||_______||_______||_______|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
[|_______||_______||_______||_______||_______|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
\=============================================/
It's suppose to print one then the other, not two at once. Not only that but in total the methods are only suppose to print out 4 times if it's 5 so I'm suppose to get something like this instead. I think it's how I formatted my for loops for that method but I could be wrong, thank you in advance to anyone willing to help.
/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
[|_______||_______||_______||_______||_______|]
[|___||_______||_______||_______||_______|___|]
\=============================================/
My "drawFullBrick" method prints out the [|_______||_______||_______||_______||_______|] part while the "drawHalfBrick" prints out the [|___||_______||_______||_______||_______|___|] part
public static void drawBrickStack (int sizeParam) {
System.out.print("/");
for (int count = 0; count < sizeParam * 9; count++)
System.out.print("^");
System.out.print("\\ \n");
for (int count = 0; count < sizeParam/2; count++)
{
for (int nestedCount = 0; nestedCount < sizeParam/2; nestedCount++)
{
drawFullBrickLine(sizeParam);
}
drawHalfBrickLine(sizeParam);
}
I need help on how to minus out the value in my object which is (25) when a random number (num) has been generated. I have written my code below but there seem to be a problem in my last line.
StickBag s1 = new StickBag(25);
int randNum = 1 + (int)(Math.random()*2);
int num = 1 + (int)(Math.random()*11);
for(int i = 0; i < 25 ; i++)
{
if(randNum == 1)
{
System.out.println("Computer player 1 chooses " + num + " sticks. ");
StickBag = StickBag - num;
}
For e.g. If a random number that is generated is 5 , then the total value in my object (25) will minus the value that was generated randomly (5) and therefore my object will then have the value 20 in it
I hope i have made myself clear
The trouble with the line
StickBag = StickBag - num;
is that StickBag is the name of a class. You actually want to refer to an instance of that class.
In your program, you have an instance of StickBag called s1. Therefore, what you probably want to write is something like this:
s1.stickCount = s1.stickCount - num;
That's with the assumption that stickCount is a public attribute of the class StickBag, and that it's what gets initialized to the value 25 when you do new StickBag(25).
Let me suggest that you rename s1 to something more expressive, such as gameBag. That might not suit your particular concept, but whatever it is, try to use words rather than single letters and numbers.
Also, num is pretty vague and could be renamed to something more specific, such as playerMove. And you might want to use the -= operator to perform the subtraction. If you were to apply all three of my suggestions, the line would look like this:
gameBag.stickCount -= playerMove;
If stickCount is private and you have to access its value with getStickCount() and set its value with setStickCount(), you would write the following.
gameBag.setStickCount(gameBag.getStickCount() - playerMove);
Note that in this case you can't use the -= operator. (Some programming philosophies insist on using getters/setters and others don't. The debate isn't germane to this question and you can find plenty of material on it elsewhere.)
New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;