ASCII conversion - character

I wanted to convert ASCII values to its corresponding characters so I wrote this simple code:
public class Test {
public static void main(String[] args) {
int i=0;
char ch='c';
for(i=0;i<127;i++)
{
ch=(char)i;
System.out.print(ch+"\t");
}
System.out.println("finish");
}
}
But as output it's showing nothing and along with that the control is not even getting out of the loop though the process gets finished..plz explain this kind of behavior and the right code.

As other people have pointed out, you have included the control characters; if you alter the loop (as below) you get the full set, excluding these control characters:
public static void main() {
for(int i = 33; i < 127; i++)
{
char ch = (char) i;
System.out.print(i + ":" + ch + "\t");
}
System.out.println("finish");
}

Related

How to make Java display box-drawing characters? I get question marks

At my Win10 CmdPrompt, the 'chcp' command returns: "Active code page: 437".
I think CodePage_437 has box-drawing characters starting around 180 or so.
I wrote a tiny program to display chars 0-255, but get no box-drawing chars.
public class CodePage_437 {
/* Display all 256 glyphs in a 16x16 matrix */
public static void displayAllGlyphs() {
int c = 0;
for ( int y = 0; y < 16; y++) {
for (int x = 0; x < 16; x++) {
System.out.format("%3d", c );
System.out.format("%2c ", c++);
}
System.out.format("\n");
}
}
public static void main(String[] args) {
displayAllGlyphs();
System.out.format("---EOJ---\n");
}
}
I get the same output in the Eclipse 2020-12 Console pane, as in a CmpPrompt
window. It looks like an encoding problem and I must have tried 10 suggested
solutions, but none worked.

How to use selection sort in objects and classes

I'm creating two classes called stop watch and random numbers, which I have already done, but I needed to create a test program that would measure the execution time of sorting 100,000 numbers using selection sort. I know how to create a selection sort, I just don't know how to take the random numbers class and put it together with the selection sort, I get the error message "incompatible types random numbers cannot be converted to int" I hope someone can help me.
My random numbers class
import java.util.Random;
public class randomnumbers {
Random ran1 = new Random();
private int size;
public randomnumbers(){
size = 100000;
}
public int getSize(){
return size;
}
public void setSize(int newSize){
size = newSize;
}
public int [] createArray(int [] size){
for (int i = 0; i < size.length; i++){
size[i] = ran1.nextInt();
}
return size;
}
public static void printArray (int [] array){
for (int i = 0; i < array.length; i++){
if (i < 0){
System.out.println(array[i] + " ");
}
}
}
}
My test Program
public static void main (String [] args){
// Create a StopWatch object
StopWatch timer = new StopWatch();
//create random numbers
randomnumbers numbers = new randomnumbers();
//Create the size of the array
numbers.getSize();
// Invoke the start method in StopWatch class
timer.start();
//sort random numbers
selectionSort();
// Invoke the stop method in StopWatch class
timer.stop();
// Display the execution time
System.out.println("The execution time for sorting 100,000 " +
"numbers using selection sort: " + timer.getElapsedTime() +
" milliseconds");
}
// selectionSort performs a selection sort on an array
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
minIndex = j;
}
}
if (i != minIndex) {
array[minIndex] = array[i];
array[i] = min;
}
}
}
}
Where exactly are you getting "incompatible types random numbers cannot be converted to int" error?
There are multiple issues with the code:
Unconventional naming
size field is in randomnumbers class is used as actual array size in constructor but in createArray it's overshadowed with a parameter of the same name but different type and meaning.
You are not passing any array to selectionSort in Main. This is where I get compile error on your code.
printArray has if (i < 0) condition that is false for all ran1.nextInt() numbers so it will not print anything.
Feeding selectionSort with numbers.createArray(new int[numbers.getSize()]) compiles and ends up sorting the array.

Eclipse: The selection cannot be launched, and there are no recent launches

So, I know that there are many people with this problem and many questions about it, but I just couldn't fin a solution for this, every other thing I try to execute works, but this doesn't and I can't figure out why...
package prob3;
public class LargestPrimeFactor {
double num = 600851475143D;
double LargestPrimeFactor;
public void getLargestPrimeFactor(String [] args){
double prevPrimeFactor = 0;
do {
for(double i = 0; i < num/2; i++){
if((num % i == 0) && (num / i != 1)){
prevPrimeFactor = num;
LargestPrimeFactor = num / i;
} else {
continue;
}
}
} while(prevPrimeFactor != LargestPrimeFactor);
System.out.println("The biggest prime factor of " + num + " is " + LargestPrimeFactor);
}
}
you should define a main function to run your program. Something like:
public static void main(String[] args) {
getLargestPrimeFactor(args);
}

add "rotation" when we encrypt an uppercase letter by rotating 13

package edu.secretcode;
import java.util.Scanner;
/**
* Creates the secret code class.
*
*
*
*/
public class SecretCode {
/**
* Perform the ROT13 operation
*
* #param plainText
* the text to encode
* #return the rot13'd encoding of plainText
*/
public static String rotate13(String plainText) {
StringBuffer cryptText = new StringBuffer("");
for (int i = 0; i < plainText.length() - 1; i++) {
int currentChar = plainText.charAt(i);
String cS = currentChar+"";
currentChar = (char) ((char) (currentChar - (int) 'A' + 13) % 255 + (int)'A');
if ((currentChar >= 'A') && (currentChar <= 'Z')) {
currentChar = (((currentChar - 'A')+13) % 26) + 'A' - 1;
}
else {
cryptText.append(currentChar);
}
}
return cryptText.toString();
}
/**
* Main method of the SecretCode class
*
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (1 > 0) {
System.out.println("Enter plain text to encode, or QUIT to end");
Scanner keyboard = new Scanner(System.in);
String plainText = keyboard.nextLine();
if (plainText.equals("QUIT")) {
break;
}
String cryptText = SecretCode.rotate13(plainText);
String encodedText = SecretCode.rotate13(plainText);
System.out.println("Encoded Text: " + encodedText);
}
}
}
I need to make this rotation work by adding-13 to a character if the resulting character is greater-than 'Z' I am suppose to subtract 'Z' then add 'A' then subtract 1 (the number 1, not the letter '1') and do this only for capital letters. I did this in the if statement and when I typed in "HELLO WORLD!" I got 303923011009295302 and I was suppose to get "URYYB JBEYQ!" and the program is not encoding correctly. Any help would be appreciated. Thanks in advance.
You're appending an int rather than a char to cryptText. Use:
cryptText.append ((char)currentChar);
Update:
Wouldn't bother with the character value manipulation stuff. You're making all sorts of character set assumptions as it is (try running on an IBM i, which uses EBCDIC rather than ASCII, and watch it all break).
Use a lookup table instead:
private static final String in = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String out = "NOPQRSTUVWXYZABCDEFGHIJKLM";
...
final int idx = in.indexOf (ch);
cryptText.append ((-1 == idx) ? ch : out.charAt (idx));

check palindrome in java code

I'm making a really simple app in java code, but for some reason it doesnt work. its a palindrome checker.
here is the code.
MAIN:
public class main {
public static void main(String[] args) {
Palindroom.palindroomChecker("RACECAR");
}
}
`Palindroom class:
public class Palindroom {
public static void palindroomChecker(String input) {
String omgekeerd = "";
boolean isPalindroom = false;
int length = input.length();
for(int i = 0; i < length; i++ ) {
String hulp = "" + input.charAt(i);
omgekeerd = omgekeerd + hulp;
}
System.out.println(omgekeerd);
System.out.println(input);
if(omgekeerd.equals(input)){
System.out.println("DIT IS EEN PALINDROOM!");
}
else {
System.out.println("HELAAS, DIT IS GEEN PALINDROOM!");
}
}
}`
For some reason the check in the if-statement doesnt go as it has to go. As you can see i checked omgekeerd and input and i also checked earlier the length of omgekeerd to see if there were clear spaces.
Can someone help me out!
thanks in advance
greetings Mauro Palsgraaf
Your logic is flawed. You're reconstructing a new string by appending every char of the input, in the same order, and then check that both strings are equal. So your method always says that the input is a palindrome.
You should construct a new string by appending the chars in the reverse order.
Or you could make it faster by checking that the nth character is the same as the character at the length - 1 - n position, for each n between 0 and length / 2.
You are not actually reversing the string, looks like omgekeerd will be in the same order as input.
Replace for with for(int i = length-1; i >= 0; i--) {
This can be simplified a lot
boolean isPalindrome = new StringBuilder(input).reverse().equals(input);
Maybe this would work for you?
String str = "madam i'm adam."; // String to compare
str = str.replaceAll("[//\\s,',,,.]",""); // Remove special characters
int len = str.length();
boolean isSame = false;
for(int i =0; i<len;i++){
if(str.charAt(i) == str.charAt(len-1-i)){
isSame = true;
}
else{
isSame = false;
break;
}
}
if(isSame){
System.out.print("Equal");
}
else{
System.out.print("Not equal");
}
i=0;
j=str.length()-1; //length of given string
String str; // your input string
while((i<j)||(i!=j)){
if(str.charAt(i)!=str.charAt(j)){
System.out.println("not palindrome");
break;
}
i++;
j--;
}
System.out.print("palindrome");
//this can used for checking without the need of generating and storing a reverse string