How to detect whitespace of operator - java

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;

Related

No sorting correctly

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.

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 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) + "'");
}

JAVA Hangman Program revealing letter at a certain index, handling multiple instances of char in word

if (posOfGuessLetter == -1)
{
System.out.print("Your letter was not found in the
spaces provided");
} //if
if (posOfGuessLetter == 0)
{
displayWordAsDashes = (guessLetter +
displayWordAsDashes.substring(posOfGuessLetter + 1));
displayWord =
displayWordAsDashes.substring(posOfGuessLetter + 1);
} //if
if (posOfGuessLetter == 9)
{
displayWordAsDashes = (displayWordAsDashes.substring(0,
posOfGuessLetter) + guessLetter);
displayWord = (displayWordAsDashes.substring(0,
posOfGuessLetter));
} //if
else
{
displayWordAsDashes = (displayWordAsDashes.substring(0,
posOfGuessLetter) + guessLetter +
displayWordAsDashes.substring(posOfGuessLetter + 1));
displayWord = (displayWordAsDashes.substring(0,
posOfGuessLetter) +
(displayWordAsDashes.substring(posOfGuessLetter + 1)));
}
while (displayWord.contains(guessLetter))
{
displayWordAsDashes = (displayWordAsDashes.substring(0,
posOfGuessLetter) + guessLetter +
displayWordAsDashes.substring(posOfGuessLetter + 1));
displayWord = (displayWordAsDashes.substring(0,
posOfGuessLetter) +
(displayWordAsDashes.substring(posOfGuessLetter + 1)));
} //while
} //else
System.out.print("The updated word is: " +
displayWordAsDashes);
I am trying to create a hangman program, and in this part it checks the index position of a user input for the character they want to find in the word and then removes the dash on that index and reveals the letter they just guessed. However, my program is not revealing both letters if the word has two of the same letter (i.e. naRRowing, lOOps) which is what I tried to program the while loop at the end to do. Can anyone tell me what I messed up on??
I didn't see what error you did but both pos == 0 and pos == 9 are superfluous due to
aString.substring(aString.length());
and
aString.substring(0, 0);
both returning the empty string.
If you don't have to keep track of where the letter was you could do something like this:
private String wordToGuess = "hangman";
private String guessedSoFar = wordToGuess.replaceAll(".", "-");
private String leftToGuess = wordToGuess;
public String guess(char c) {
for(int i = 0 ; i < leftToGuess.length() ; i++) {
if(leftToGuess.charAt(i) == c) {
guessedSoFar = guessedSoFar.substring(0, i) + c + guessedSoFar.substring(i + 1);
}
}
leftToGuess = leftToGuess.replace(c, '-');
return guessedSoFar;
}

Error on the for loop - trying to use loop to count the repetition of letter

On the for loop I have the Java applet is showing me that I have an error. I am trying to use the for loop to count the repetition of letter.
String countString = "";
for (int i = 0; i < 26; i++){
// at the line below, my java applet says I have an error, and that the
//"letterCounts" should be a int and not a string, but I need it to be a string
String n = letterCounts[i];
if (n.equals("0")) {
countString = countString + " ";
} else if (n.length() == 1) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);
You donot show the definition of letterCounts, but I bet it is int[] letterCounts.
So since letterCounts is an array of int, you cannot just assign it to a String.
Just change String n to int n and your comparison to n == 0 and it should work. See below:
String countString = "";
for (int i = 0; i < 26; i++)
{
int n = letterCounts[i];
if (n == 0) {
countString = countString + " ";
} else if (n < 10) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);

Categories