I have tried to develop code for project euler
Problem 17
I have successfully written a java program and the output appears as expected. But however the online judge says it is the wrong answer. Have a look at my code:
package projectEuler;
import java.util.*;
public class Problem17 {
/**
* #param args
*/
static String []units={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
static String []special={"Ten","Eleven","Twelve","Thirteen","Fourteen",
"Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
static String []tens={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
"Eighty","Ninety"};
static String hundredValue="Hundred and";
public static void main(String[] args)
{
long totalLength=0;
for(int currentNumber=1;currentNumber<=1000;currentNumber++)
{
String currentWord=getWords(currentNumber);
// System.out.println(currentNumber+"->"+currentWord.replaceAll(" ",""));
totalLength+=currentWord.replaceAll(" ","").length();
}
System.out.print("The total length of all the word is :"+totalLength);
/*Scanner input = new Scanner(System.in);
System.out.print("Enter a number :");
int num = input.nextInt();
System.out.print(getWords(num));*/
}
public static String getWords(int num)
{
//Find the equivalent word and return it
String wordValue="";
switch(String.valueOf(num).length())
{
case 1:
wordValue=operateOn_1(num);
break;
case 2:
wordValue= operateOn_2(num);
break;
case 3:
wordValue= operateOn_3(num);
break;
default:
wordValue="One Thousand";
}
return wordValue;
}
public static String operateOn_3(int num)
{
String result="";
result= Problem17.units[num/100]+" "+
Problem17.hundredValue+" "+
operateOn_2(Integer.parseInt((String.valueOf(num).substring(1))));
return result;
}
public static String operateOn_2(int num)
{
String result="";
if(String.valueOf(num).charAt(0)=='1')
{
result=Problem17.special[num%10];
}
else
{
result=Problem17.tens[Integer.parseInt(String.valueOf((String.valueOf(num)).charAt(0)))];
result+=" "+operateOn_1(num%10);
}
return result;
}
public static String operateOn_1(int num)
{
return (Problem17.units[num]);
}
}
The total length which the program found out as 21592 but it is wrong according to project euler. If any could have a look at my code and help me please...
It looks like the problem is with the word 'and'
static String hundredValue="Hundred and";
Which should not occur for numbers such as 300 (Three hundred and)
In addition to the "Hundred and"-problem described by Christopher, there is another issue:
You pass an int to operateOn_2, which you then convert to a string. This way, you miss the leading zero when converting a number like 101, which is converted to One Hundred and Eleven
Related
I'm pretty new to coding Java. Below are codes for a program that is supposed to use several methods to ask for a string, reverse the string, test for palindrome and output the result of the test. I'm trying to debug my many errors.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original, String reverse) {
if (original.equals(getString(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String original, Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original,reverse);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
}
return reverse
}
public static void main(String[] args) {
System.out.print(promptForPalindrome);
}
}
For a start in main
you are calling
System.out.print(promptForPalindrome);
but if you look at the method promptForPalindrome you will see that it takes the parameters String original, Scanner Keyboard
BUT
These parameters are not even used, so maybe just delete them and change the main code to be
System.out.print(promptForPalindrome ());
Consider reading a basic java tutorial as well.
edit
Similar problems exist for isPalindrome - I suggest you change to
public static boolean isPalindrome(String original) {
return original.equals(getReverse(original));
}
and call it in as
boolean answer = isPalindrome(original);
But then your answer in
while (answer == false) {
will never change - so many bugs
The method signatures for the isPalindrome needs to be changed to only accept 1 string argument because you don't have the reversed string when it is called. Also there is no reason to pass in a scanner object for the prompt method because you instantiate it in the method. Also I changed your .equals to .equalsIgnoreCase so you don't get messed up by capitals. Also you need to update your boolean after each loop.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equalsIgnoreCase(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
answer = isPalindrome(original);
}
return getReverse(original);
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
Hope this helps I may have made some typos so let me know.
Your code has lot of errors. Check the below working code with comments in it.
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length() - 1; i > -1; i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) { // Two args are not required
// use equals if you need a case sensitive match
if (original.equalsIgnoreCase(getReverse(original))) { // Call getReverse() to reverse the string
return true;
} else {
return false;
}
}
public static String promptForPalindrome() { // Arguments are not required
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = null;
boolean answer = false;
do { // Use a do-while loop since you need to continue till it is success
original = keyboard.nextLine();
answer = isPalindrome(original);
if (!answer) {
System.out
.printf("Error: %s is not a palindrome. Please enter a palindrome.",
original);
}
} while (!answer);
keyboard.close(); // Close the Scanner
return original;
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
}
Thanks guys for all your help,
I was finally able to debug the code.
package osu.cse1223;
import java.util.Scanner;
public class Homework08a {
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equals(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String msg, Scanner keyboard) {
System.out.print(msg);
String userInput = keyboard.nextLine();
return userInput;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String msg ="Please enter a Palindrome";
String userInput = promptForPalindrome(msg, keyboard);
while (isPalindrome(userInput) == false) {
userInput = promptForPalindrome(msg, keyboard);
}
System.out.printf("%s is a palindrome", userInput);
}
}
Given a string and an integer value x, return a new string with the first x characters
of the original string now at the end. Make sure there are enough characters before
attempting to move them to the end of the string.
Sample Data :
Data File: stringChopper.dat
apluscompsci 3
apluscompsci 5
apluscompsci 1
apluscompsci 2
apluscompsci 30
apluscompsci 4
Sample Output : (output needs to be exact)
uscompsciapl
compsciaplus
pluscompscia
luscompsciap
no can do
scompsciaplu
My code:
public class StringChopperRunner_Cavazos {
public static void main(String[] args) throws IOException {
Scanner fileIn = new Scanner(new File("stringChopper.dat"));
while(fileIn.hasNext()) {
System.out.println(StringChopper.chopper(fileIn.next(), fileIn.nextInt()));
}
}
}
class StringChopper {
public static String chopper(String word1, int index) {
if(word1.length() < index - 1){
return "no can do";
}
else {
return word1;
}
}
}
So my question is; How can I return the String with the index number indicated if it's less than that to make sure there are ENOUGH letters printed?
Use String#substring to find different portions of a String and then concatenate them together using the + operator.
if (word1.length() < index - 1){
return "no can do";
} else {
return word1.substring(index) + word1.substring(0, index);
}
I've just started with Java, and so far been only playing around solving problems online, where you're not supposed to write the whole functional of a program, but only adjust a few lines of code to the already organized code.
However, I'm still struggling to organize my code in a compiling program in IntelliJ Idea, getting confused at,e.g. how methods invocations must be properly written.
Here's what I'm getting stuck with: an example from codingbat.com:
- Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
I've come up with a solution online, but now I wanna run it in Idea, with main method, with Scanner/BufferedReader input from console etc. Looks like I'm missing something...
import java.util.Scanner;
public class Bat
{
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString();
}
public String stringBits(String str) {
String result = "";
for (int i = 0; i<str.length();i += 2) {
result += str.substring(i, i+1);
}
return result;
}
public static void printString () {
System.out.println(result);
}
}
I ask your help to solve it out. What to do to make it:
Read a word from a console;
create a new string;
print it out.
Two alternatives:
make stringBits static
create an instance of the class Bat and invoke the member method
First solution - easy, not much to change
import java.util.Scanner;
public class Bat {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString(stringBits(str));
}
public static String stringBits(String str) {
String result = "";
for (int i = 0; i < str.length();i += 2) {
result += str.substring(i, i + 1);
}
return result;
}
public static void printString (String string) {
System.out.println(string);
}
}
Second solution - a bit more advances
import java.util.Scanner;
public class Bat {
private String string;
public Bat(String string) {
this.string = string;
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
Bat bat = new Bat(str);
bat.printStringBits();
}
private String stringBits() {
String result = "";
for (int i = 0; i < string.length(); i += 2) {
result += string.substring(i, i + 1);
}
return result;
}
public void printStringBits() {
System.out.println(stringBits());
}
}
Your result variable is only accessible from within the "stringBits" method. Since the method returns a string you can do the following to print it:
System.out.println(stringBits(string)); //Call in main method in place of printString();
Edited: My code wasn't a working example. Note that stringBits has to be a static method in order to work.
Accidentally i postet before i was finish. Here a basic description: I'm working on a simple calculater (apprenticeship IT), and am stucked in following problem: Shurly i could get to my goal in an other way (regex-opposite match), but i'd like to understand, why this problem exists.
(I think i now reckon what's the problem. Even if i type in a letter, the scanner is trying to read the next DOUBLE. Afcourse it won't be able to compare with regex, if the error already appears before it get's to comparing :))
This works:
OP = read.next();
if (OP.matches(isOperand) == false){
happend = true;
fehlerMsg();
askForOp();
}
But this doesn't work:
result = read.nextDouble();
String stResult;
stResult = String.valueOf(result);
if (!stResult.matches(isNumber)){
fehlerMsg();
}
Would be super, if some one could give me a clue, why this doesn't work with the double Regex check. I just get a nothing specific saying error when i try to compile. Sorry for my bad english, i'm swiss.
Here the full Code (OP is a String, result a double, stResult a string and isOperand/isNumber are RegEx:
public class TheUltimativeBestCalculatorOnThisWorldIswear {
public static boolean happend = false;
public static String isOperand = "[\\+\\-\\*\\/\\^]";
public static String isNumber = "[\\d]";
public static Scanner read = new Scanner(System.in);
public static String answer;
static String sTresult;
static boolean weiter = true;
static double zahlX;
static double zahlY;
static double result;
static boolean fehler = true;
static String OP;
/**
* #param args the command line arguments
*/
//Start the Stuff
public static void main(String[] args) {
first();
LetTheShowBegin();
}
//First thing that happens
public static void first(){
write("Zahl1?");
result = read.nextDouble();
String stResult;
stResult = String.valueOf(result);
if (!stResult.matches(isNumber)){
fehlerMsg();
}
}
//Second thing that happens
public static void second(){
write("Zahl2?");
zahlY = read.nextInt();
}
//Thing that happens on n' on
public static void LetTheShowBegin(){
while (weiter){
askForOp();
second();
calc();
showTheStuff();
}
write("Tschüss");
}
public static void showTheStuff(){
sTresult = String.valueOf(result);
write(sTresult);
write("Weiter? (j oder n)");
answer = read.next();
if ("j".equals(answer)){
weiter = true;
}
else if ("n".equals(answer)){
weiter = false;
}
}
public static void askForOp(){
if (happend == false){
write("Welchen Operator möchten Sie benutzen?");
}
else if (happend == true){
write("Nochmal: Welchen OPERATOR möchten Sie benutzen? (+, -, *, /, ^)");
}
OP = read.next();
if (OP.matches(isOperand) == false){
happend = true;
fehlerMsg();
askForOp();
}
}
public static void fehlerMsg(){
write("Versuche es noch mal, ich bin ein Waal, habe keine Wahl, mit meinem Schaal....");
}
public static void calc(){
if (null != OP)switch (OP) {
case "+":
doPlus();
break;
case "-":
doMinus();
break;
case "*":
doTimes();
break;
case "/":
doDurch();
break;
case "^":
doPow();
break;
}
}
public static void doPlus(){
result = result + zahlY;
}
public static void doMinus(){
result = result - zahlY;
}
public static void doTimes(){
result = result * zahlY;
}
public static void doDurch(){
result = result / zahlY;
}
public static void doPow(){
result = Math.pow(result, zahlY);
}
public static void fehler(){
}
public static void write(String x){
System.out.println(x);
}
}
nextDouble() will throw an Exception if the next token is not a double :
InputMismatchException - if the next token does not match the Double regular expression, or is out of range
You may first call hasNextDouble() to ensure that there is a double value coming next.
Or, you may read the token as a String (method next()) , then apply your regex to check if it is a double.
I am trying to make a program that is basically virtual notecards. Each notecard has a string for a question and an answer as well as a count for now many times it has been asked. I am using a scanner in many instances and I think i am using it incorrectly, and am not quite sure why. The program will let me answer the first 2 questions, tell me they are incorrect no matter what, and skip letting me answer the last one. Here is the notecard class:
public class Notecard {
public String ans;
public String q;
public int count;
public Notecard(String q, String ans) {
this.q = q;
this.ans = ans;
this.count = 0;
}
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
System.out.println("Correct!");
return true;
} else {
System.out.println("Incorrect! Correct answer:" + this.ans);
count++;
return false;
}
}
public void clearCount() {
this.count = 0;
}
public String getQ() {
return this.q;
}
}
and here is my other file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class CreateNotecard {
int trys;
public static void main(String[] args) {
System.out.println("Get ready to be quizzed \n\n");
ArrayList<Notecard> notecards = makeCards();
quiz(notecards);
}
static ArrayList<Notecard> makeCards() {
ArrayList<Notecard> notecards = new ArrayList<Notecard>();
try {
BufferedReader in = new BufferedReader(new FileReader(
"notecards.txt"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
String[] argg = str.split(",");
notecards.add(new Notecard(argg[0], argg[1]));
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
return notecards;
}
static void quiz(ArrayList<Notecard> notecards) {
ArrayList<Notecard> backupList = notecards;
Scanner sc = new Scanner(System.in);
long seed = System.nanoTime();
Collections.shuffle(notecards, new Random(seed));
int total = notecards.size();
int correct = 0;
for (Notecard x : notecards) {
System.out.println(x.getQ());
String effort = sc.next();
Boolean nailedIt = x.answer(effort);
if (nailedIt) {
correct++;
}
}
System.out.println("Total Notecards: " + total + "\nTotal Correct: "
+ correct);
System.out.println("Accuracy: " + (correct / total));
System.out.println("Do you want to repeat? Put \"y\" or \"n\"");
String choice1 = sc.nextLine();
if (choice1.toUpperCase().equals("Y")) {
System.out.println("Use only cards missed or all? Type \"missed\" or \"all\"");
String choice2 = sc.nextLine();
if (choice2.toUpperCase().equals("MISSED")) {
quiz(notecards);
} else {
quiz(backupList);
}
} else {
return;
}
}
}
I have a text file which I am using for this program, it contains
19-9,10
square root of 4,2
capitol of Missouri,Jefferson City
Blastoise's 1st evolution,squirtle
and my output is
Get ready to be quizzed
square root of 4
2
Incorrect! Correct answer:2
capitol of Missouri
Jefferson City
Incorrect! Correct answer:Jefferson City
Blastoise's 1st evolution
Incorrect! Correct answer:squirtle
Total Notecards: 3
Total Correct: 0
Accuracy: 0
Do you want to repeat? Put "y" or "n"
You are comparing the wrong things:
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
Should be
if (this.ans.toUpperCase().equals(effort.toUpperCase())) {
The problem is that the Scanner class is looking for a delimiter to create tokens with, which is by default whitespace. Since you enter "2", the Scanner.next() finds no delimiters, so no token.
For example, if you enter "Jefferson City", the Scanner found one delimiter, so two tokens. sc.next in that case would be "Jefferson" only (no "City", that's the next token).
Solution? Read the line from stdin and using sc.nextLine()