I don't know how to get the right output - console

import java.util.Scanner;
public class NumberWord {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
String word = x.nextLine();
int number = x.nextInt();
System.out.println(number + ","+" " + word);
}
}
I want to write the program that reads in from the console a string and an integer and then outputs the integer followed a comma, a space, and then the string. For example, if the input is Wow and 10 then your output should be 10, Wow.

OK.. so this is my code, copied from yours..
public class NumberWord {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
String word = x.nextLine();
int number = x.nextInt();
System.out.println(number + "," + " " + word);
}
}
And them here is the output. Isnt this as expected?
IMP: Because you are using nextLine, make sure that you are pressing Enter after intering Wow and then after 10 as well.
BTW, Are you entering 10 first and then wow like below?

Related

netcore - elegant way to check var A or B is not null/empty to get it

Is there any operator like || to get first non-null/empty value like we can do in other languages?
I can achieve the same using ifs:
public static void Main(string[] args)
{
string a = "value";
string b = null;
string c = b;
if (string.IsNullOrEmpty(c)) {
c = a;
if(string.IsNullOrEmpty(c)){
throw new System.Exception("...");
}
}
}
If I have more variables to check, it will become a mess. Is there other way to achieve it?
You can use extensions for this
public static string IfNullOrEmptyGet(this string str, string newValue)
{
if (!string.IsNullOrEmpty(str))
return str;
if (string.IsNullOrEmpty(newValue))
throw new Exception($"{nameof(newValue)} is null or empty");
else
return newValue;
}
and use like c = c.IfNullOrEmptyGet(a)

I need to identify characters in a string using a users input

For example if the user enters the string "hello world" they will then be prompted for a number. If the user enters "6" I want "w" to print
This is my work so far which doesn't seem to work
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string:");
String str = in.next();
System.out.print("Enter the index: ");
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
System.out.print(c);
}
}
This is the code. You have to use nextLine rather than next
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string:");
String str = in.nextLine();
System.out.print("Enter the index: ");
Scanner reader = new Scanner(System.in);
Integer index = Integer.parseInt(reader.nextLine());
char c = str.charAt(index);
System.out.print(c);
}}

How to access a method (value) that is nested in a public static class

How do I access/get the string return values of a public static method that is nested in a public static class?
I want to display the string on a screen.
I've tried using private StringProperty variables to setDataString() the method return values as seen in the code snippet below.
The method named "byteToHex(buffer)" is the one whose return value I'm trying to access.
public static class SerialPortReader implements SerialPortEventListener
{
final public static char COMMA = ',';
final public static String COMMA_STR = ",";
final public static char ESCAPE_CHAR = '\\';
#Override
public void serialEvent(SerialPortEvent event)
{
if(event.isRXCHAR() && event.getEventValue() > 0)
{
try {
byte buffer[] = serialPort.readBytes();
byteToHex(buffer);
TransCeiveSerialData dataString = new TransCeiveSerialData();
dataString.setDataString(byteToHex(buffer));
/*
* wait some milliseconds before sending next data package to avoid data losses
*/
try {
Thread.sleep(100);
}catch(InterruptedException ie)
{
Logger.getLogger(TransCeiveSerialData.class.getName()).log(Level.SEVERE, null, ie);
}
}
catch(SerialPortException spe) {System.out.println("Error in port listener: " + spe);}
}
}
}
public static String byteToHex(byte x[])
{
StringBuffer retString = new StringBuffer();
for(int i = 0; i < x.length; ++i)
{
retString.append(Integer.toHexString(0x0100 + (x[i] & 0x00FF)).substring(1));
}
return retString.toString();
}
Using for exmaple System.out.println("Received data: " + instanceOfClass.getDataString()); in an external class to get the method's return string I get a "null". But I expect to get 31323334353637380d0a.
I've also tried binding the values but without any success.
Do you perhaps have any ideas how I can solve this problem? Your help will be very much appreciated.
Thanks a lot in advance!
AvJoe

Java Code - ArrayIndexOutofBoundsException

I have written the following code and keep running into this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at yournamep3.Yournamep3test.main(Yournamep3test.java:23)
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class Yournamep3test {
public static void main(String[] args) {
// Check if target file exists
File targetFile = new File(args[0]);
try {
PrintWriter out = new PrintWriter(targetFile);
out.write("\r\nStringed musical Instrument program");
for (int arrayIndex = 0; arrayIndex < 10; arrayIndex++) {
out.write("\r\n\r\n");
out.write("\r\nCreating new Stringed Musical Instrument object now..............");
Yournamep3 violinInstrument = new Yournamep3();
violinInstrument.setNameOfInstrument("Violin # " + (arrayIndex+1));
out.write("\r\nCreated instrument with name - "
+ violinInstrument.getNameOfInstrument());
int num = violinInstrument.getNumberOfStrings();
out.write("\r\nNumber of strings in instrument is " + num);
out.write("\r\nNames of String are ");
String strings[] = violinInstrument.getStringNames();
for (int counter = 0; counter < num; counter++) {
out.write("\r\n" + strings[counter]);
}
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
out.write("\r\nIs the Instrument tuned - "
+ violinInstrument.isTuned());
out.write("\r\nTuning now.........");
violinInstrument.setTuned(true);
out.write("\r\nIs the Instrument tuned - "
+ violinInstrument.isTuned());
out.write("\r\nCalling the Instrument play method now..");
violinInstrument.startPlayInstrument();
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
out.write("\r\nStopping playing of instrument..............");
violinInstrument.stopPlayInstrument();
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
}
out.close();
} catch (IOException e) {
}
}
}
I think the issue is with line 23. Any advice would be appreciated, thanks.
This is the other part of the code yournamep3
public class Yournamep3 {
//fields to determine if the instrument is isTuned,
private boolean isTuned;
//and if the instrument is currently isPlaying.
private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public Yournamep3() {
this.isTuned = false;
this.isPlaying = false;
}
/**
* #return the name
*/
public String getNameOfInstrument() {
return name;
}
/**
* #param name the name to set
*/
public void setNameOfInstrument(String nameOfInstrument) {
this.name = nameOfInstrument;
}
// Other methods
public boolean isPlaying() {
return isPlaying;
}
public void setPlaying(boolean playing) {
this.isPlaying = playing;
}
public boolean isTuned() {
return isTuned;
}
public void setTuned(boolean isTuned) {
this.isTuned = isTuned;
}
public void startPlayInstrument() {
System.out.println("The Instrument is now Playing.");
isPlaying = true;
}
public void stopPlayInstrument() {
System.out.println("The Instrument is not Playing anymore.");
isPlaying = false;
}
public void startTuneInstrument() {
System.out.println("The Instrument is Tuned.");
isTuned = true;
}
public void stopTuneInstrument() {
System.out.println("The Instrument is not Tuned.");
isTuned = false;
}
public int getNumberOfStrings() {
return this.numberOfStrings ;
}
public String[] getStringNames() {
return nameofStringsInInstrument;
}
}
I would look at your getStringNames() method for your violinInstrument. It seems to me that it isn't populating your String array properly, or the getNumberOfStrings() method does not give the right number of strings. If you put the code for that up, I can help a bit more.
Line 23 appears to be
Yournamep3 violinInstrument = new Yournamep3();
If that's the case you should check the constructor for Yournamemp3
Since Line 23 is
File targetFile = new File(args [0]);
It indicates that your args object is empty. ArrayIndexOutOfBoundException is thrown to indicate that an array has been accessed with an illegal index. 0 is an illegal index.

TrippleDES without base 64 encoding: Given final block not properly padded

I'm trying to encrypt and decrypt a string using TrippleDES algorythm and without using Base64 encoding (my app will be talking to another app that has these requirements). Everything worked beautifully when I was testing stuff using Base64 encoding/decoding, but when I switched to doing it plain-text style (like the app I'm calling requires), everything broke.
I've read this post Given final block not properly padded which says the key is wrong on decoding, but that can't be, because these lines actually pass in the same variables for both the key and transformation:
ecipher = Cipher.getInstance(transformation);
dcipher = Cipher.getInstance(transformation);
ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
dcipher.init(Cipher.DECRYPT_MODE, key, iv);
Also, I've printed out the lengths of both the encoded string and the array, their lengths are multiples of 8.
My output with I'm getting:
originalText: Abcdefgh
number of bites: 16
cryptText: d4167d9e2b3b1b2d1f940bc45099da0a
cryptText.length: 32
cryptText.getBytes().length: 32
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
Java Result: 1
My full code (slightly modified version of this tutorial http://eternusuk.blogspot.com/2008/09/java-triple-des-example.html):
package com.test.encrypt;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Hex;
public class TrippleDESTest
{
private Cipher ecipher;
private Cipher dcipher;
private String algorithm = "DESede";
private String transformation = "DESede/CBC/PKCS5Padding";
private String keyPhrase = "123456789012345678901234"; //your keyphrase 24 bit
private SecretKey key;
private IvParameterSpec iv;
private static TrippleDESTest cryptoUtil;
private String ENCODING = "UTF-8";
public static TrippleDESTest getInstance() throws Exception
{
if (cryptoUtil == null)
{
cryptoUtil = new TrippleDESTest();
}
return cryptoUtil;
}
private TrippleDESTest() throws Exception
{
DESedeKeySpec keySpec = new DESedeKeySpec(keyPhrase.getBytes());
key = SecretKeyFactory.getInstance(algorithm).generateSecret(keySpec);
iv = new IvParameterSpec(new byte[8]);
ecipher = Cipher.getInstance(transformation);
dcipher = Cipher.getInstance(transformation);
ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
dcipher.init(Cipher.DECRYPT_MODE, key, iv);
}
public String encrypt(String str) throws Exception
{
byte[] utf8 = str.getBytes(ENCODING);
byte[] enc = ecipher.doFinal(utf8);
System.out.println("number of bites: " + enc.length);
return Hex.encodeHexString(enc);
}
public String decrypt(String str) throws Exception
{
byte[] dec = str.getBytes();
byte[] utf8 = dcipher.doFinal(dec);
return Hex.encodeHexString(utf8);
}
public static void main(String[] args) throws Exception
{
TrippleDESTest test = TrippleDESTest.getInstance();
String originalText = "Abcdefgh";
System.out.println("originalText: " + originalText);
String cryptText = test.encrypt(originalText);
System.out.println("cryptText: " + cryptText);
System.out.println("cryptText.length: " + cryptText.length());
System.out.println("cryptText.getBytes().length: " + cryptText.getBytes().length);
System.out.println("decote text: " + test.decrypt(cryptText));
}
}// end class TrippleDESTest
Thanks in advance!
You are performing the hexadecimal encoding in the wrong order. You need to decode the ciphertext, instead of encoding the plain text in your decrypt method.

Resources