I'm trying to implement the Caesar cipher.
But while doing so I am getting an unexpected output which I am unable to rectify.
Will someone help me please?
My code is as follows:
import java.io.*;
public class encryptology
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t, move = Integer.parseInt(br.readLine());
String s = "", st = br.readLine();
int l = st.length();
for(int x = 0; x < l; x++){
char c = st.charAt(x);
t = (int)c;
if(move != 0){
t = t + move;
if(t > 90){
t = t - 26;
}
if(t < 65){
t += 26;
}
c = (char)t;
s = st + c;
}
}
System.out.println(s);
}
}
I entered move = 2 and st = charles
The output was: charles[
You are changing wrong string. You are acctualy setting result with starting string st and add encrypted char. Change
s=st+c;
to
s=s+c;
Related
I have tried to write a Java program that count number of words start with UpperCase in each line separately, like in a txt file, and print the line number next to the number of words start with UpperCase in that line.
I have only come out with how to count the number for a single line using:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine();
char ch;
int count = 0;
for (int i = 1; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isUpperCase(ch) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
}
}
System.out.println("total number of words start with capital letters are :" + count);
I tried to do it on the way I want, but it keep showing me "File is empty":
FileInputStream in = new FileInputStream("io-02.txt");
Scanner inScanner = new Scanner(in);
FileOutputStream out = new FileOutputStream("io-02-out.txt");
PrintWriter pwr = new PrintWriter(out);
int linenumb=0;
String s="";
char c;
int count = 0;
inScanner.useDelimiter("");
for (int i = 1; i < s.length(); i++) {
s = " " + inScanner.nextLine().trim();
c = s.charAt(i);
if (Character.isUpperCase(c) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
} else if(s == "\n"){
if(linenumb == 0)
pwr.printf("%6s%35s%n", "Line#", "Number of Uppercase characters");
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
count = 0;
}
}
if(linenumb == 0)
System.out.println("Error: The input file is empty");
else{
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
System.out.println("The file output.txt has been created . . . ");
}
Please help.
Java 8 solution:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
final public class UppercaseWordCounter { // https://stackoverflow.com/questions/49193228/counting-number-of-words-start-with-uppercase-letter-in-strings-java
final private static File FILE_WORDS = new File("io-02.txt");
final private static File FILE_RESULTS = new File("io-02-out.txt");
public static void main(final String[] args) {
if (!FILE_WORDS.exists()) {
System.err.println("Input file does not exist: " + FILE_WORDS);
System.exit(1);
}
if (FILE_RESULTS.exists()) {
if (!FILE_RESULTS.delete()) {
System.err.println("Intended output file exists already and can't be deleted: " + FILE_RESULTS);
System.exit(2);
}
}
try (final BufferedReader br = Files.newBufferedReader(FILE_WORDS.toPath(), StandardCharsets.UTF_8);
final BufferedWriter bw = Files.newBufferedWriter(FILE_RESULTS.toPath(), StandardCharsets.UTF_8)) {
int lineCounter = 1;
String line;
while ((line = br.readLine()) != null) {
final int upperCaseWordsInThisLine = countUpperCaseWords(line);
bw.write("Line " + lineCounter + " has " + upperCaseWordsInThisLine + " upper case word" + (upperCaseWordsInThisLine == 1 ? "" : "s") + ".\n");
lineCounter++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
private static int countUpperCaseWords(final String line) {
int ret = 0;
final int length = line.length();
boolean newWord = true;
for (int i = 0; i < length; i++) {
final char c = line.charAt(i);
if (" .,;/".indexOf(c) >= 0) {
newWord = true;
} else if (newWord) {
newWord = false;
if (Character.isUpperCase(c)) {
ret++;
}
}
}
return ret;
}
}
Why don't you use a method from Files class, which is available from java 1.7
List<String> lst = Files.readAllLines(Path path, Charset cs)
then you can loop over the lst List checking your condition
So I'm trying to read in a string from a file. However, I want each string to contain exactly 64 characters or less if the last string doesn't have 64 in it. So essentially I have a counter, when that counter reaches 64, I set the array of characters to a string, go to the next row and reset the count to zero. However I'm not getting output of any kind when I run it. Any help is appreciated. Here is a snippet of my code
public static void main(String[] args) throws IOException{
File input = null;
if (1 < args.length) {
input = new File(args[1]);
}
else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(0);
}
String key = args[0];
BufferedReader reader = null;
int len;
Scanner scan = new Scanner(System.in);
System.out.println("How many lines in the file?");
if(scan.hasNextInt()){
len = scan.nextInt();
}
else{
System.out.println("Please enter an integer: ");
scan.next();
len = scan.nextInt();
}
scan.close();
String[] inputText = new String[2 * len];
String[] encryptText = new String[2 * len];
char[][] inputCharArr = new char[2 * len][64];
reader = new BufferedReader(new FileReader(input));
int r;
int counter = 0;
int row = 0;
while ((r = reader.read()) != -1) {
char ch = (char) r;
if(counter == 64){
String temp = new String(inputCharArr[row]);
inputText[row] = temp;
encryptText[row] = inputText[row];
System.out.println(inputText[row]);
row++;
counter = 0;
}
if(row == len){
break;
}
inputCharArr[row][counter] = ch;
counter++;
}
Edit: Is this close?
CharBuffer cbuf = CharBuffer.allocate(64);
int counter = 0;
while (reader.read(cbuf) != -1) {
inputText[counter] = cbuf.toString();
encryptText[counter] = inputText[counter];
counter++;
cbuf.clear();
}
There is something wrong in this section:
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String faaltu = cin.readLine();
String inp = cin.readLine();
String[] part = inp.split("\\s");
for(int k = 0; k < part.length; k++)
{
System.out.println(part[k]);
}
obj.Smax = Integer.parseInt(part[0]);
I gave the following input:
2
4 12345
3 1234
Here is the complete code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codejam
{
Codejam(){};
static Codejam obj = new Codejam();
int totalStanding = 0;
int T;//no of test cases
int[] S;// no of people at each given shyness level
boolean[] standing;
int Smax;
int total = 0, newInv = 0;
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
obj.T = Integer.parseInt(cin.readLine());
for(int i = 0; i < obj.T; i++)
{
obj.populate();
obj.update();
while (obj.totalStanding < obj.total)
{
obj.newInv++;
obj.S[0]++;
obj.update();
}
System.out.println("Case #" + i + ": " + obj.newInv);
}
}
public void update()
{
for(int i = 0;i < obj.S.length; i++)
{
if ((totalStanding >= i) && (obj.standing[i] == false) )
{
obj.totalStanding += obj.S[i];
obj.standing[i] = true;
}
}
}
public void populate() throws IOException
{
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String faaltu = cin.readLine();
String inp = cin.readLine();
String[] part = inp.split("\\s");
for(int k = 0; k < part.length; k++)
{
System.out.println(part[k]);
}
obj.Smax = Integer.parseInt(part[0]);
obj.S = new int[Smax + 1];
obj.standing = new boolean[Smax + 1];
for(int j = 0;j < part[1].length(); j++)
{
obj.S[j] = part[1].charAt(j) - '0';
obj.total += S[j];
}
}
}
and got exception
Exception in thread "main" java.lang.NumberFormatException:
For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Codejam.populate(Codejam.java:57)
at Codejam.main(Codejam.java:24)
Please point out where I have gone wrong.
The error is pretty clear, you tried to parse to a number an empty string which thrown an exception.
We have no idea what is your input, but part[0] is the empty string causing the error :
obj.Smax = Integer.parseInt(part[0]);
It looks to me like you are trying to read too many lines from your input.
I suspect you are reading past the end of file.
I suggest you pass cin.readline () to your populate() method as an argument so you don't have to open another reader.
You also shouldn't have to escape your split expression so heavily I think it currently reads "a backslash and an s" rather than "whitespace".
What I need to do is to implement the 0-1 Knapsack problem. There is an input file named "In0302.txt" and an output file named "Out0302.txt". The program gets values from INPUT file and saves the results to OUTPUT file. I got my input values on paper from my "dr".
Putting them to the file seems to be ok in OUTPUT file. But... on classes "dr" tried to put other values in INPUT file, but the program didn't work. What is more there was no even an error, but the program was still compiling and compiling... and I can't get know where the problem is. Does anybody would try to change something in this code or tell me what is wrong ?
INPUT:
4 6
2 1
3 2
3 4
4 5
OUTPUT:
1 4
2 3
JAVA CODE:
public class Knapsack {
public static int max(int a, int b){
if (a > b){
return a;
}
else{
return b;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args){
int n = 0, W = 0, p[] = null, w[] = null, S[][] = null, S_object[][] = null;
//s[][] = arrays with values
try {
FileReader fr = new FileReader("In0302.txt");
BufferedReader in = new BufferedReader(fr);
String line = in.readLine();
String[] cols = line.split(" ");
n = Integer.parseInt(cols[0]); W = Integer.parseInt(cols[1]);
p = new int[n+1]; w = new int[n+1];
int k = 1;
while ((line = in.readLine()) != null) {
cols = line.split(" ");
p[k] = Integer.parseInt(cols[0]);
w[k] = Integer.parseInt(cols[1]);
k++;
}
S = new int[W+1][n+1];
S_object = new int[W+1][n+1];
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
if (i == 0){
S[weight][i] = 0;
S_object[weight][i] = 0;
}
else if (weight < w[i]){
S[weight][i] = S[weight][i-1];
S_object[weight][i] = S_object[weight][i-1];
}
else if (weight >= w[i-1]){
S[weight][i]=max(S[weight][i-1],S[weight-w[i]][i-1]+p[i]);
if ((max(S[weight][i-1], S[weight-w[i]][i-1] + p[i]) == (S[weight-w[i]][i-1] + p[i]))) {
S_object[weight][i]=i;
} //added new element to bag
else {
S_object[weight][i]=S_object[weight][i-1];
} //nothing has been added
}
}
}
in.close();
fr.close();
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
File outputFile;
FileWriter out;
try{
outputFile = new File("Out0302.txt");
out = new FileWriter(outputFile);
String line = "";
int max_value = S[W][n];
for (int m = n; m > 0; m--){
if (S[W][m] == max_value){
line = " " + S_object[W][m] + "";
int temp = W;
while ((temp-w[S_object[temp][m]]) > 0){
temp = temp - w[S_object[temp][m]];
line += " " + S_object[temp][m];
}
out.write(line + "\n");
out.write("\n\t");
}
}
out.close();
}
catch (IOException e) {
System.out.println("Error: " + e.toString());
}
System.out.println("Arrar of values:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S[weight][i] + " ");
}
System.out.println("");
}
System.out.println("Array of objects:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S_object[weight][i] + " ");
}
System.out.println("");
}
}
}
I wrote this code for converting binary to text .
public static void main(String args[]) throws IOException{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a binary value:");
String h = b.readLine();
int k = Integer.parseInt(h,2);
String out = new Character((char)k).toString();
System.out.println("string: " + out);
}
}
and look at the output !
Enter a binary value:
0011000100110000
string: ?
what's the problem?
instead of
String out = new Character((char)k).toString();
do
String out = String.valueOf(k);
EDIT:
String input = "011000010110000101100001";
String output = "";
for(int i = 0; i <= input.length() - 8; i+=8)
{
int k = Integer.parseInt(input.substring(i, i+8), 2);
output += (char) k;
}
Even Simpler:
String out=""+k;