package Fibonacci;
class Fibonacci
{
public static void main(String[]args) {
int a = 0;
int b = 1;
String input;
input = javax.swing.JOptionPane.showInputDialog("How many elements you want to print in a Fibonacci series");
int n = Integer.parseInt(input);
javax.swing.JOptionPane.showMessageDialog(null, a + " "+ b + " ");
int c;
for(int i = 2; i < n; i++) {
c = a + b;
javax.swing.JOptionPane.showMessageDialog(null, c + " ");
a = b;
b = c;
}
}
}
// Here is the code ? what can I change to display the output on only one dialogbox? Sorry I'm just new with learning java,
You should first collect the data which you want to print in a DialogBox.
Then you can print the data with the DialogBox (not in the for loop).
Take a look at following code.
import javax.swing.*;
public class main {
public static long fibonacci(int n){
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
b = a + (a = b);
}
return a;
}
public static void main(String... args){
int input = Integer.parseInt(JOptionPane.showInputDialog("Number of print elements"));
String fib = "";
for (int i = 0; i <= input; i++) {
fib = fib + fibonacci(i) + "\n";
}
JOptionPane.showMessageDialog(null, fib);
}
}
Related
I'm an Engineering Student and I'm stuck on this part of the Affine Cypher.
import java.util.Scanner;
public class abcd {
public static int a, b;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter key(a,b): ");
a = sc.nextInt();
b = sc.nextInt();
Scanner hj = new Scanner(System.in);
System.out.print("Enter String: ");
String word = hj.nextLine();
sc.close();
hj.close();
System.out.println("Cyphered text: " + cypher(word));
System.out.println("Decyphered text: " + decypher(cypher(word)));
}
public static String cypher(String plaintext) {
String CT = "";
for (int i = 0; i < plaintext.length(); i++) {
char x = plaintext.charAt(i);
int val = (char)x-97;
int C = ((a* val + b)%26);
char n = (char) (C + 97);
CT = CT + n;
}
return CT;
}
public static int inv (int a, int b) {
a=a%b;
for (int x = 1; x<26; x++) {
if ((a*x)%26==1) {
return x;
}
}
return 1;
}
public static String decypher(String cyphertext) {
String t = "";
for (int i = 0; i<cyphertext.length(); i++) {
char x = cyphertext.charAt(i);
int val = (char)x - 97;
int D = ((inv(a, 26)*(val-b))%26);
char n = (char)(D + 97);
t = t + n;
}return t;
}
}
The cyphered text shows the desired output but the deciphered text doesn't match the original text.
Here is my console input and output:
Enter key(a,b):
7
2
Enter String: hello
Cyphered text: zebbw
Decyphered text: heRRo
I was expecting the deciphered text to match the original text since that is what it was supposed to do.
As Joachim Sauer and Tan Yu Hau Sean suggest, % does things you may not expect on negative numbers. If a is negative, a%b will be a number between -b and 0.
If you add a method like this
public static int mod(int a, int b) {
return (a%b+b)%b;
}
and replace your instances of % with calls to it, e.g.:
int C = mod(a* val + b,26);
things will work a lot better.
i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}
class Main{
public static void main (String str[]) throws IOException{
Scanner scan = new Scanner (System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ "," ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0,0,0};
Getting the error, "java.lang.StringIndexOutOfBoundsException: String index out of range: -1" , in one of the for loops. I want the program to check for each substring in the sWord array and count how many times it occurs in the main message input.
for (int x = 0; x < sWords.length; x++){
for (int i = 0, j = i + sWords[x].length(); j < message.length(); i++){
if ((message.substring(i,j)).equals(sWords[x])){
count[c]++;
}
}
}
}
}
Following your approach, you need to set the value of jwithin the inner loop. Otherwise, it is only assigned on the first iteration. This changes the upper bound in the inner for loop as shown below. You also need to increment the counter index c after you search for an sWord.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ ", " ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0, 0, 0};
for (int x = 0; x < sWords.length; x++) {
for (int i = 0; i <= message.length()-sWords[x].length(); i++) {
int j = i + sWords[x].length();
if ((message.substring(i, j).equals(sWords[x]))) {
count[c]++;
}
}
++c;
}
}
}
You can find number of occurrences of each string in sWords in the code below:
public static void main(String[] args) {
try {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ ", " ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0, 0, 0};
for (int i = 0; i < lenOfArray; i++) {
while (c != -1) {
c = message.indexOf(sWords[i], c);
if (c != -1) {
count[i]++;
c += sWords[i].length();
}
}
c = 0;
}
int i = 0;
while (i < lenOfArray) {
System.out.println("count[" + i + "]=" + count[i]);
i++;
}
} catch (Exception e) {
e.getStackTrace();
}
}
It's better to use apache commons lang StringUtils
int count = StringUtils.countMatches("a.b.c.d", ".");
I have a java problem that I don't know how to solve the program is :
two number must got from user n,k.
I need to find a permuation of numbers from 1 to N such that the difference between two items >=k for example :
we get the numbers (n = 5 and k = 2 )
and the answer must be 1,4,2,5,3 :
and for (n=2 and k = 2) there is not answer because the difference between 1 and two is 1(1,2 or 2,1).
I hope you understand what I want.
and I write some codes that are wrong:
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int n = user_input.nextInt();
int k = user_input.nextInt();
int a ;
if (n%2==0) a = (n-2)/2; else a = (n-1)/2 ;
if (k!=a) {System.out.println("Impossible"); return;}
int h = k+1;
int value = 0;
int t = 1;
boolean b = true;
String res = "1 ";
while (value<n-1) {
value++;
if (b){
t = t + h;
res = res + t + " ";
b = false;
}else {
t = t-k;
res = res + t + " ";
b = true;
}
}
System.out.println(res);
}
Here is the code
public class HelloWorld{
public static void calculationMethod(int n, int k) {
if(n<2 || n/2 < k) {
System.out.println("Impossible");
return;
}
else {
int i = (int)Math.ceil(n/2.0);
int j = n;
int start = i;
boolean flag = true;
while(i>=1 || j>start) {
if(flag) {
System.out.print(i + " " );
i--;
flag = false;
}
else {
System.out.print(j + " " );
j--;
flag = true;
}
}
}
}
public static void main(String []args){
calculationMethod(7,3);
}
}
The idea is to divide your range(n) in half. If k>n/2 then it is not possible to construct any such sequence.
If that is not the case, then have 2 pointers one at the middle of your range and one at the end of the range. and print them alternatively decrementing both pointers until u reach the beginning.
Feel free to improve the code.
public void calculationMethod(int n, int k) {
ArrayList<Integer> intList = new ArrayList<>();
for (int i = 1; i <= n; i++) {
int a = i;
int b = i + 2;
if (!intList.contains(a) && a<=n) {
intList.add(a);
}
if (!intList.contains(b) && b<=n) {
intList.add(b);
}
}
String mValues= TextUtils.join(",",intList);
Log.i("values", mValues);
}
I am developing a program that will search through my array for how many times my single random # appears and then print how many times or that it was not found. I have been researching ways to do this and cannot seem to get it figured out. This is what I have so far and thanks in advance.
My code:
import java.util.Scanner;
import java.util.Random;
class Main {
public static final Random RND_GEN = new Random();
public void createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
for (int i = 0; i < 1; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
for (int i = 0; i < 1; i++) {
System.out.println("Single Random # " + i + " : " + randomNumbers[i]);
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] number = new int[20];
createNum(number);
printNum(number);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
import java.util.Random;
import java.util.Scanner;
public class Main {
private static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public int findNumInstancesInArray(int[] array, int numLookingFor) {
int count = 0;
for(int i : array) {
if (i == numLookingFor) {
count++;
}
}
return count;
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numLookingFor = RND_GEN.nextInt(10) + 1;
System.out.println("Number of instances of " + numLookingFor + " is: " + findNumInstancesInArray(numbers, numLookingFor));
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
This is how you can count an element in an int array:
public int countOccurrences(int[] array, int needle) {
int count = 0;
for (int index = 0; index < array.length; array[++index] == needle ? count++ : count);
return count;
}
It seems as if this is the search part of your other question posted here: Random number and array search
There, you were suggested to learn about linear search and binary search. If you did, it shouldn't be too hard to translate linear search into code (binary search won't help you here). You simply have to loop through the array (you're code proves you know how to do that) and check every value if it equals the one you're searching for. Of course, if you want to count the hits, you have to increase a counter every time the value matches.