I need to make a two dimensional table that has two columns with the following code.
public static void printCommonLogTable() {
double x = 0.0;
int i = 1;
while (x <= 10.0) {
System.out.print(x + " " + Math.log(x) + " ");
x = x + 0.5; }
System.out.println("");
}
public static void main(String[] args) {
printCommonLogTable();
}
The first column in the table should be the number for which you are computing the log and the second column should be the result.
But when I run this, everything is on the same line.
That's because your call to System.out.println(""); is misplaced: it should be at the end of the while loop (but inside it). This is easier to see when the code is correctly indented, like this:
public static void printCommonLogTable() {
double x = 0.0;
while (x <= 10.0) {
System.out.print(x + " " + Math.log(x) + " ");
x = x + 0.5;
System.out.println();
}
}
Note that I removed the unused i variable, and replaced System.out.println(""); with just System.out.println();
You can also combine the two print statements in one:
public static void printCommonLogTable() {
double x = 0.0;
while (x <= 10.0) {
System.out.println(x + " " + Math.log(x) + " ");
x = x + 0.5;
}
}
public static void main(String args[]) {
double x = 0.0;
int i = 1;
while (x <= 10.0) {
System.out.println(x + " " + Math.log(x) + " "); // old : System.out.print(x + " " + Math.log(x) + " ");
x = x + 0.5; }
}
The println("...") method prints the string "..." and moves the cursor to a new line. The print("...") method instead prints just the string "...", but does not move the cursor to a new line. Hence, subsequent printing instructions will print on the same line. The println() method can also be used without parameters, to position the cursor on the next line.
Related
I want to split any number to any identical pieces and the last remaining but not dividable piece will be the last piece. I wrote this code but I know that it should be more simple way to do this :) For example; 7500 divided by 2000 and the last modulus part will be the last part. Any suggestions?
public class MyClass {
public static void main(String args[]) {
int x =7500;
int y = 2000;
int lastPartCount = 0;
String result = new String();
if(x%y != 0){
lastPartCount = x%y;
}
int newx = x-lastPartCount;
for(int i=1; i<=(newx/y); i++){
if(i == 1){//first member
result = "part " + i + ": 0-" + y*i;
}else
{
result = "part " + i + ": " + (y*(i-1)) + "-" + y*i;
}
System.out.println(result);
if(i == (newx/y)){//last member
result = "part " + (i+1) + ": " + (y*(i)) + "-" + x;
System.out.println(result);
}
}
}
}
the result is like this:
part 1: 0-2000
part 2: 2000-4000
part 3: 4000-6000
part 4: 6000-7500
You can simplify your code like the following:
public static void main(String args[]) {
int x = 7500;
int y = 2000;
for (int i = 0; i < x/y; i++) {
System.out.println("Part " + (i+1) + ": " + y*i + " - " + y*(i+1));
}
if (x%y != 0) {
System.out.println("Part " + ((x/y)+1) + ": " + (x/y)*y + " - " + x);
}
}
(x/y)*y) is not equal to x since you divide integers, so (x/y)*y is actually the same as the "next" i of the for-loop.
You can also try the below code:
private void test() {
int x = 7500;
int y = 2000;
int j = 0;
int newX = x;
while (newX > y) {
System.out.println("Part " + (j + 1) + " = " + y * j++ + " - " + y * j);
newX -= y;
}
System.out.println("Part " + (j + 1) + " = " + j * y + " - " + x);
}
Alternative approach using two variables in your for loop and Math.min():
int x = 7500;
int y = 2000;
for (int i = 0, p = 1; i < x; i += y, p++) {
System.out.printf("Part %d: %d - %d%n", p, i, Math.min(i+y,x));
}
The task is to simulate a wheel of fortune, which you are allowed to turn ten times.
You can spin as many times as you like, but as soon as the 0 comes, all points are gone. The program should stop the round as soon as a score over 10 is reached or a 0 comes. The results should be added at the end.
We are now at the point where the points are added and fields are fixed, but we can't think of anything to do with stopping or adding the results.
Does anyone have an idea?
Thanks in advance!
import java.util.Map;
import java.util.LinkedHashMap;
public class RandomBeispielzwei {
private static final Map<Double, Integer> GRENZEN = new LinkedHashMap<Double, Integer>();
static {
GRENZEN.put(0.1, 1);
GRENZEN.put(0.2, 2);
GRENZEN.put(0.3, 3);
GRENZEN.put(0.4, 1);
GRENZEN.put(0.5, 2);
GRENZEN.put(0.6, 3);
GRENZEN.put(0.7, 1);
GRENZEN.put(0.8, 2);
GRENZEN.put(0.9, 3);
GRENZEN.put(1.0, 0);
}
private Integer naechsteZufallzahl() {
double random = Math.random();
for (Map.Entry<Double, Integer> entry : GRENZEN.entrySet()) {
if (random <= entry.getKey().doubleValue()) {
return entry.getValue();
}
}
throw new UnsupportedOperationException("Fuer die Zufallszahl wurde kein passender Wert in der Map gefunden");
}
public static void main(String[] args) {
int anzahl1 = 0;
int anzahl2 = 0;
int anzahl3 = 0;
int anzahl0 = 0;
RandomBeispielzwei b = new RandomBeispielzwei();
for (int i = 0; i < 10; i++) {
Integer z = b.naechsteZufallzahl();
if (z.intValue() == 1) {
anzahl1++;
} else if (z.intValue() == 2) {
anzahl2++;
} else if (z.intValue() == 3) {
anzahl3++;
} else {
anzahl0++;
}
}
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
System.out.println("1: " + anzahl1);
System.out.println("Punktzahl 1: " + ges1);
System.out.println("2: " + anzahl2);
System.out.println("Punktzahl 2: " + ges2);
System.out.println("3: " + anzahl3);
System.out.println("Punktzahl 3: " + ges3);
System.out.println("0: " + anzahl0);
System.out.println("Gesamtzahl: " + (anzahl1 + anzahl2 + anzahl3 + anzahl0));
System.out.println("Gesamtpunktzahl: " + (ges1 + ges2 + ges3));
}
}
For exiting the for-loop (and any other loop), you can use the "break" statement, which simply ends the loop (similar to how "return" will exit a method). In order to be able to stop once the total score reaches ten, you of course need to keep track of the total score. To do this, the easiest way would be to introduce aa integer variable (e.g. "gesamtpunktzahl"), to which you add the amount of points scored in each turn. In all, it would look something like this:
import java.util.Map;
import java.util.LinkedHashMap;
public class RandomBeispielZwei {
private static final Map<Double, Integer> GRENZEN = new LinkedHashMap<Double, Integer>();
static {
GRENZEN.put(0.1, 1);
GRENZEN.put(0.2, 2);
GRENZEN.put(0.3, 3);
GRENZEN.put(0.4, 1);
GRENZEN.put(0.5, 2);
GRENZEN.put(0.6, 3);
GRENZEN.put(0.7, 1);
GRENZEN.put(0.8, 2);
GRENZEN.put(0.9, 3);
GRENZEN.put(1.0, 0);
}
private Integer naechsteZufallzahl() {
double random = Math.random();
for (Map.Entry<Double, Integer> entry : GRENZEN.entrySet()) {
if (random <= entry.getKey().doubleValue()) {
return entry.getValue();
}
}
throw new UnsupportedOperationException("Fuer die Zufallszahl wurde kein passender Wert in der Map gefunden");
}
public static void main(String[] args) {
int anzahl1 = 0;
int anzahl2 = 0;
int anzahl3 = 0;
int anzahl0 = 0;
int gesamtpunktzahl = 0; // this will store what the total score is so far
RandomBeispielzwei b = new RandomBeispielzwei();
for (int i = 0; i < 10000; i++) {
Integer z = b.naechsteZufallzahl();
if (z.intValue() == 1) {
anzahl1++;
gesamtpunktzahl++; // a 1 was scored, so we increase the total score by 1
} else if (z.intValue() == 2) {
anzahl2++;
gesamtpunktzahl += 2; // same with a 2
} else if (z.intValue() == 3) {
anzahl3++;
gesamtpunktzahl += 3; // same with a 3
} else {
anzahl0++;
break; // a 0 was rolled, so we end the game (by exiting the for-loop)
}
if (gesamtpunktzahl >= 10) break; // at least 10 points were scored so far, so we exit the for-loop
}
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
System.out.println("1: " + anzahl1);
System.out.println("Punktzahl 1: " + ges1);
System.out.println("2: " + anzahl2);
System.out.println("Punktzahl 2: " + ges2);
System.out.println("3: " + anzahl3);
System.out.println("Punktzahl 3: " + ges3);
System.out.println("0: " + anzahl0);
System.out.println("Gesamtzahl: " + (anzahl1 + anzahl2 + anzahl3 + anzahl0));
System.out.println("Gesamtpunktzahl: " + gesamtpunktzahl); // since we calculated it anyway, we might as well just use it here
}
}
I suggest using the loop do ... while for the counting and printing.
And please check you code - does you need count the same variable anzahl1 for each ges?:
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
if not - then replace ges[i] = anzahles[1] * (i+1); to ges[i] = anzahles[i+1] * (i+1);
public static void main(String[] args) {
int[] anzahles = new int[4];
int gesamtpunktzahl = 0;
Integer z = 0;
RandomBeispielzwei b = new RandomBeispielzwei();
do {
z = b.naechsteZufallzahl();
anzahles[z]++;
gesamtpunktzahl += z;
} while (!(z == 0 || gesamtpunktzahl >= 10));
int ges[] = new int[3];
for (int i = 0; i < 3; i++) {
ges[i] = anzahles[1] * (i+1);
System.out.println((i+1) + ": " + anzahles[i+1]);
System.out.println("Punktzahl " + (i+1) + ": " + ges[i]);
}
System.out.println("0: " + anzahles[0]);
System.out.println("Gesamtzahl: " + Arrays.stream(anzahles).sum());
System.out.println("Gesamtpunktzahl: " + Arrays.stream(ges).sum());
}
Creating an Algebra Tutor trying to create random integers to solve y=m*x+b. Searched and found a lot of users have worked with this equation but not with generating a random question to require an answer and check if correct. This is what I have written so far;
import java.util.Scanner;
class AlgebraTutor {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
for (int x = 0; x < 1; x++){
System.out.println("X = " + ((int)(Math.random() * 200) -99));
}
for (int m = 0; m < 1; m++){
System.out.println("M = " + ((int)(Math.random() * 200) -99));
}
for (int b = 0; b < 1; b++){
System.out.println("B = " + ((int)(Math.random() * 200) -99));
}
}
}
I believe I'm on the right path with generating numbers between -100 and 100. I just don't know what to do to move forward with combining them so that I can input an answer to the numbers created. My best guess was
System.out.print("Y = " + m * x + b);
But that didn't work the way I thought it would. I want to be able to input an answer and have it check true or false. Thanks for any advice to get past this.
You need to store the values in variables for example:
int x = ((int)(Math.random() * 200) -99));
Also your for loops are unnecessary in that they only run once so you could just run the program instead of looping once.
so in the end your code should be something like this:
import java.util.Scanner;
class AlgebraTutor {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int x = ((int)(Math.random() * 200) -99);
int m = ((int)(Math.random() * 200) -99);
int b = ((int)(Math.random() * 200) -99);
System.out.println("X = " + x);
System.out.println("M = " + m);
System.out.println("B = " + b);
System.out.println("Y = " + m*x+b);
}
}
And to have it check the answer if it is true or false you would have to do something like this:
import java.util.Scanner;
class AlgebraTutor {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int x = ((int)(Math.random() * 200) -99);
int m = ((int)(Math.random() * 200) -99);
int b = ((int)(Math.random() * 200) -99);
int y = m*x+b;
System.out.println("X = " + x);
System.out.println("M = " + m);
System.out.println("B = " + b);
int INPUT = in.nextInt();
if(INPUT == y){
System.out.println("You Got It Right!");
System.out.println("Y = " + y);
} else {
System.out.println("You Got It Wrong :(");
System.out.println("The Answer was: Y = " + y);
}
}
}
The variables x,m and b in your example are in the scope of each for-loop but die after the } of the loops.
int x = (int)(Math.random() * 200) -99); // these variables will live long enough.
int m = (int)(Math.random() * 200) -99);
int b = (int)(Math.random() * 200) -99);
System.out.println("X = " + x);
System.out.println("M = " + m);
System.out.println("B = " + b);
System.out.print("Y = " + m * x + b);
This should work, but note to be careful when you try to divide these numbers like "x/b" - you will need a cast to float (google division by integer)
I need to sum the points after each round. When I do it it doesn't work. It just outputs the point system under the if statements. Help and an explanation would be very helpful! Thank you from an intro Java coder.
public class J1 {
public static void main(String args[]) {
// create random object
java.util.Random rand = new java.util.Random();
java.util.Scanner scanner = new java.util.Scanner(System.in);
// check next int value
System.out.println("Wall height: " + rand.nextInt(10));
double height = rand.nextInt(10);
System.out.println("Distance from wall: " + rand.nextInt(20));
double dist = rand.nextInt(20);
for(int i = 1; i > 0; i++) {
System.out.println("Set a lanuch angle between 0 and 90: ");
double angle = scanner.nextDouble();
System.out.println("Set a lanuch speed: ");
double speed = scanner.nextDouble();
double point;
double a;
double b;
double c;
double d;
//double e;
double y;
a = dist*(Math.tan(Math.toRadians(angle)));
b = 9.81*(dist*dist);
c = (speed * Math.cos(angle)) * (speed * Math.cos(Math.toRadians(angle)));
d = 2*c;
y = a - (b/d);
System.out.println("Your max height is " +y+ " high");
double space;
space = height - y;
if(space <= 3 && space > 0) {
System.out.println("You just made it! ");
point = 0 - 1 + 3;
System.out.println("You have " +point+ " points.");
}
if (space > 3 && space <= 6) {
System.out.println("Aww. Plenty of room!");
point = 0 - 1 + 5;
System.out.println("You have " +point+ " points.");
}
if(space <= 0 && space >= -3) {
System.out.println("So close!");
point = 0 - 1 - 2;
System.out.println("You have " +point+ " points.");
}
if (space < -3) {
System.out.println("Terrible aim!");
point = 0 - 1 - 4;
System.out.println("You have " +point+ " points.");
}
}
System.out.println("Your total points: " +point);
}
}
The declaration of the point variable would need to occur outside of the for loop for it to be accessible for printing at the end of the code.
It also appears the for(int i = 1; i > 0; i++) { ... } loop will run indefinitely, which means the System.out.println("Your total points: " +point); line at the end will never be reached. You would need to fix the for loop so it only runs a limited amount of times.
The points after each round are never added to the grand total in the if sections, you would need to change the statement so that point += instead of point =.
I have added a few comments in the code below so you can see which changes have been made. I have also closed the scanner at the end as it is common practice, and fixed the code indentation for clarity purposes:
public class J1
{
public static void main( String args[] )
{
// create random object
java.util.Random rand = new java.util.Random();
java.util.Scanner scanner = new java.util.Scanner(System.in);
// check next int value
System.out.println("Wall height: " + rand.nextInt(10));
double height = rand.nextInt(10);
System.out.println("Distance from wall: " + rand.nextInt(20));
double dist = rand.nextInt(20);
double point = 0; //ADD THIS LINE
for(int i = 1; i < 10; i++) //CHANGED SO THAT i < 10 INSTEAD OF i > 0
{
System.out.println("Set a lanuch angle between 0 and 90: ");
double angle = scanner.nextDouble();
System.out.println("Set a lanuch speed: ");
double speed = scanner.nextDouble();
//double point; *** REMOVE THIS LINE ***
double a;
double b;
double c;
double d;
//double e;
double y;
a = dist*(Math.tan(Math.toRadians(angle)));
b = 9.81*(dist*dist);
c = (speed * Math.cos(angle)) * (speed * Math.cos(Math.toRadians(angle)));
d = 2*c;
y = a - (b/d);
System.out.println("Your max height is " +y+ " high");
double space;
space = height - y;
if(space <= 3 && space > 0)
{
System.out.println("You just made it! ");
point += 0 - 1 + 3; //ADDED += INSTEAD OF =
System.out.println("You have " +point+ " points.");
}
if(space > 3 && space <= 6)
{
System.out.println("Aww. Plenty of room!");
point += 0 - 1 + 5; //ADDED += INSTEAD OF =
System.out.println("You have " +point+ " points.");
}
if(space <= 0 && space >= -3)
{
System.out.println("So close!");
point += 0 - 1 - 2; //ADDED += INSTEAD OF =
System.out.println("You have " +point+ " points.");
}
if(space < -3)
{
System.out.println("Terrible aim!");
point += 0 - 1 - 4; //ADDED += INSTEAD OF =
System.out.println("You have " +point+ " points.");
}
}
System.out.println("Your total points: " +point);
scanner.close(); //ADD THIS LINE
}
}
I'm practicing writing for loops in Java. This is what I have so far:
int a = 0;
int b = 0;
int c = 0;
int d = 0;
System.out.println ("Num "+"Square "+"Num "+"Square "+"Num "+"Square "+"Num "+"Square ");
for (int x = 1; x<=20; x++) {
a = x * 1;
b = 20+a;
c = 40+a;
d = 60+a;
for (int y = 1; y <= 1; y++) {
System.out.println (a + " " + (a * a) + " " + b + " " + (b * b) + " " + c +
" " + (c * c) + " " + d + " " + (d * d));
}
}
I don't want to change the code at all (meaning I don't want to add anything more complicated than I already have), but I'd like the columns to line up. When the numbers start increasing in digits, obviously the spacing gets messed up. Any ideas on how to fix this?
EDIT: To answer your questions, I'm pretty new to this and haven't taught myself much more than this. I'm more than sure there are way better ways to do this, but I'm just practicing my for loops. Anywho, thanks for the help.
You can use tab(\t) to format it. A double tab will provide more space in your case.
// Changed Num to Number - Out of habit
System.out.println("Number\t\t" + "Square\t\t" + "Number\t\t" + "Square\t\t" + "Number\t\t" + "Square\t\t" + "Number\t\t" + "Square");
System.out.println(a + "\t\t" + (a * a) + "\t\t" + b + "\t\t" + (b * b) + "\t\t" + c + "\t\t" + (c * c) + "\t\t" + d + "\t\t" + (d * d));
public String appendBlankSpace(int val){
String returnValue=Integer.toString(val);
int lengthTobeAppend=10-returnValue.length();
//Here you can use any number instead of 10.It is for space allocated for a column
for(int i=1;i<=lengthTobeAppend;i++){
returnValue= " " + returnValue;
}
return returnValue;
}
now you can use,
System.out.println (appendBlankSpace(a) + appendBlankSpace(a * a) + appendBlankSpace(b) + appendBlankSpace(b * b) + appendBlankSpace(c) + appendBlankSpace(c * c) + appendBlankSpace(d) + appendBlankSpace(d * d));
I hope it will help you.
you can store a,b,c,d values in array like inside loop
for (int x = 1; x<=20; x++) {
a = x * 1;
b = 20+a;
c = 40+a;
d = 60+a;
int [] array = {a,b,c,d}
//using enhanced for loop
for(int ele : array){
System.out.println(ele +"\t\t"+ ele*ele)
}
}
output will appear like :
2 4
3 9
4 16
Use printf.
public class Squarely {
public static void main(String[] args) {
for (int x = 1; x <= 20; ++x) {
int a = x, b = 20+x, c = 40+a, d = 60+a;
System.out.printf("%6d %6d %6d %6d %6d %6d %6d %6d%n",
a, a*a, b, b*b, c, c*c, d, d*d);
}
}
}