System.out.println("Composition Statistics for Families with Two Children: \n");
System.out.println("Total Number of Families: ");
FamilyNumber = Integer.parseInt(in.nextLine());
List<String> list = Arrays.asList(boy, girl);
while (RunCount < FamilyNumber) {
randNum = (int)(Math.random() * 1 + 0);
randNum2 = (int)(Math.random() * 1 + 0);
FirstGender = list.get(randNum);
SecondGender = list.get(randNum2);
GenderValues = FirstGender + SecondGender;
if (GenderValues == "BG" || GenderValues == "GB") {
BGCount++;
}
else if (GenderValues == "GG") {
GGCount ++;
}
else {
BBCount++;
}
RunCount++;
}
GGPercent = ((double)(GGCount/FamilyNumber)*(100));
BGPercent = ((double)(BGCount/FamilyNumber)*(100));
BBPercent = ((double)(BBCount/FamilyNumber)*(100));
System.out.println("Number of Families with: \n");
System.out.println("\tTwo Boys: " + BBCount + " Represents " + BBPercent + "%");
System.out.println("\tTwo Girls: " + GGCount + " Represents " + GGPercent + "%");
System.out.println("\tOne Boy and One Girl: " + BGCount + " Represents " + BGPercent + "%");
This is the segment of code the issue is in. I already initialized all the variables and imported everything necessary. The problem is, whenever I run the program, I get this output:
Composition Statistics for Families with Two Children:
Total Number of Families:
15
Number of Families with:
Two Boys: 15 Represents 100.0%
Two Girls: 0 Represents 0.0%
One Boy and One Girl: 0 Represents 0.0%
The output is always two boys make up all the families. I'm assuming that the issue is with randNum and randNum2 variables, but I'm really not sure. I have no idea what to do so any input on where I'm going wrong is greatly appreciated.
Math.random returns a number between 0 and 1.
So when cast to an int it will be always 0.
Select a scaling factor and multiply the result (lets say 5)
and then the result will an int in the range 0-4
I want to display the sum of two numbers beside the equal sign.
Scanner scan = new Scanner(System.in);
int i ;
System.out.println("enter a number: " );
i = scan.nextInt();
int a = i - 1 ;
while(a >= 1){
System.out.println(i +" + "+ a + " = " );
//i want to display the sum of two numbers beside the equal sign.
i =i + a ;
System.out.println(i);
a --;
// how can I display the answer beside the equal sign?
}
}
}
How can I display the answer beside the equal sign?
Change your first println to print.
As per your question I think you are most probably asking how we can show the sum of two numbers in the print statement.
So in your code after "=" you just need to add (i+a) this will sum the value of i and a.
System.out.println(i +" + "+ a + " = " + (i+a)).
I hope this answers your question.
System.out.println() method prints a "newline character" (\n) right after its' input.
There is another method that does not do this:
System.out.print()
You should change
System.out.println(i +" + "+ a + " = " ); to
System.out.print(i +" + "+ a + " = " ); this.
Description: Write a program that asks the user for a starting value and an ending value. The program should then print all values inclusively between those values. In addition, print out the sum and average of the numbers between those two values.
I need help trying to layout the program and getting it to run correctly. The program runs, the desired result just isn't the same. Can someone help me understand what i should do for it to work correctly. Thank you.
But, here is my code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Prog152d
{
public static void main(String[] args) throws IOException
{
BufferedReader userin = new BufferedReader(new InputStreamReader(System.in));
String inputData;
int starting, ending, sum;
double avg;
sum = 0;
System.out.print("Enter Starting Value: ");
inputData = userin.readLine();
starting = Integer.parseInt( inputData );
System.out.print("Enter Ending Value: ");
inputData = userin.readLine();
ending = Integer.parseInt( inputData );
while ( starting <= ending)
{
System.out.println(starting);
sum = sum + starting;
avg = sum / 4;
System.out.println("Sum of the numbers " + starting + " and " + ending + " is " + sum);
System.out.println("The average of the numbers " + starting + " and " + ending + " is " + avg);
starting++;
}
}
}
Sample Output:
Enter Starting Value: 5
Enter Ending Value : 8
5
6
7
8
Sum of the numbers 5..8 is 26
The average of the numbers 5..8 is 6.5
The first problem I see is with the following line:
avg = sum / 4;
Don't use a constant value (in this case 4) unless it is the ONLY possibility. Instead use a variable and set its value equal to the difference between your starting and ending values:
int dif = ending - starting + 1; // add one because we want to include end ending value
avg = sum / dif;
Also, the average only needs to be calculated once at the end and therefore doesn't belong inside your loop. After making these adjustments you'll end up with something like this...
int start = starting; // we don't want to alter the value of 'starting' in our loop
while ( start <= ending)
{
System.out.println(start);
sum = sum + start;
start++;
}
int dif = ending - starting + 1;
avg = (double)sum / dif;
System.out.println("Sum of the numbers between " + starting + " and " + ending + " is " + sum);
System.out.println("The average of the numbers between " + starting + " and " + ending + " is " + avg);
Just starting learning java today and can't seem to figure this out. I am following the tutorial on learnjavaonline.org which teaches you a few things and then asks you to write a code to do a specific thing, it then checks the output to see if its correct. The thing is, if its not correct, it doesn't say why, or give you an example of the correct code.
It wants me to output a string saying "H3110 w0r1d 2.0 true" using all of the primitives
i came up with this
public class Main {
public static void main(String[] args) {
char h = 'H';
byte three = 3;
short one = 1;
boolean t = true;
double ten = 10;
float two = (float) 2.0;
long won = 1;
int zero = 0;
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
System.out.println(output);
}
}
but it outputs 86.0 w0r1d 2.0 true
how can i make it so it doesn't add all the integers, but displays them consecutively?
The problem with this line:
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
is that operations are performed left to right, so it first sums h + three (which evaluates to an int) and then one and then ten. Up to that point you have a numerical value (an int) that then will be "summed" to a String. Try something like this:
String output = "" + h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
In this second case your expression will start with a String object, evaluating the rest of the operations as Strings.
You of course could use "" at the beginning or any other value that evaluates to String, like String.valueOf(h). In this last case you wouldn't need to use String.valueOf() for the other operands, as the first one is already a String.
You can either convert your numbers into a string using the toString or valueOf methods of the wrapper classes (guess you are not there yet), or just stuff all your primitives into the printline without the String output.
system.out.println(h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t);
All you need to look for is that there is a String in the printline statement. Meaning if you only want to print our number based datatype you can use system.out.println("" + youNumberVariable).
There would also be the option to add an empty string at the beginning of your declaration of output output = "" + theRest; to force all following values into the string like it does in the printline statement.
Most of it is not very pretty coding but will completly suffice for the learning process.
An easy and ugly way to do this would be to use String.valueOf for each numerical value.
As in:
String output = h + String.valueOf(three); // + etc...
Edit
morgano's approach is perfectly valid as well - +1 for that.
On a more general topic, you might want to use String.concat for String concatenation, or even better, a StringBuilder object.
This SO page contains a lot of info you can use on the matter.
I would use String.valueOf to explicitly cast each numeric value to String before being added. Like so:
String output = h + String.valueOf( three ) + String.valueOf( one ) + String.valueOf( ten ) + " " + "w" + String.valueOf( zero ) + "r" + String.valueOf( won ) + "d " + String.valueOf( two ) + " " + t;
The trick is to get the compiler to interpret + as string concatenation (which then silently convert the numbers to strings) instead of adding two numbers. This mean that one of the two arguments to + must be a string, and not - as your first three arguments - numbers (and yes, a char is a number).
It is not typical in code in the wild to want numbers to be directly adjacent to each other, but have a space between them, like:
String output = h + " " + three + " " + one + " " + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
If you really want to have no spaces, then just let the first argument be the empty string:
String output = "" + h ....
You could also just change h from char to String.
The result you're getting is because, essentially, you're doing arithmetical operations on numeric variable before printing them when relying on implicit casting.
Even the Char is a numeral! H has the value 72 in the ascii table, so you are basically instructing the Java program to print the result of:
72 + 3 + 1 + 10.0 (which is equal to 86.0)
String concatenation with mixed inputs of numerals and symbols like this can be problematic since implicit casting is in play.
In order to make sure stuff is as you want, without using explicit casting, maybe use either strings between each numeric value, like this:
char h = 'H'; // This is a numeral! Capital H has value 72 in Ascii table
byte three = 3;
short one = 1;
boolean t = true; // not a numeral
double ten = 10;
float two = (float) 2.0;
long lOne = 1;
int zero = 0;
System.out.println(h + "" + three + "" + one + "" + (int) ten + " w"
+ zero + "r" + lOne + "d " + two + " " + t );
Note how I needed to cast ten to the int-type, to lose the decimal...
Above example is however not a good example of using string concatenations!
For a proper solution, and this is maybe more aimed at people with more experience, is to try using String formatting, like this:
System.out.println(String.format("%s%s%s%s w%sr%sd %s %s", h, three, one,
(int) ten, zero, lOne, two, t));
Another way is to use message formatting like this, maybe not the best choice for this assignment since the float will be printed as an integer. Also needs to import java.text.MessageFormat
// please note: the double and the float won't print decimals!
// note: import java.text.MessageFormat for this
System.out.println(MessageFormat.format("{0}{1}{2}{3} w{4}r{5}d {6} {7}", h,
three, one, (int) ten, zero, lOne, two, t));
More examples from the Ascii table.
public class Main {
public static void main(String[] args) {
int b = 3110;
int d = 0;
String e = "orld";
double f = 2;
boolean g = true;
System.out.println("H" + b + " " + "w" + d + e + " " + f + " " + g);
}
}
I'm a bit confused about how += assignment operator works. I know that x += 1 is x = x+1. However, in this code there is a string variable called 'String output' and initialized with an empty string. My confusion is that that there are 5 different outputs for the variable 'output' but I don't see where it's being stored. Help clarify my misunderstanding. I can't seem to figure it out.
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; //number of questions
int correctCount = 0; // Count the number of correct answer
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = " "; // Output string is initially empty
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// 2. if number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer "What is number1 - number2?"
System.out.print(
"What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
// 4. Grade the answer and display the result
if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++; // Increase the correct answer count
}
else
System.out.println("Your answer is wrong.\n" + number1
+ " - " + number2 + " should be " + (number1 - number2));
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "
wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime = startTime;
System.out.println("Correct count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
}
}
Answer given by Badshah is appreciable for your program and if you want to know more about operator' usability, jst check out this question i came across
+ operator for String in Java
The answers posted have very good reasoning of the operator
Its Add AND assignment operator.
It adds right operand to the left operand and assign the result to left operand.
In your case
output += someString // output becomes output content +somestring content.
`
Maybe the proper answer was written but if I understand your question correctly, you want some clarification instead of meaning of +=
Change the code;
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
as this:
output += "\nCount: " + count + " and the others: " +
number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
// Increase the question count
count++;
So you can see the line and the count together. Then increase as your wish.
In Java, Strings are immutable. So output += somethingNew makes something like this:
String temp = output;
output = temp + somethingNew;
At the end, it becomes something like concat/merge