No sorting correctly - java

I am trying to write a program for a class. I can get the program to sort the names by time. However, when the program goes to sort by the first letter of a name I get this.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class Race {
public static void main (String[] args){
//declaring Variables
String runner1, runner2, runner3, infoRunner1, infoRunner2, infoRunner3, inputUser, rankOutput;
int runtime1, runtime2, runtime3;
inputUser = JOptionPane.showInputDialog("Please enter runner one name: ");
runner1 = (inputUser);
inputUser = JOptionPane.showInputDialog("Enter runner one time: ");
runtime1 = Integer.parseInt(inputUser);
infoRunner1 = (runner1 + " " + runtime1);
inputUser = JOptionPane.showInputDialog("Please enter runner two name: ");
runner2 = (inputUser);
inputUser = JOptionPane.showInputDialog(" Please enter runner two time ");
runtime2 = Integer.parseInt(inputUser);
infoRunner2 = (runner2 +" " + runtime2);
inputUser = JOptionPane.showInputDialog("Please enter runner three name: ");
runner3 = (inputUser);
inputUser = JOptionPane.showInputDialog(" Please enter runner three time ");
runtime3 = Integer.parseInt(inputUser);
infoRunner3 = (runner3 +" " + runtime3);
//Naming sort
String OutputName = "";
if (runner1.compareToIgnoreCase(runner2) <= 0 && runner1.compareToIgnoreCase(runner3) <= 0) {
OutputName += infoRunner1 + "\n";
if (runner2.compareToIgnoreCase(runner3) <= 0) {
OutputName += infoRunner3 + "\n";
OutputName += infoRunner2 + "\n";
} else {
OutputName += infoRunner2 + "\n";
OutputName += infoRunner3 + "\n";
}
}
else
if (runner2.compareToIgnoreCase(runner1) <= 0 && runner2.compareToIgnoreCase(runner3) <= 0) {
OutputName += infoRunner2 + "\n";
if (runner1.compareToIgnoreCase(runner3) <= 0) {
OutputName += infoRunner1 + "\n";
OutputName += infoRunner3 + "\n";
} else {
OutputName += infoRunner1 + "\n";
OutputName += infoRunner2 + "\n";
}
}
else
if (runner3.compareToIgnoreCase(runner2) <= 0 && runner3.compareToIgnoreCase(runner1) <= 0) {
OutputName += infoRunner3 + "\n";
if (runner2.compareToIgnoreCase(runner1) <= 0) {
OutputName += infoRunner2 + "\n";
OutputName += infoRunner1 + "\n";
} else {
OutputName += infoRunner1 + "\n";
OutputName += infoRunner2 + "\n";
}
}
//ranking
String firstplace = "";
String secondplace = "";
String thirdplace = "";
if (runtime1 >= runtime2 && runtime1 >= runtime3){
firstplace = infoRunner1;}
else if (runtime1 >= runtime2 && runtime1 <= runtime3){
secondplace = infoRunner1;}
else if (runtime1 <= runtime2 && runtime1 <= runtime3){
thirdplace = infoRunner1;}
if (runtime2 >= runtime1 && runtime2 >= runtime3){
firstplace = infoRunner2;}
else if (runtime2 >= runtime1 && runtime2 <= runtime3){
secondplace = infoRunner2;}
else if (runtime2 <= runtime3 && runtime2 <= runtime1){
thirdplace = infoRunner2;}
if (runtime3 >= runtime1 && runtime3 >= runtime2){
firstplace = infoRunner3;}
else if (runtime3 >= runtime1 && runtime3 <= runtime2){
secondplace = infoRunner3;}
else if (runtime3 <= runtime1 && runtime3 <= runtime2){
thirdplace = infoRunner3;}
rankOutput = thirdplace + "\n" + secondplace + "\n" +firstplace + "\n";
JOptionPane.showMessageDialog(null, "Ranking Order\n" + rankOutput + "\nName Order \n" + OutputName);
System.exit(0);
The assignment only called for certain names to be used. When I was testing the program I found it could not have the same first letter of a name. We have not gotten to the array's not sure we can use those for this assignment.

It seems this pair of lines is incorrect:
if (runner2.compareToIgnoreCase(runner3) <= 0) {
OutputName += infoRunner3 + "\n";
This code says that if runner2 comes before runner3, put out runner3 first, which seems wrong. Put out runner2 then runner 3.
To find bugs like this, walk through your code by hand. There may be other bugs, and where there is one kind of bug, look in code for similar code because the same kind of mistake may have been made more than once.
And #Robo Mop is right, there are much simpler ways. For one thing, you can lower-case all the names first before doing any comparisons. You can make a simple array of strings and then sort that. Research "collections" in Java, and the sort methods. You probably don't have to write an iterator or comparator. Taking this approach will also allow you to extend the code to sort 10,000 runners if there is a city-wide marathon for example.

Related

NumberFormatException java assembler

I have been working on an assembler in java for my VM and i dont know why this is happening because the string that is provided is a 1. I have tried trimming it and it is still throwing this error. Everything i found wont help with this issue the error is on line 117 where i set tmpa please help!
asm.java
package vm;
import java.util.Scanner;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
class asm {
public static int pc = 0;
public static void main(String[] args){
String a = "";
String filename = "prog.asm";
String tmp = "";
try
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null)
{
tmp += line;
tmp += " ";
}
reader.close();
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.", filename);
e.printStackTrace();
System.exit(1);
}
tmp = tmp.replace(", ", " ");
tmp = tmp.replace(",", " ");
tmp = tmp.replace(" ,", " ");
String[] prog = tmp.split(" ");
for(int i=0;i<prog.length;i++){
System.out.println(
"CURRENT POS: " + i +
", " + prog[i]
);
}
while(pc < prog.length){
String d = prog[pc];
if(!((prog[pc].substring(0, 1)).equals("$")) && !((prog[pc].substring(0, 1)).equals("r"))){
System.out.println("FOUND INSTR " + prog[pc].substring(0, 1));
a += " 0x";
}
if(prog[pc].equals("hlt")) {
a += "00000000";
}else if(prog[pc].equals("mov")){
if(prog[pc].substring(0, 1).equals("r")){
a += "02";
}else{
a += "01";
}
}else if(prog[pc].equals("add")){
if(prog[pc].substring(0, 1).equals("r")){
a += "04";
}else{
a += "03";
}
}
else if(prog[pc].equals("sub")){
if(prog[pc].substring(0, 1).equals("r")){
a += "06";
}else{
a += "05";
}
}
else if(prog[pc].equals("mul")){
if(prog[pc].substring(0, 1).equals("r")){
a += "08";
}else{
a += "07";
}
}
else if(prog[pc].equals("div")){
if(prog[pc].substring(0, 1).equals("r")){
a += "0A";
}else{
a += "09";
}
}else if(prog[pc].equals("psh")){
if(prog[pc].substring(0, 1).equals("r")){
a += "0C";
}else{
a += "0B";
}
}else if(prog[pc].equals("psh")){
if(prog[pc].substring(0, 1).equals("r")){
a += "0E";
}else{
a += "0D";
}
}else if(prog[pc].substring(0, 1).equals("$")){
int tmpa = Integer.parseInt(prog[pc + 1].substring(1, 2)) - 1;
String tmpc="";
char[] tmpd = prog[pc].toCharArray();
for(int i=0;i<tmpd.length;i++) {
if(tmpd[i] == '$') {}
else if(tmpd[i] == '#') break;
else tmpc += tmpd[i];
}
a += tmpa;
a += "0";
if(tmpc.length() > 3) {
a += tmpc;
}else if(tmpc.length() > 2) {
a += "0" + tmpc;
}else if(tmpc.length() > 1) {
a += "00" + tmpc;
}else if(tmpc.length() > 0) {
a += "000" + tmpc;
}
pc++;
}
else if(prog[pc].substring(0, 1).equals("r")) {
System.out.println(prog[pc + 1].substring(1, 2));
int tmpa = Integer.parseInt(prog[pc + 1].substring(1, 2).trim()); << Error
int tmpb = Integer.parseInt(prog[pc].substring(1, 2).trim());
a += tmpb;
a += tmpa;
a += "0000";
pc++;
}
pc++;
}
System.out.println(a);
}
}
prog.asm
mov $1#, r1
mov $1#, r2
add r1, r2
psh r1
hlt
When your code is ran on "hlt" line and examined substring contains an "l" letter which is not a digit, so the Integer.ParseInt cannot convert an "l" letter to an integer.

How to end the while loop with either player1 or player2 entering "Q"?

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

how do you convert a number in a text form to a number?

What is the code wherein if you input any number in text form line for example "twenty seven" the output is 27?
but with this code it will take time to make it reach like in millions that is why I want to know what can be done to make things efficient
import java.util.Scanner;
public class conversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter A Number In Text Form: ");
String inp = input.nextLine();
if (inp.equals("zero")) {
System.out.println("0");
} else if (inp.equals("one")) {
System.out.println("1");
} else if (inp.equals("two")) {
System.out.println("2");
} else if (inp.equals("three")) {
System.out.println("3");
} else if (inp.equals("four")) {
System.out.println("4");
} else if (inp.equals("five")) {
System.out.println("5");
} else if (inp.equals("six")) {
System.out.println("6");
} else if (inp.equals("seven")) {
System.out.println("7");
} else if (inp.equals("eight")) {
System.out.println("8");
} else if (inp.equals("nine")) {
System.out.println("9");
}
}
}
create a dictionary map with all possible but minimal combinations :
e.g var dics= { twenty :20 , two: 2}
Now you can split your input string by space. and then try to build a logic to utilize these values.
this will be complex to implement for sure but yes , it's possible.
You can split the string to an array with split function.
and loop it
String[] inps = inp.split(" ");
int remaining = inps.length;
String outstr = "";
for (String numstr : inps)
{
remaining--;
int digit = 0;
switch (numstr.toLowerCase()) // in the JDK7, You can use Strings in switch
{
case "twenty": outstr += '2'; digit=10; break;
case "thirty": outstr += '3'; digit=10; break;
// ...
}
if (digit == 10 && remaining == 0)
{
// tenth digit, but no remaining
outstr += '0';
}
}
System.out.println(outstr);
public static final String[] tens = {
"", // 0
"", // 1
"Twenty", // 2
"Thirty", // 3
"Forty", // 4
"Fifty", // 5
"Sixty", // 6
"Seventy", // 7
"Eighty", // 8
"Ninety" // 9
};
public static String convert(final int n) {
if (n < 0) {
return "Minus " + convert(-n);
}
if (n < 20) {
return units[n];
}
if (n < 100) {
return tens[n / 10] + ((n % 10 != 0) ? " " : "") + units[n % 10];
}
if (n < 1000) {
return units[n / 100] + " Hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
}
if (n < 100000) {
return convert(n / 1000) + " Thousand" + ((n % 10000 != 0) ? " " : "") + convert(n % 1000);
}
if (n < 10000000) {
return convert(n / 100000) + " Lakh" + ((n % 100000 != 0) ? " " : "") + convert(n % 100000);
}
return convert(n / 10000000) + " Crore" + ((n % 10000000 != 0) ? " " : "") + convert(n % 10000000);
}
public static void main(final String[] args) {
int n;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number to convert into word format");
n =s.nextInt();
System.out.println(NumberFormat.getInstance().format(n) + "='" + convert(n) + "'");
}

How to get time difference between two ZonedDateTimes and pretty print it like "4 hours, 1 minute, 40 seconds ago"?

This is how I call getTimeBetween function:
getTimeBetween(ZonedDateTime.now().minusHours(4).minusMinutes(1).minusSeconds(40), ZonedDateTime.now());
And I expect this output:
4 hours, 1 minute, 40 seconds ago
This is my getTimeBetween function:
private String getTimeBetween(ZonedDateTime zonedDateTime1, ZonedDateTime zonedDateTime2) {
Duration timeDifference = Duration.between(zonedDateTime1, zonedDateTime2);
if (timeDifference.getSeconds() == 0) return "now";
String timeDifferenceAsPrettyString = "";
Boolean putComma = false;
if (timeDifference.toDays() > 0) {
if (timeDifference.toDays() == 1) timeDifferenceAsPrettyString += timeDifference.toDays() + " day";
else timeDifferenceAsPrettyString += timeDifference.toDays() + " days";
putComma = true;
}
if (timeDifference.toHours() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.toHours() == 1) timeDifferenceAsPrettyString += timeDifference.toHours() + " hour";
else timeDifferenceAsPrettyString += timeDifference.toHours() % 24 + " hours";
putComma = true;
}
if (timeDifference.toMinutes() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.toMinutes() == 1) timeDifferenceAsPrettyString += timeDifference.toMinutes() + " minute";
else timeDifferenceAsPrettyString += timeDifference.toMinutes() % 60 + " minutes";
putComma = true;
}
if (timeDifference.getSeconds() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.getSeconds() == 1) timeDifferenceAsPrettyString += timeDifference.getSeconds() + " second";
else timeDifferenceAsPrettyString += timeDifference.getSeconds() % 60 + " seconds";
}
timeDifferenceAsPrettyString += " ago";
return timeDifferenceAsPrettyString;
}
This function works as expected but is it really necessary to do it like this? Perhaps there is a better way to achieve this?
I'm using Java 8.
How about this?
static String getTimeBetween(ZonedDateTime from, ZonedDateTime to) {
StringBuilder builder = new StringBuilder();
long epochA = from.toEpochSecond(), epochB = to.toEpochSecond();
long secs = Math.abs(epochB - epochA);
if (secs == 0) return "now";
Map<String, Integer> units = new LinkedHashMap<>();
units.put("day", 86400);
units.put("hour", 3600);
units.put("minute", 60);
units.put("second", 1);
boolean separator = false;
for (Map.Entry<String, Integer> unit : units.entrySet()) {
if (secs >= unit.getValue()) {
long count = secs / unit.getValue();
if (separator) builder.append(", ");
builder.append(count).append(' ').append(unit.getKey());
if (count != 1) builder.append('s');
secs %= unit.getValue();
separator = true;
}
}
return builder.append(epochA > epochB ? " ago" : " in the future").toString();
}
You could probably store the LinkedHashMap instead of instantiating it every method call, but this should work.

How to detect whitespace of operator

I have some problem about my code.
I want to detect whitespace of operator like " + ", " +", "+ " or "+".
I want my output is
Whitespace of an operator is "A"
How can I modify my code?
My code is here.
Scanner input = new Scanner (new File(PATH to file));
int plus1;
int plus2;
int plus3;
int plus4;
String sPlus = "";
while (in.hasNext()) {
String line = in.nextLine();
in.hasNextLine();
LOC++;
if (line.length() > 0) {
plus1 = -1;
plus2 = -1;
plus3 = -1;
plus4 = -1;
while (true) {
plus1 = line.indexOf(" + ", plus1 + 1);
plus2 = line.indexOf(" +", plus2 + 1);
plus3 = line.indexOf("+ ", plus3 + 1);
plus4 = line.indexOf("+", plus4 + 1);
if (plus1 > 0) {
sPlus = "A";
}
if (plus2 > 0) {
sPlus = "B";
}
if (plus3 > 0) {
sPlus = "C";
}
if(plus4 > 0){
sPlus = "D";
}
if ((plus1 < 0) || (plus2 < 0) || (plus3 < 0) || (plus4 < 0)) break;
}
}
}
There are two problems with your logic:
You are using trim() in line.indexOf(" +".trim(), plus2+1), which returns the index of "+" NOT " +"
Any one occurrence of " + " will be counted 4 times, because line.indexOf(" +") will also count occurrences of " + "
For 2. it would be much easier to use line.indexOf('+'), and then check before and after the index to see how many whitespaces there are:
int plus = line.indexOf('+');
if(plus == -1) break;
if(line.charAt(plus-1) == ' ') {
if(line.charAt(plus+1) == ' ') //A;
else //B;
}
else if(line.charAt(plus+1) == ' ') {
//C
}
else {
//D
}
Proper else-if could be help.
if (line.indexOf(" + ") != -1) sPlus = "A";
else if (line.indexOf(" +") != -1) sPlus = "B";
else if (line.indexOf("+ ") != -1) sPlus = "C";
else if (line.indexOf("+") != -1) sPlus = "D";
else break;

Categories