I'm trying to make a code which counting pages as the user set, the problem is the ListView is skipping some of the row !!
I tried the code alone as a java code and it's work well !!
Here's the code:
public void CollectThePages(int Num1,int Num2){
int startpage = Num1;
int endpage = Num2;
int Number = startpage;
int Day = 1;
int DailyPages = 9;
while(Number >= startpage){
HashMap<String,String> data = new HashMap<>();
if(Number == startpage){
System.out.println("Day Number " + Day);
data.put("day", "Day " + Day);
Day ++;
System.out.print("From " + Number);
data.put("from","From " + Number);
Number += DailyPages;
int NumberofPages = DailyPages + 1;
System.out.print(" To "+Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + NumberofPages);
data.put("NOP",NumberofPages + " Pages");
}
if(Number >= startpage){
Number +=1;
System.out.println("Day Number " + Day);
data.put("day", "Day " + Day);
Day ++;
System.out.print("From "+Number);
data.put("from", "From " + Number);
Number += DailyPages;
int NumberofPages = DailyPages + 1;
System.out.print(" To "+Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + NumberofPages);
data.put("NOP", NumberofPages + " Pages");
}
if(Number > endpage | (Number + DailyPages) > endpage){
Number +=1;
System.out.println("Day Number " + Day);
data.put("day","Day " + Day);
Day ++;
System.out.print("From " + Number);
data.put("from","From " + Number);
int value = endpage - Number;
Number += value;
System.out.print(" To " + Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + (value + 1));
data.put("NOP",value + " Pages");
}
if(Number == endpage | (Number + 1) == endpage){
Number = 0;
}
valueList.add(data);
}
ValueList = (ListView) findViewById(R.id.valueList);
//Out of The Loop
valueListAdapter = new ValueListAdapter(getApplicationContext(),valueList);
ValueList.setAdapter(valueListAdapter);
}
And Here's the result (First page is 1, Last is 55) - Skipped the 1st day and 5th day
#Shree Krishna correctly pointed out your mistake and should fix your code accordingly. You can use following as well :-
public void CollectThePages(int Num1,int Num2){
int startpage = Num1;
int endpage = Num2;
int Number = startpage;
int Day = 1;
int DailyPages = 9;
while(Number <= endpage){
HashMap<String,String> data = new HashMap<>();
System.out.print("Day Number " + Day);
data.put("day", "Day " + Day);
++Day;
System.out.print("From " + Number);
data.put("from", "From " + Number);
int prevNumber = Number;
Number += DailyPages;
Number = Number > endpage ? endpage : Number;
int NumberofPages = Number - prevNumber + 1;
System.out.print(" To " + Number);
data.put("to", "To " + Number);
System.out.print(" | The Pages are " + NumberofPages);
data.put("NOP", NumberofPages + " Pages");
++Number;
valueList.add(data);
}
ValueList = (ListView) findViewById(R.id.valueList);
//Out of The Loop
valueListAdapter = new ValueListAdapter(getApplicationContext(),valueList);
ValueList.setAdapter(valueListAdapter);
}
As your logic in codes, Simply lets take an example if
Num1 = 1
Your condition will be
if(Number == startpage) ---> if(1 == 1) //Condition satisfied
Then what happened is Day is increased by 1 and added to variable data.
Another condition in the same loop
if(Number >= startpage) ---> if(10 >= 1) //Again Condition satisfied
Then again Day is increased by 1
Conclusion
Your every data is being shown with +1 added.
To prevent this
Check your every if condition and make them all unique, Don't make it repetitive in the same condition, OR change the value of startpage too in each condition if it doesn't violate your logic in future.
Related
I am stuck at a part where in a game, I use while loop and to end the loop and get the results of the game, I want either "player1" or "player2" to enter "Q", and so i tried doing it like this:
if (player1.equals("Q") || player2.equals("Q")){
go = false; //go is a boolean variable
}
This doesn't seem to work as I have to enter "Q" for both player1 and player2 for the game to end, but instead I just want either of them to enter "Q" and the game would stop.
Code:
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Soccer Game Between 2 Teams");
System.out.println("Win is 2 points" + "\n" + "Loss is worth 0 points" + "\n" + "Overtime is worth 1 point");
System.out.println("Type W, O, or L" + "\n" + "Type Q to end the game");
int pointsw = 0;
int pointsl = 0;
int pointso = 0;
int pointsw2 = 0;
int pointsl2 = 0;
int pointso2 = 0;
int totalpoints = 0;
int totalpoints2 = 0;
int counter = 0;
int counter2 = 0;
boolean go = true;
System.out.println("\n" + "Enter team one:");
String phrase = keyboard.next();
System.out.println("\n" + "Enter team two:");
String phrase2 = keyboard.next();
System.out.println();
while (go) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next();
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next();
if (team1.equals("W") || team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("O") || team1.equals("o")) {
pointso += 1;
} else if (team1.equals("L") || team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("W") || team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("O") || team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("L") || team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
if (team1.equals("Q") || team2.equals("Q")) {
go = false;
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
}
}
}
}
You should reorganize your code:
while (true) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next().toLowerCase();
if ("q".equals(team1)) {
break;
}
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next().toLowerCase();
if ("q".equals(team2)) {
break;
}
if (team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("o")) {
pointso += 1;
} else if (team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
} // loop completed
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
I'm not completely sure, but I think the issue is that after player 1 / player 2 says 'Q'
the scanner is still waiting for the next line to read.
String phrase = keyboard.next();
System.out.println("\n"+"Enter team two:");
String phrase2 = keyboard.next();//if player 1 types q this next() method must be resolved before it will continue to the logic
so add an if statement before play 2 goes asking if player 1 typed 'Q' , if so calculate scores and end game, if player 1 did not type 'Q' use else statement to continue on to player 2's turn
I want to be able to take the values out of the for loop as well as make individual values for the separate iterations of the for loop so that I can put them into the comparison if/else statements below the for loop.
public static void calculateBirthdays(Scanner console) {
//Print purpose
System.out.println("This program compares two birthdays");
System.out.println("and displays which one is sooner.");
Calendar cal = Calendar.getInstance();
int todayYear = cal.get(Calendar.YEAR);
int todayMonth = cal.get(Calendar.MONTH)+1;
int todayDay = cal.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat d = new SimpleDateFormat();
int todayDayValue = absDayVal(todayMonth, todayDay, todayYear);
System.out.println("Today is " + d.format(cal.getTime()) + ", day #" + todayDayValue + " of the year.");
for (int i = 1; i <= 2; i++) {
System.out.println("Person " + i + ":\nWhat month, day and year were you born?");
int month = console.nextInt();
int day = console.nextInt();
int year = console.nextInt();
int daysPassed = absDayVal(month, day, year);
int daysInYear = leapYear(todayYear);
int daysUntilBday = daysAway(daysPassed, todayDayValue, daysInYear);
DecimalFormat df = new DecimalFormat("0.##");
System.out.println(month + "/" + day + "/" + todayYear + " falls on day #" + todayDayValue + " of " + daysInYear + ".");
if(todayDayValue == daysPassed){
System.out.println("Happy birthday!");
} else if (todayDayValue != daysPassed){
System.out.println("Your next birthday is in " + daysUntilBday + " day(s).");
System.out.println("That is " + df.format((percentUntil(daysUntilBday, daysInYear)) * 100) + " percent of a year away.");
}
}
if(percent < percent) {
System.out.println("Person 1's birthday is sooner.");
} else if (percent < percent) {
System.out.println("Person 2's birthday is sooner.");
} else if (percent == percent) {
System.out.println("Wow, you share the same birthday!");
}
}
You can simply declare them outside of the loop like this.
int month;
int day;
int year;
for (int i = 1; i <= 2; i++) {
System.out.println("Person " + i + ":\nWhat month, day and year were you born?");
month = console.nextInt();
day = console.nextInt();
year = console.nextInt();
...
}
This concept is known as scope. Here is an article that might give you a better understanding on variable scope.
My code works, but what I need it to do is when nothing is enter the evaluation for the highest and the lowest should be N/A. Right now all it displays is the max and min number when something isn't entered.
Example:
Press K for keyboard or F to read expressions from a file OR escape to exit:
k
Please Enter a Post-Fix Expression (eg: 5 2 *)
Application Closed
Evaluations complete....
Highest Value: -3.4028235E38
Lowest Value: 3.4028235E38
Agregate result: 0.0
Average result: NaN
Valid expressions: 0.0
Invalid Expressions: 0.0
I need the ones in bold to say n/a but i don't know how.
private static void keyboardService(){
while (true){
System.out.println("Please Enter a Post-Fix Expression (eg: 5 2 *)");
String postfix=keyboard.nextLine();
String [] elements =postfix.split(" ");
if (postfix.equals("")){
System.out.println("Application Closed");
evaluation();
System.exit(0);
}
if (elements.length == 3){
try{
num1 = Float.valueOf(elements[0]);
num2 = Float.valueOf(elements[1]);
float total;
if(elements[2].equals("+")){
total = num1 + num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("*")){
total = num1 * num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("/")){
total = num1 / num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("-")){
total = num1 - num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else{
display("Error Invalid Expression: "+ postfix);{
invalid_count = invalid_count + 1;
}
}} catch(NumberFormatException e){
display("Error Invalid Expresion: "+postfix);
invalid_count = invalid_count + 1;
} //end of second if
} else {
display("Error Invalid Expression: "+ postfix);
invalid_count = invalid_count + 1;
}
}
}//end of keyboard service
////////////////////////////////////////////////////////////////////////////////////////////////////////
private static void calc(float total){
highest = Math.max(highest, total );
lowest= Math.min(lowest, total);
aggregate = aggregate + total;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
private static void evaluation(){
display("Evaluations complete....");
display("Highest Value: " + highest);
display("Lowest Value: " + lowest);
display("Agregate result: " + aggregate );
display("Average result: " + aggregate/valid_count);
display("Valid expressions: " + valid_count);
display("Invalid Expressions: " + invalid_count);
}
}
Here you go:
display("Highest Value: " + (highest == Float.MIN_VALUE ? "N/A" : String.valueOf(highest)));
display("Lowest Value: " + (lowest == Float.MAX_VALUE ? "N/A" : String.valueOf(lowest)));
and so on
In the evaluation method, before you print, check highest and lowest.
if (highest < 0)
display("Highest Value: " + "N/A");
else
display("Highest Value: " + highest);
Beside the fact that a better structure for you code would be the prefered solution you could achieve it with following changes in your code.
in your method ` keyboardService()
...
String [] elements =postfix.split(" ");
boolean validInput = true;
if (postfix.equals("")){
validInput = false;
in your method evaluation()
display("Highest Value: " + (validInput ? highest : "n/a"));
display("Lowest Value: " + (validInput ? lowest : "n/a"));
display("Agregate result: " + (validInput ? aggregate : "n/a"));
display("Average result: " + (validInput ? aggregate / valid_count : "n/a"));
display("Valid expressions: " + valid_count);
display("Invalid Expressions: " + invalid_count);
This code should display a menu and afterwards it should give the user the possibility to choose from the menu. The user can choose 3 items along with the quantity and afterwards the total price is displayed and the program stops.
This is what the program should look like when it runs:
This is the menu for Tal'Qroq Restourant:
This is the menu of pizzas
A.Margherita ..... $5.50
B.Capricosa ..... $6.50
C.Funghi ..... $7.00
D.Vegeterian..... $7.00
E.Tropical..... $8.00
F.Meat ..... $8.00
G.Salami..... $8.00
H.Maltija..... $8.00
I.Calzona..... $8.50
J.Tal'Qroq special..... $8.00
Enter your pizza order according to the menu letters:
After the user inputs the pizza the quantity is asked and that works fine.
The user must be asked 3 times to enter the pizza and quantity but instead the loop wont stop and keep asking and asking infinitely and this is my problem!
The following is the code:
public class Menu{
public static void main (String[]args){
float total = 0;
char cas = 0;
int quant = 0;
int count = 0;
System.out.println("This is the menu for Tal'Qroq Restourant:");
System.out.println("\n");
System.out.println("This is the menu of pizzas");
System.out.println("\n");
System.out.println("A.Margherita ..... $5.50");
System.out.println("\n");
System.out.println("B.Capricosa ..... $6.50");
System.out.println("\n");
System.out.println("C.Funghi ..... $7.00");
System.out.println("\n");
System.out.println("D.Vegeterian..... $7.00");
System.out.println("\n");
System.out.println("E.Tropical..... $8.00");
System.out.println("\n");
System.out.println("F.Meat ..... $8.00");
System.out.println("\n");
System.out.println("G.Salami..... $8.00");
System.out.println("\n");
System.out.println("H.Maltija..... $8.00");
System.out.println("\n");
System.out.println("I.Calzona..... $8.50");
System.out.println("\n");
System.out.println("J.Tal'Qroq special..... $8.00");
System.out.println("\n");
float a = 5.50f;
float b = 6.50f;
float c = 7.00f;
float d = 7.00f;
float e = 8.00f;
float f = 8.00f;
float g = 8.00f;
float h = 8.00f;
float i = 8.00f;
float j = 8.00f;
do{
System.out.print("Enter your pizza order according to the menu letters: ");
cas = Keyboard.readChar();
System.out.print("Enter the ammount of pizza you want: ");
quant = Keyboard.readInt();
if(cas == 'a' || cas == 'A'){
System.out.println("Total for " + quant + " Margherita is :" + (a*quant));
System.out.println("\n");
total = total + (a*quant);
count = count++;
}else if(cas == 'b' || cas == 'B'){
System.out.println("Total for " + quant + " Capricosa is :" + (b*quant));
System.out.println("\n");
total = total + (b*quant);
count = count++;
}else if(cas == 'c' || cas == 'C'){
System.out.println("Total for " + quant + " Funghi is :" + (c*quant));
System.out.println("\n");
total = total + (c*quant);
count = count++;
}else if(cas == 'd' || cas == 'D'){
System.out.println("Total for " + quant + " Vegeterian is :" + (d*quant));
System.out.println("\n");
total = total + (d*quant);
count = count++;
}else if(cas == 'e' || cas == 'E'){
System.out.println("Total for " + quant + " Tropical is :" + (e*quant));
System.out.println("\n");
total = total + (e*quant);
count = count++;
}else if(cas == 'f' || cas == 'F'){
System.out.println("Total for " + quant + " Meat is :" + (f*quant));
System.out.println("\n");
total = total + (f*quant);
count = count++;
}else if(cas == 'g' || cas == 'G'){
System.out.println("Total for " + quant + " Salami is :" + (g*quant));
System.out.println("\n");
total = total + (g*quant);
count = count++;
}else if(cas == 'h' || cas == 'H'){
System.out.println("Total for " + quant + " Calzona is :" + (h*quant));
System.out.println("\n");
total = total + (h*quant);
count = count++;
}else if(cas == 'i' || cas == 'I'){
System.out.println("Total for " + quant + " Maltija is :" + (i*quant));
System.out.println("\n");
total = total + (i*quant);
count = count++;
}else if(cas == 'j' || cas == 'J'){
System.out.println("Total for " + quant + " Tal'Qroq special is :" + (j*quant));
System.out.println("\n");
total = total + (j*quant);
count = count++;
}else{
System.out.println("Your selection isn't avaliable in our Menu!");
System.out.println("\n");
}
} while (count <= 3);
System.out.println("Your total is €" + total);
}
}
Any answers or help is highly appreciated :).
Your statement count = count++ looks wrong. Use just count++ or count = count + 1.
Using count = count++ creates byte code somewhat like this:
temp = count
count = count + 1
count = temp
So in effect the count is not getting incremented.
Using count = ++count should work, but logically looks wrong:
count = count + 1
count = count
Best not try the funny characteristic of compilers.
int i = 1;
i = i++;
System.out.prinln(i); //-> 1
You just have to write "i++;" and then you are good.
And btw. Never Ever save money in a float or a double ;)
Edit:
int i = 1;
i = ++i;
That would be possible because you are increasing i before you assign the new value.
You have several things that you could improve in your program. First, let's get to the bug, you are saying count = count ++ but by doing this, the compiler will start by incrementing the value of count, and then revert count to its old value, since count++ will be returning not the incremented value. To simplify, this statement does nothing, and do not increment the value of count.
When you want to increment, use the postfix operator:
count++;
By analysing your program, you can notice a lot of duplicate code that could be reduced!
For example, when comparing the inputs, you can use .equals(), this way you don't have to split the case for upper and lowercase:
(cas == 'f' || cas == 'F')
is equivalent to
cas.equals('f')
Which you can repeat for the rest of the cases.
Inside each if statement, you are doing the same system.out.println. For simplicity you can declare a variable for print, like
String typeofPizza;
And then inside each if
typeofPizza = "Margherita";
This way, you can remove the print to the end of the ifclauses:
System.out.println("Total for " + quant + typeofPizza + "is :" + total);
Thank you for your early responses :).The program worked fine. I can't believe a made such a stupid mistake count ++ instead of ++ count.I also had the change int count to 1 instead of 0.
Below is my code...I am trying to make a countdown timer. Right now it works correctly in terms of counting down in the correct sequential order. I am trying to figure out how to place an if statement within the code so that is prints 1 minute and ''seconds, instead of 1 minutes and '' seconds
import java.util.Scanner;
public class countdown {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int minutes;
System.out.println("Please enter the timer countdown in minutes:");
minutes = scan.nextInt();
while (minutes < 1) {
System.out.print("Invalid entry: Enter 1 or more minutes: ");
minutes = scan.nextInt();
}
for (int i = minutes - 1; i >= 0; i--)
{
for (int s = 59; s >= 1; s--)
System.out.println(i + " minutes, " + s + " seconds");
System.out.println("The timer is done!");
}
}
}
Like this,
String minutes = i + (i > 1 ? " minutes" : " minute"); // put this line in outer loop
String seconds = s + (s > 1 ? " seconds" : " second"); // and this line in inner loop
System.out.println(minutes +", "+ seconds);
just add an if/else statement in there:
for (int i = minutes - 1; i >= 0; i--){
String minute;
if(minutes == 1)
minute = " minute ";
else
minute = " minutes ";
for (int s = 59; s >= 1; s--){
String seconds;
if(s == 1)
seconds = " second";
else
seconds = " second";
System.out.println(i + minute + s + seconds);
}
}
The other answer is probably better, but it uses a different syntax that makes all this code into a short line. They do basically the same thing.
These two if/else statements should work.
for (int s = 59; s >= 1; s--)
{
if (i == 1)
System.out.print(i + " minute, ");
else
System.out.print(i + " minutes, ");
if (s == 1)
System.out.println(s + " second");
else
System.out.println(s + " seconds");
}