Method not working? - java

Updated code:
import java.util.*;
public class Main {
/**
* #param args
*/
static int[] C;
static int[] D;
static String P;
public static void main(String[] args) {
C = new int[10];
D = new int[10];
getNumber();
}
private static void getNumber() {
System.out
.println("Enter your first number with spaces in between digits.");
Scanner S = new Scanner(System.in);
String O = S.nextLine();
String[] A = new String[10];
A = O.split(" ");
for (int X = 0; A.length > X; X++) {
C[X] = toNumber(A[X]);
}
String P = S.nextLine();
String[] B = new String[10];
B = P.split(" ");
for (int Y = 0; B.length > Y; Y++) {
C[Y] = toNumber(A[Y]);
}
System.out.print(C[0]);
remainders();
}
private static void remainders() {
for (int A = 0; C.length > A; A++) {
if (D[1] * C[A] >= 10) {
Integer B = new Integer(D[1] * C[A]);
Character E = B.toString().charAt(0);
P.concat(E.toString());
}
}
for (int A = 0; C.length > A; A++) {
if (D[0] * C[A] >= 10) {
Integer B = new Integer(D[1] * C[A]);
Character E = B.toString().charAt(0);
P.concat(E.toString());
}
}
System.out.print(P);
}
private static int toNumber(String string) {
if (string.equals("0")) {
return 0;
} else if (string.equals("1")) {
return 1;
} else if (string.equals("2")) {
return 2;
} else if (string.equals("3")) {
return 3;
} else if (string.equals("4")) {
return 4;
} else if (string.equals("5")) {
return 5;
} else if (string.equals("6")) {
return 6;
} else if (string.equals("7")) {
return 7;
} else if (string.equals("8")) {
return 8;
} else if (string.equals("9")) {
return 9;
} else {
return 0;
}
}
}
For some reason, the last thing it prints is null. I am pretty sure the problem is the toNumber method, but I can't figure out what's wrong. If there are other problems with the code other than this, please let me know. Please help.
Edit: Problem seems to be with remainder method, please help

Use the string.equals(n) method to test if string is n

String constants are compared this way: "0".equals(string). String literals are actual String objects and You can call any String method on them. And you should prefer to call methods on constants, because it's guaranteed they exists, whereas variables can be null.
You don't need to reinvent the wheel. Java has rich SDK.
Simply use
int x = Integer.valueOf(a[X]);
If you want only numbers 0-9, then simply test
if (0 <= x && x <= 9) {
//valid continue
} else {
//invalid state handling
}

Related

Finite State Machine Program invalid output

I am working on a project and my code isn't working not sure why. Given the test program and general class I need a program that satisfies the following logical regular epxression:
L1: For alphabet {a,b}, all strings that contain an odd number of a's and exactly one b.
Test input: aabaaaa, aaabaaaa, aabaaaab, baaaaaa, aaaaabaa
What it should be:
aabaaaa False
aaabaaaa True
aabaaaab false
baaaaaa false
aaaaabaa True
Program output:
(ture, true, true, false, true)
My Test program:
import java.util.Scanner;
// Test Finite State Machine Class
public class TestFSML1
{
public static void main(String[] args){
String A = "ab";
int[][] ST = {{1,3,0},
{1,2,1},
{2,2,2},
{3,3,3}};
int[] AS = {0,0,1,0};
Scanner in = new Scanner(System.in);
String inString;
boolean accept1 = false;
FSM FSM1 = new FSM(A, ST, AS);
// Input string is command line parameter
System.out.println(" Input Accepted:");
for(int i=0;i<args.length;i++) {
inString = args[i];
accept1 = FSM1.validString(inString);
System.out.printf("%10s%13s\n",inString, accept1);
}
} // end main
} // end class
FSM Class
// Finite State Machine Class
public class FSM
{
// Instance variables
public String alphabet;
public int stateTrans[][];
public int acceptState[];
private int cstate;
// Constructor function
public FSM(String A, int[][] ST, int[] AS)
{
int NSYMBOLS = A.length();
int NSTATES = AS.length;
// Alphabet
alphabet = "" + A;
// State transition table
stateTrans = new int[NSTATES][NSYMBOLS];
for(int r = 0; r < NSTATES; r++)
for(int c = 0; c < NSYMBOLS; c++)
stateTrans[r][c] = ST[r][c];
// Accept states
acceptState = new int[NSTATES];
for(int r = 0; r < NSTATES; r++)
acceptState[r] = AS[r];
// Start state
cstate = 0;
}
// Methods
public int getState()
{
return cstate;
}
public void setState(int state)
{
cstate = state;
return;
}
public int nextState(char symbol)
{
int nstate = -1;
int col = alphabet.indexOf(symbol);
if(col >= 0)
nstate = stateTrans[cstate][col];
return nstate;
}
public boolean accept(int state)
{
if(state < 0)
return false;
return (acceptState[state] != 0);
}
public boolean validString(String word)
{
cstate = 0;
for(int k = 0; k < word.length(); k++){
cstate = nextState(word.charAt(k));
System.out.print(cstate);
System.out.println(" " + word.charAt(k));
if(cstate < 0)
return false;
}
return accept(cstate);
}
} // end class
Thanks!
Here's a simple method I typed up to perform the task you wanted.
public static boolean validWord(String s) {
int aCounter = 0;
int bCounter = 0;
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if ((int) c == (int) 'a') {
aCounter++;
} else {
bCounter++;
}
}
return (aCounter % 2 == 1 && bCounter == 1);
}
I had trouble understanding how you were implementing your method, and I think it could be much simpler. I'm sure the instance variables you included in the FSM class serve some other use, but I you don't really need any of them to analyze the string. Just use something like this, it should be easy enough to integrate into your code as all it takes is the string. Hope this helps!

how to return in a recurssive fn in java

Actually my aim is to find the super no for eg i will be given 2 values n,k where n=148 and k =3 so i have to form p = 148148148 then add digits of p until i get a single no (ans = 3) this is what i have tried.......
import java.util.*;
public class RecurrsiveDigitSum {
public int check(int n) {
int s = 0;
int d;
while(n>0) {
d = n%10;
s = s+d;
n = n/10;
System.out.println(s);
}
if(s/10 !=0){
check(s);
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int sum;
RecurrsiveDigitSum obj = new RecurrsiveDigitSum();
sum = obj.check(n);
System.out.println(sum);
sum = sum * k;
System.out.println(sum);
int s1 = obj.check(sum);
System.out.println(s1);
}
}
but the problem here is that even if my s = 4 finally its just returning the first value of s that has been found so pls help me friends
you must put return before recursive calling.
if(s/10 !=0){
return check(s);
}
If you don't put it, the result of calling function will be loss and the result of s will be returned instead of check(s).
I've improved your solution little bit.
public int check(int n) {
int s = 0;
while(n>0) {
s += n%10;
n /= 10;
}
if(s/10 != 0){
return check(s);
}
return s;
}

comparing two statements with one define variable java

I wrote this code that random picks two cards from a deck, but I'm having trouble trying to get it to compare, I've run into some issues and want to work that out step by step but unsure how to compare both statements with only one defined variable?
package question1;
public class HouseOfCards {
public static void main(String[] args) {
String [] SuitNames= {
"Spades","Diamonds","Clubs","Hearts"
};
String [] CardNames= {
"Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"
};
String SuitName="hi",SuitName2="die";
String CardName="hi", CardName2="die";
for (int i=0; i<=1; i++){
int numCard=52;
int randNum=(int)(Math.random() * numCard);
int randNum2=(int)(Math.random() * numCard);
int suitNum = randNum / 13;
int cardNum = randNum % 13;
int suitNum2 = randNum2 / 13;
int cardNum2 = randNum2 % 13;
SuitName = SuitNames[suitNum];
CardName = CardNames[cardNum];
SuitName2 = SuitNames [suitNum2];
CardName2 = CardNames[cardNum2];
System.out.println(CardName + " of " + SuitName);
}
if (CardName.equals(CardName2)){
System.out.println("Same Rank");
}
else if (SuitName.equals(SuitName2)){
System.out.println("Same Suit");
}
}
}
i edited my code so that it displays if its the same rank between both random picked cards or same suit between random picked cards, but sometime it doesn't print the statement, why?
Try something like this:
public class HouseOfCards {
public class HouseOfCards {
public static void main(String[] args) {
int Spades=1;
String [] suitNames= {
"Spades","Diamonds","Clubs","Hearts"
};
String [] cardNames= {
"Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"
};
String card1="";
String card2="";
String suitName="";
String cardName1="";
String suitName2="";
String cardName2="";
int cardPosition1 = 0;
int cardPosition2 = 0;
for (int i=0; i<=1; i++){
int numCard=52;
int randNum=(int)(Math.random() * numCard);
int suitNum = randNum / 13;
int cardNum = randNum % 13;
if(i==0) {
suitName = suitNames[suitNum];
cardName1 = cardNames[cardNum];
card1 = cardName1+" of "+suitName;
}
else {
suitName2 = suitNames[suitNum];
cardName2 = cardNames[cardNum];
card2 = cardName2+" of "+suitName2;
}
}
System.out.println(card1);
System.out.println(card2);
for (int i = 0; i < cardNames.length; i++) {
if(cardName1.equals(cardNames[i])) {
cardPosition1 = i;
}
if(cardName2.equals(cardNames[i])) {
cardPosition2 = i;
}
}
System.out.println(cardPosition1);
System.out.println(cardPosition2);
if(cardPosition1>cardPosition2) {
System.out.println("First card has bigger number");
}
else if (cardPosition1<cardPosition2) {
System.out.println("Second card has bigger number");
}
else if (cardPosition1==cardPosition2) {
System.out.println("Equal cards (probably different suites you can check it further)");
}
}
}

How to ADD in java through a runner class and a methods class?

ADDn - The first n (0 ≤ n ≤ 4) bits replicate and are concatenated to the first n bits. The last n bits are deleted
e.g. ADD3 ABCDEFGH becomes ABCABCDE
METHODS -
public class Methods
{
public String ADD(String x, int y)
{
if(y > 0)
{
String output = x.substring(0,y);
String output2 = x.substring(y, x.length() - y);
return output + output + output2;
}else {
return x;
}
}
RUNNER -
import java.io.*;
import java.util.*;
public class Runner
{
public static void main(String []args)throws FileNotFoundException
{
Scanner in = new Scanner(new File("data.txt"));
Methods md = new Methods();
String cell = in.nextLine();
String methods = in.nextLine();
for (int x = 0; x < 5; x++)
{
if(methods.equals(("ADD2"))
{
int i = Integer.parseInt(methods);
System.out.println( );
}
DATAFILE-
ADD2 ABBCDFGG
I need it to print ABABBCDF
class Problem {
public static void main(String[] args) {
for (int num = 1000; num <= 2000; num++) {
if (String.valueof(num).contains("3")) {
System.out.println(num);
}
}
}
}

Java: check if number belongs to Fibonacci sequence

I'm supposed to write a code which checks if a given number belongs to the Fibonacci sequence. After a few hours of hard work this is what i came up with:
public class TP2 {
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 <= n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 8;
System.out.println(ehFibonacci(n));
}
}
I must be doing something wrong, because it always returns "false". Any tips on how to fix this?
You continue the loop while fib2 <= n, so when you are out of the loop, fib2 is always > n, and so it returns false.
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 < n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 5;
System.out.println(ehFibonacci(n));
}
This works. I am not sure about efficiency..but this is a foolproof program,
public class isANumberFibonacci {
public static int fibonacci(int seriesLength) {
if (seriesLength == 1 || seriesLength == 2) {
return 1;
} else {
return fibonacci(seriesLength - 1) + fibonacci(seriesLength - 2);
}
}
public static void main(String args[]) {
int number = 4101;
int i = 1;
while (i > 0) {
int fibnumber = fibonacci(i);
if (fibnumber != number) {
if (fibnumber > number) {
System.out.println("Not fib");
break;
} else {
i++;
}
} else {
System.out.println("The number is fibonacci");
break;
}
}
}
}
you can also use perfect square to check whether your number is Fibonacci or not. you can find the code and some explanation at geeksforgeeks.
you can also see stackexchange for the math behind it.
I'm a beginner but this code runs perfectly fine without any issues. Checked with test cases hopefully it'll solve your query.
public static boolean checkMember(int n) {
int x = 0;
int y = 1;
int sum = 0;
boolean isTrue = true;
for (int i = 1; i <= n; i++) {
x = y;
y = sum;
sum = x + y;
if (sum == n) {
isTrue=true;
break;
} else {
isTrue=false;
}
}
return isTrue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(checkMember(n));
}

Categories