Output keeps moving to next line - java

I'm having an issue whereby my output upon printing moves to the next line on its own, not the entire line moves, but parts of it. I would like it to be on the same line.
I've tried searching for similar issues online but no luck, I've also double checked my code, it shouldn't be moving to the next line for no reason. I would appreciate some insight on this, perhaps i'm too inexperienced to notice my error. This is what I have: Any help is appreciated! Thanks!
public static void main(String[] args)
{
//for loop to repeat 5 times
for (int i= 1; i < 6; i++)
{
//create 2 new points to use as argument
Point p1 = new Point();
Point p2 = new Point();
//create array to store return values, call method to generate points
Point point[] = getTwoPoints(p1, p2);
System.out.println("Set:" + i);
System.out.print("Given Point:" + "(" + point[0] + ")");
System.out.print("Given Point:"+ "(" + point[1]+ ")");
System.out.print("Line:" + "("+ point[0]+ ")" + "(" + point[1] + ")");
System.out.printf("Distance:"+"%.4f", point[0].getDistance(point[1]));
System.out.println("");
System.out.println("==================================");
}
}
Sample Output:
Set:1
Given Point:(60,57
)Given Point:(-75,83
)Line:(60,57
)(-75,83
)Distance:137.4809

What's the implementation of Point::toString method?
Most likely it contains a \n in it. Thus each time you print a point the caret goes to the next line.

Related

Parking Lot doesn`t save in matrix more than 1 line

So I have this project for my college and I'm stuck here, I tried everything I had in mind to make this code save more than 1 slot, as I must save up to 100 into a matrix database. Everything works great but the program always overwrites the first line, never passes on to the second...Here's the code:
Reserve part method:
for (n=1; n<100; n++) {
parkinglot[n][0] = Integer.toString(n);
parkinglot[n][1] = JOptionPane.showInputDialog(null, "License plate: ").toUpperCase();
String hourofreservation = JOptionPane.showInputDialog(null, "Reservation hour(hh:mm): ");
parkinglot[n][2] = hourofreservation;
parkinglot[n][3] = formatter.format(date);
parkingtime = Integer.parseInt(JOptionPane.showInputDialog(null, "Hours : "));
parkinglot[n][4] = Integer.toString(parkingtime);
int totalfee = (toMinutes(parkingtime)/30) * fee;
pay(totalfee);
//SaveReservation(nrinmat, parkinglot);
//save
JOptionPane.showMessageDialog(null, "This is yout reservation" + "\n\n" + " | " + parkinglot[n][0] + " | " + parkinglot[n][1] + " | " + parkinglot[n][2] + " | " + parkinglot[n][3] + " | " + parkinglot[n][4] + " HOURS |");
break;
}
Database method:
public static String[][] database(String [][]parkinglot)
{
System.out.println("This is database");
for (int i = 1; i < parkinglot.length; i++) {
for (int j = 0; j < parkinglot[i].length; j++) {
System.out.print(parkinglot[i][j] + "\t");
}
System.out.println();
}
return parkinglot;
}
Your program is starting at 1 every time because you have this line:
for (n=1; n<100; n++)
which initializes n to 1 before you enter the loop. (As noted in a comment, usually you would initialize n to zero, but that's not your problem here.)
Later, you break out of the loop, when n is still 1. When you call this code again (I assume it's in a function), it reinitializes n to 1 at the start of the loop. So n is never anything other than 1.
If you only want to fill in one record each time you run the program, then you don't need a loop at all. You need to store the value of n somewhere (like on disk, or in a database) and then read it back when you run the program again. Or, if you're saving the contents of parkinglot somewhere and reading it back in, you could scan it (using a for loop) to find the first empty entry, and initialize n to that, something like:
int n = 1; // or 0
for (; n < parkinglot.length && parkinglot[n][0] != null; n++);
if (n < parkinglot.length) {
populateParkingLotEntry(parkinglot, n);
} else {
// No more slots left...
}

Java - Error with a While loop not exiting when if condition hits break:

I am a beginner programmer so bear with me. I am currently working on a project for my coding class, where I am tasked with writing a program to simulate a batter facing a pitcher in a baseball game for one turn at bat. I think the problem in my code is a logic error, but I'm not quite sure how to fix it. I have tried added additional while loops and if statements but nothing has worked. The code in my batter class and pitcher class work completely fine, it's just the code in my driver. Stuff sometimes breaks out of loop when it's suppose to and other times it doesn't and sometimes it repeats the same line of text when it's not suppose to.
I would really appreciate some help on this. Thank you so much in advance.
Here is my code for the driver program:
public static void main(String[] args) {
Batter batter = new Batter();
batter.getname();
// making the pitcher object and calling the get name method.
Pitcher pitcher = new Pitcher();
pitcher.getname();
System.out.println(pitcher.getname() + " is pitching to " + batter.getname());
while (true) {
int ball = 0;
int strike = 0;
// desiding if the hit method gets called on the batter object
if (pitcher.pitch() == false) {
ball++;
System.out.println("The count is " + ball + " balls " + strike + " strikes");
}
if (pitcher.pitch()== false && ball ==4 ){
System.out.println("The count is " + ball + " balls " + strike + " strikes");
System.out.println(batter.getname() + " walked.");
break;
}
if (batter.hit() == false) {
strike++;
System.out.println("The count is " + ball + " balls " + strike + " strikes");
}
if (batter.hit() == false && strike == 3){
System.out.println("The count is " + ball + " balls " + strike + " strikes");
System.out.println(batter.getname() + " struck out.");
break;
}
if (batter.hit() == true && pitcher.pitch() == true) {
break;
}
}
}
At a quick glance I'd recommend the following.
For a start change to this as there is no point calling the getter every time so give it a variable name:
Batter batter = new Batter();
bName = batter.getname();
Pitcher pitcher = new Pitcher();
pName = pitcher.getname();
You can then replace batter.getName() & pitcher.Name() with bName & pName
I'm not a fan of while(true) and you need move ball and strike so try this instead:
int ball = 0, strike = 0;
boolean game = true;
while(game){
Then i'm not sure if your second if is right as you check for pitcher.pitch()==false in first if so try second one as:
if(ball == 4) {
Finally replace break with:
game = false;
You are resetting the values back to 0 every time the loop starts. Because you include the assignment inside the loop, it returns every time. Please note the number of the comments, meant to be read chronologically.
while (true) {
int ball = 0;
// [3] here, we are resetting ball to 0, so the ++ below is negated
int strike = 0;
if (pitcher.pitch() == false) {
ball++;
// [1] lets assume we get here, the value of ball now is 1.
// [2] we go to comment [3]
if you want to maintain the result, you should set the values before the loop.
int ball = 0;
int strike = 0;
// [1] both are 0 now
while (true) {
// [3] now, we maintain ball is 1. see 4
if (pitcher.pitch() == false) {
ball++;
// [2] setting ball to 1, repeating loop, see [3]
// [4] now we increment ball again, ball has value 2. Etc.

why do my simple arrays not work?

This program should ask how many of an animal are left in the wild 5 times. Then it should use a second method to output the same information. But i cant figure this out; every time i change anything based on previous questions here i just add to the number of errors.
import java.util.Scanner;
class animals {
public static void main(String[] args) {
int[] q1 = question();
output(q1);
System.exit(0);
} // exit main
public static int[] question() {
String[] wild = { "Komodo Dragon", "Mantee", "Kakapo", "Florida Panther", "White Rhino" };
int number = 0;
int[] record = {};
for (int i = 1; i <= 5; i++) {
System.out.println(wild[number] + ":");
Scanner scanner = new Scanner(System.in);
System.out.println("How many are left in the wild?");
int howMany = scanner.nextInt();
record = new int[] {howMany};
number++;
}//end for loop
return record;
}// end method question
public static void output(int[] q1){
System.out.println("There are " + q1[0] + " Komodo Dragons in the wild");
System.out.println("There are " + q1[1] + " Mantees in the wild");
System.out.println("There are " + q1[2] + " Kakapos in the wild");
System.out.println("There are " + q1[3] + " Florida Panthers in the wild");
System.out.println("There are " + q1[4] + " White Rhinos in the wild");
}//end method output
} // end class animals
So this compiles alright, then when i've added 5 numbers in terminal after each loop i get
There are 3 Komodo Dragons in the wild
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at animals.output(animals.java:39)
at animals.main(animals.java:13)
Other than the fact that im getting the text, the monodo dragon number being provided is the last number i input not the first
This doesn't make sense
int[number] record = {};
most like what you meant was
int[] record = new int[wild.length];
and instead of
for (int i = 1; i <= 5; i++) {
you need
for (int i = 0; i < wild.length; i++) {
instead of the following which creates an array of 1 value [0]
record = new int[] {howMany};
which will produce the following when you try to access [1]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
you need
record[i] = howMany;
As you write each line of code in your IDE (or your editor) you should see if that compiles and if it doesn't adding more lines is unlikely to help. I suggest you try to compile and test as often as possible so you know where the source of your errors are and when you get a bug, you can step through the code in your debugger to see why the program is not doing what you expect.
This is what you need:
int number = 0;
int[] record = new int[5];
and another modification which you need to make:
int howMany = scanner.nextInt();
record[number] = howMany;
Remove comment from last line.
Now your program should work fine.
Learn some basic stuff about arrays.

Tower of Hanoi error

Alright so I designed a code for the activity "The Towers of Hanoi". It is excellent for recursion exercise. The problem is that when I solve the puzzle via pencil and paper after outputting the results, it turns out to be wrong.
When n = 2, the puzzle works beautifully. But I just tried n = 3, and something is out of place.
My program is designed to make the 3 peg the final place for all the pieces. So the disks all finalize on peg 3.
public class TowersOfHanoi {
public static String hanoi(int nDisks, int fromPole, int toPole)
{
int helpPole;
String Pol1, Pol2, MyStep, MyPol; //contains moves
if(nDisks ==1)
{
return "There is " + nDisks + " disk moving from " + fromPole + "==>" + toPole + "\n";
}
else
{
helpPole = 6 - fromPole - toPole; //fromPole + helpPole + toPole = 6
Pol1 = hanoi(nDisks-1, fromPole, helpPole);
MyStep = "There are/is " + (nDisks-1) + " disk(s) moving from " + fromPole + "==>" + toPole + "\n";
Pol2 = hanoi(nDisks-1, helpPole, toPole);
MyPol = Pol1 + MyStep + Pol2; //+ = String concatenation
return MyPol;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
int n = 3;
String StepsToSolution;
StepsToSolution = hanoi (n, 1, 3);
System.out.println(StepsToSolution);
}
}
Output:
There is 1 disk moving from 1==>3
There are/is 1 disk(s) moving from 1==>2
There is 1 disk moving from 3==>2
There are/is 2 disk(s) moving from 1==>3
There is 1 disk moving from 2==>1
There are/is 1 disk(s) moving from 2==>3
There is 1 disk moving from 1==>3
nDisks tells the method how many disks are to be moved. It is not an identification or the number of disks being moved at one particular time but the rest of the job in one particular place.
Thus. There will always be one disk moving from one peg to another, never 2. You do (nDisks-1) in myStep where you should have done 1. Or put more simply, myStep could have been: myStep = hanoi(1, fromPole, toPole);
Other than that your output of the moves are correct. That means you can increase to more disks and expect correct moves.

What's wrong with my code and/or logic?

I having some trouble with an APCS assignment. The program is supposed to read strings with a length of two from a text file - test1.txt - and print out percentages of: a) girl-girl, boy-boy, boy-girl or girl-boy combinations, and b) the total number of individual groups.
I've been trying for an hour to figure this out! Although I'm suspicious of the String declaration in line 25, I don't have a way to confirm that. Furthermore, I'm worried that I messed up my if-else-if-else loop without prompting a compiler error.
The source code is attached for your reference. If you need any additional information, please don't hesitate to ask.
Since I'm a new user with a reputation < 10, please see the attached image:
For elaboration on what isn't working. I took a screenshot and wrote relevant comments on it!
/**
* Family takes user input of sets of boys, girls, and boys + girls. Results are then
* tabulated and displayed in a percentage form to the user. The total number of
* individuals are also displayed.
*
* #E. Chu
* #Alpha
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family {
public static void main (String[] args) throws IOException {
int boyCount = 0;
int girlCount = 0;
double boyGroupCount = 0.0;
double girlGroupCount = 0.0;
int mixedGroupCount = 0;
int totalPersonCount = 0;
double totalGroupCount;
String currentToken = " ";
Scanner inFile = new Scanner (new File ("test1.txt"));
while (inFile.hasNextLine()) {
currentToken = inFile.nextLine( );
if (currentToken == "BG") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "GB") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "BB") {
boyCount += 2;
boyGroupCount++; }
else {
girlCount += 2;
girlGroupCount++; }
}
inFile.close();
totalPersonCount = boyCount + girlCount;
totalGroupCount = boyGroupCount + girlGroupCount + mixedGroupCount;
System.out.println("Sample Size: " + totalPersonCount);
System.out.println("Two Boys (%): " + boyGroupCount / totalGroupCount + "%");
System.out.println("One Boy, One Girl (%): " + mixedGroupCount + "%");
System.out.println("Two Girls (%): " + girlGroupCount / totalGroupCount + "%");
} // End of main method.
} // End of class Family.
currentToken == "BB" should be currentToken.equals("BB")
Don't use == use the method equals instead
Hint: you don't want to compare strings using ==, look into the equals method.

Categories

Resources