im in need of some code to stop my current code
producing negative numbers if the start INTs are larger than the End INTs
Im aware there is a lot of code here i have commented out the bit i need help with (about half way down) but i wanted to provide it all so you ca complie and run to se what im struggling with
import javax.swing.JOptionPane;
public class race {
public static void main(String[] args) {
System.out.println("Course Start time End time Gender Total time Name");
int count = 1;
while (count<7){
count++;
System.out.println( "");
String colour = JOptionPane.showInputDialog(null,
"Competitor Enter your course colour first letter" );
String Starth = JOptionPane.showInputDialog(null,
"Competitor Enter your Start time (hours)" );
int Starthour=Integer.parseInt(Starth);
String Startm = JOptionPane.showInputDialog(null,
"Competitor Enter your Start time (mins)" );
int Startmin=Integer.parseInt(Startm);
String Starts = JOptionPane.showInputDialog(null,
"Competitor Enter your Start time (secs)" ) ;
int Startsec=Integer.parseInt(Starts);
String Endh = JOptionPane.showInputDialog(null,
"Competitor Enter your End time (hours)" );
int Endhour=Integer.parseInt(Endh);
String Endm = JOptionPane.showInputDialog(null,
"Competitor Enter your End Time (mins)" );
int Endmin=Integer.parseInt(Endm);
String Ends = JOptionPane.showInputDialog(null,
"Competitor Enter your End Time (secs)" );
int Endsec=Integer.parseInt(Ends);
String sex = JOptionPane.showInputDialog(null,
"Male or Female (M/F)" );
String Name = JOptionPane.showInputDialog(null,
"Competitor Enter your Full Name (Joe Bloggs)" );
int Timeh = (Endhour - Starthour);
int Timem = (Endmin - Startmin);
int Times = (Endsec - Startsec);
//so here i need code so that if i take endsec e.g50 away from startsec e.g54 Times wont print out -4, rather it will take one of Timem and print Times as 56//
System.out.print(colour);
System.out.print(" ");
System.out.print( String.format("%02d",Starthour));
System.out.print( ":");
System.out.print( String.format("%02d",Startmin));
System.out.print( ":");
System.out.print( String.format("%02d",Startsec));
System.out.print( " ");
System.out.print( String.format("%02d",Endhour));
System.out.print( ":");
System.out.print( String.format("%02d",Endmin));
System.out.print( ":");
System.out.print( String.format("%02d",Endsec));
System.out.print(" "+sex);
System.out.print(" "+Timeh);
System.out.print(":");
System.out.print(""+Timem);
System.out.print(":");
System.out.print(""+Times);
System.out.print(" "+Name);
}// end while
}
}
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I am trying to get this code to loop so once I run through the main while loop it starts over and asks for the input of the program again. I have a commented out of input at the bottom of the code and for some reason when the program reaches this line it terminates.
enter image description here
image of output I'm looking for.
import java.util.Scanner;
public class Eggs
{
public static void main(String[] args)
{
String program="";
String program2 ="";
String PythonID;
int PythonAge = 0;
int PreviousYr=0;
int CurrentYr=35;
int SumEggs=0;
int GTeggs=0;
int PythonYr=0;
System.out.println("This is the Python Snake Eggstimator Program.");
System.out.println("It estimates the number of eggs that a female python will "
+ "produce over a lifetime.");
Scanner input = new Scanner(System.in);
System.out.println("Please enter HISS if you want run the program STOP to quit");
program= input.nextLine();
while (program.equals("HISS"))
{
//Ask user to continue program
//ask for Python ID name
System.out.println("Enter the Python ID:");
PythonID= input.nextLine();
//Python age
do
{
System.out.println("Enter the age of the python in years:");
PythonAge= input.nextInt();
}
while(PythonAge <1 || PythonAge >20);
//setting year to 0
PreviousYr=0;
SumEggs=0;
//if age is less than 4
if (PythonAge <4)
{
PythonAge = 4;
}
//Calculation egg stuff
while (PythonAge <=20)
{
SumEggs = PreviousYr + CurrentYr;
System.out.println("Year " +PythonAge+ " Previous "+PreviousYr + " Current Year " +CurrentYr+ " Sum eggs "+SumEggs);
PreviousYr= PreviousYr + CurrentYr;
PythonAge++;
}
//ask for program again
System.out.println(PythonID+ " will lay a total of " + SumEggs + " over her remaining lifetime of 20 years.");
System.out.println("Please enter HISS if you want run the program STOP to quit");
//program= input.nextLine();
GTeggs=GTeggs + SumEggs;
System.out.println("The sum of all eggs for all Pythons processed is " + GTeggs);
}
System.out.println("The sum of all eggs for all Pythons processed is " + GTeggs);
}
}
Hi please find the modified working code.
import java.util.Scanner;
public class Demo123 {
public static void main(String[] args)
{
String program="";
String program2 ="";
String PythonID;
int PythonAge = 0;
int PreviousYr=0;
int CurrentYr=35;
int SumEggs=0;
int GTeggs=0;
int PythonYr=0;
System.out.println("This is the Python Snake Eggstimator Program.");
System.out.println("It estimates the number of eggs that a female python will "
+ "produce over a lifetime.");
Scanner input = new Scanner(System.in);
System.out.println("Please enter HISS if you want run the program STOP to quit");
program= input.nextLine();
while (program.equals("HISS"))
{
//ask for Python ID name
System.out.println("Enter the Python ID:");
PythonID= input.nextLine();
//Python age
do
{
System.out.println("Enter the age of the python in years:");
PythonAge= input.nextInt();
input.nextLine();
}
while(PythonAge <1 || PythonAge >20);
//setting year to 0
PreviousYr=0;
SumEggs=0;
//if age is less than 4
if (PythonAge <4)
{
PythonAge = 4;
}
//Calculation egg stuff
while (PythonAge <=20)
{
SumEggs = PreviousYr + CurrentYr;
System.out.println("Year " +PythonAge+ " Previous "+PreviousYr + " Current Year " +CurrentYr+ " Sum eggs "+SumEggs);
PreviousYr= PreviousYr + CurrentYr;
PythonAge++;
}
//ask for program again
System.out.println(PythonID+ " will lay a total of " + SumEggs + " over her remaining lifetime of 20 years.");
System.out.println("Please enter HISS if you want run the program STOP to quit");
//program= input.nextLine();
GTeggs=GTeggs + SumEggs;
System.out.println("The sum of all eggs for all Pythons processed is " + GTeggs);
System.out.println("Please enter HISS if you want run the program STOP to quit");
program= input.nextLine();
}
}
}
I know I'm explaining it terribly, I'm having a hard time understanding the logic of it also. What I've done is created a way for the user to enter in how many rooms (up to 5) to be created in this calculator. What I don't know how to do, is create the next few lines that act as... placeholders(?) for (up to) 5 rooms. I've put an example below. I apologize, very new to Java.
System.out.print ("Please enter the number of rooms! (Up to 5!) ");
int roomcount = sc.nextInt();
String[] places = new String[roomcount];
for(int i = 0; i < places.length; i++) {
places[i] = "Place Number: " + i;
}
sc.nextLine();
System.out.println("You said that there were " + roomcount + " rooms!");
System.out.print ("Please enter the types of rooms (up to " +roomcount+ ") that fill up the " + roomcount + " rooms!\n"
+ "(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!) \n ") ;
String roomname1 = sc.next();
String roomname2 = sc.next(); <------ I know these lines are redundant.
I'm just unsure of how to put the idea into action.
Thanks for any help!
You can create an array to add the types of rooms:
String[] types = new String[roomcount];
for(int i = 0; i < types.length; i++) {
System.out.print ("Please enter the types of room " + places[i]);
String roomName = sc.next();
types[i] = roomName;
System.out.println("Room name: " + roomName);
}
I apologize if my question is confusing, I'll try to explain it better here.
I'm creating a Property Calculator where the user is required to enter the Rooms of the residence, the area of each room, and then the price. Which ultimately gets calculated (total area from each room * price).
I'm not too familiar with Java so I'm not sure why I'm unable to use the variable declared in the class, outside.
Here is the code, followed by the issue that is happening:
EDIT
package realestatepropvalue;
import java.util.Scanner;
public class RealEstateProbValueA3
{
public static void main(String[] args)
{
Scanner sc = new Scanner ( System.in );
System.out.println ( "Hello friend, you will enter a series "
+ "of fields that'll calculate your Real Estate Property Value.");
System.out.print ("Please enter a Street Number ");
String streetnum = sc.next();
sc.nextLine();
System.out.println ("You entered the Street Number, " +streetnum );
System.out.print ( "Please enter a Street Name ");
String streetnam = sc.nextLine();
System.out.println ("You entered the Street Name, " + streetnam + " " );
END EDIT
System.out.print ("Please enter the number of rooms! (Up to 5!) ");
int roomcount = sc.nextInt();
String[] places = new String[roomcount];
for(int i = 0; i < places.length; i++) {
places[i] = "Place Number: " + i;
}
sc.nextLine();
System.out.println("You said that there were " + roomcount + " rooms!");
System.out.print ("Please enter the types of rooms (up to " +roomcount+ ") that fill up the " + roomcount + " rooms!\n"
+ "(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!) \n ") ;
int squareCounter = 0;
String[] types = new String[roomcount];
for(int i = 1; i < types.length; i++) {
System.out.print ("Please enter the types of room " + places[i] + ": ");
String roomName = sc.nextLine();
types[i] = roomName;
System.out.print ("Please enter the square feet of " + roomName + ": ");
int squareFeet = sc.nextInt();
squareCounter = squareFeet + squareCounter;
System.out.println("Room name: " + roomName + " is: " + squareFeet + "square feet.");
System.out.println("The counter total: " + squareCounter );
System.out.println("What is the price per sq. feet?");
int pricePer = sc.nextInt();
int finalCalc = pricePer * squareCounter;
System.out.println( "Estimated Property value: $____" + finalCalc);
}
Here is the log:
LOG EDIT
run:
Hello friend, you will enter a series of fields that'll calculate your Real
Estate Property Value.
Please enter a Street Number 7
You entered the Street Number, 7
Please enter a Street Name Washington Street
You entered the Street Name, Washington Street
END EDIT
Please enter the number of rooms! (Up to 5!) 3
You said that there were 3 rooms!
Please enter the types of rooms (up to 3) that fill up the 3 rooms!
(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!)
Please enter the types of room Place Number: 1: Kitchen
Please enter the square feet of Kitchen: 50
Room name: Kitchen is: 50square feet.
The counter total: 50
What is the price per sq. feet?
50
Estimated Property value: $____2500
Please enter the types of room Place Number: 2: Please enter the square feet of :
The last line immediately skips the type of room, and asks the square feet. Why does this happen?
Thank you for any help!
I wrote this program to calculate the total number of votes that each person got in an election, and to enter multiple districts. When I try to enter another district the program just prints out the votes received from the first district instead of setting up another poll. What is wrong with it and how do I fix it?
import java.util.Scanner;
public class Election{
public static void main (String[] args){
int votesForPolly = 0; // number of votes for Polly in each precinct
int votesForErnest = 0; // number of votes for Ernest in each precinct
int totalPolly = 0; // running total of votes for Polly
int totalErnest = 0; // running total of votes for Ernest
String response = ""; // answer (y or n) to the "more precincts" question
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
// Initializations
// Loop to "process" the votes in each precinct
{
System.out.println ("Enter Votes? Enter Y or N");
response=scan.next().toUpperCase();
if (response.equals("Y")){
response="Yes";
System.out.println ("Enter votes for Polly:");
votesForPolly=scan.nextInt();
totalPolly=totalPolly+ votesForPolly;
System.out.println ("Enter votes for Ernest:");
votesForErnest=scan.nextInt();
totalErnest=totalErnest+ votesForErnest;
System.out.println ("Enter another District? Enter Y or N");
response=scan.next().toUpperCase();
}else{
int count = 0;
while (count == 1){
// Print out the results
}
}
System.out.println ("Total votes for Polly is: " + totalPolly);
System.out.println ("Total votes for Ernest is: " + totalErnest);
}
}
}
Your current looping is broken (because you start with count = 0, therefore while (count == 1) is not entered, I would rewrite it as follows
final String msg = "Enter Votes for District %d?"
+ " Enter Y to continue, N to stop.\n";
// Loop to "process" the votes in each precinct
for (int i = 1;; i++) {
System.out.printf(msg, i);
response = scan.next().toUpperCase();
if (response.startsWith("N")) {
break;
}
System.out.println("Enter votes for Polly: ");
votesForPolly = scan.nextInt();
totalPolly += votesForPolly;
System.out.println("Enter votes for Ernest: ");
votesForErnest = scan.nextInt();
totalErnest += votesForErnest;
}
System.out.printf("Total votes for Polly is: %d\n"
+ totalPolly);
System.out.printf("Total votes for Ernest is: %d\n"
+ totalErnest);
You are not looping through the polling section.
Change
if (response.equals("Y")){
to
while (response.equals("Y")){
and remove the else statement.
When I enter input that satisfies everything and doesn't trigger any of my errors, the program just exits after last input like it is skipping over the for or if loop.
Also after System.out.printf("Enter the name of your second species: "); it won't allow for any input, it just skips to the next prompt. I'm not sure why that is. The section above it asking for the first species' info works fine.
import java.util.Scanner;
public class HW2johnson_pp1 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Please enter the species with the higher" +
" population first\n");
System.out.printf("Enter the name of your first species: ");
String Species1 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop1 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth1 = keyboard.nextInt();
System.out.printf("Enter the name of your second species: ");
String Species2 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop2 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth2 = keyboard.nextInt();
if (Pop2 > Pop1) {
System.out.printf("The first population must be higher. \n");
System.exit(0);
}
Species input1 = new Species();
input1.name = Species1;
input1.population = Pop1;
input1.growthRate = Growth1;
Species input2 = new Species();
input2.name = Species2;
input2.population = Pop2;
input2.growthRate = Growth2;
if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <=
(input1.predictPopulation(2) - input2.predictPopulation(2))){
System.out.printf(Species2 + " will never out-populate " +
Species1 + "\n");
}
else {
for (int i = 0; input2.predictPopulation(i) <=
input1.predictPopulation(i); i++) {
if (input2.predictPopulation(i) == input1.predictPopulation(i)) {
System.out.printf(" will out-populate \n");
}
}
}
}
}
This for the predictPopulation():
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;
return result;
}
This is because you never print anything after Species 2 overtakes Species 1, except in the very special case that Species 2 and Species 1 have exactly the same population in some year.
This is because, when you enter Species 1's growth rate, you enter an integer, and then press Enter. keyboard.nextInt() swallows the integer, but leaves the newline on the input-buffer, so the subsequent keyboard.nextLine() thinks there's an empty line there waiting for it.