Printing out variables from different methods in java? - java

I have to use different methods for this code, no java shortcuts!
Here is my code:
import java.io.*;
import java.util.Scanner;
public class pg3a {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String hex;
char choice = 'y';
boolean isValid = false;
do {
switch (choice) {
case 'y':
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase();
int hexLength = hex.length();
isValid = valid(hex);
if (isValid) {
System.out.println(hex + " is valid and equal to" + convert(hex));
}
else {
System.out.println(hex + " is invalid.");
}
case 'n':
System.out.println("quit");
}
}while (choice != 'n');
}
public static boolean valid (String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i=a; i< validString.length(); i++) {
if (!((validString.charAt(i) >= 'a' && validString.charAt(i) <= 'f')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
{
return false;
}
}
return true;
}
How can I make it so that after the program checks all the parameters for the hexadecimal number and calculates what it should be in decimal form, it prints out that the hexadecimal number is valid and then what the decimal number is??
Also how can I make it a loop that ends with either ^z or ^d to end the program?

To convert Strings representing hexadecimal numbers to Integer, you can use the Integer.toString(String, int); method:
Integer parsedValue = Integer.parseInt(hex, 16);
The first argument is the string to be converted, the second is the radix specification, hence is this value 16 for now.
To be complete, the Integer.toString(Integer, int) is the reverse if the above: it converts an Integer value to a string in the specified radix.
Just create a method named convert, and make it return this.
Printing an Integer is not a big issue, you can just concatenate it to any String using the + operator.
System.out.println("The value: " + parsedValue);
Also, keep in mind, that you have a little problem:
This line makes all the charachters uppercase in your string:
hex = hex.toUpperCase();
But here you check for lowercase letters:
if (!((validString.charAt(i) >= 'a' && validString.charAt(i) <= 'f')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
Either do hex=hex.toLowerCase();, or adjust the above condition to check to be between 'A' and 'F'.
Have to mention though that checking the validity of a String ot be converted to a numeric value is different: it tinvolves a try-catch block: try to convert the number, and if it fails, it is not valid...
Integer value; //have to declare it here to be able to access it outside of the try block
try {
value = Integer.parseInt(hex,16);
} catch(NumberFormatException e) {
//if you want to get the stack trace
e.printStackTrace(); //if not using a proper logging framework!!! Don't just print it!
//handle the situation: e.g. break loop, write eror message, offer retry for user, etc...
}

Related

How to do repeated sequence check

Question: Repeated Sequence Check
The program should enter a string (possibly containing blanks), and determine whether the characters are in
lexicographic order.
For example:
“12AABab” is in order since each character is less than or equal to the one following it (‘1’ < ‘2’, ‘2’ <
‘A’, ‘B’ < ‘a’, etc.) according to the Unicode character sequence.
“abCDef” is out of order, because ‘b’ > ‘C’ (lower-case letters come after upper-case letters in the
Unicode sequence).
If the string is in order, the program should display “The input is in order”; otherwise, it should display
“The input is out of order”
The program should repeat this process until the user enters the string “quit”, regardless of case. It should
not check the sequence of “quit”.
Finally, the program should display “Goodbye”.
Notes:
This program will require nested loops. The inner loop will check the sequence of the input, while
the outer loop will repeat the input and check process.
Be sure to reinitialize all variables at the start of the outer loop.
A string of length 0 or 1 is considered to be in order by definition.
what I could do best is: (I tried with 2 other different methods I could send it too if you like)
package homelab03;
import java.util.Scanner;
public class Quest3deneme3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String whole,remain,d,e;
char h1,h2;
int lenght,b,c,sayac;
//int[] a;
String[] a;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
whole=whole.replaceAll("\\s+","");
lenght=(int)whole.length();
//System.out.println(+lenght);
remain=whole;
sayac=0;
c=0;
b=0;
a= new String[lenght];
//boolean cem = d.compareTo(e);
while(b<lenght)
{
a[b]=remain.substring(b,b+1);
remain=remain.substring(b+1);
System.out.println(a[b]);
d=a[b];
e=a[c];
while(a[b]<a[c] )
{
sayac=sayac+1;
h1=h2;
}
}
if(sayac==lenght)
{
System.out.println("oley");
}
else
{
System.out.println("nooo");
}
}
//a[b]=remain.substring(b,b+1);
//remain=whole.substring(b+1);
//System.out.println(a[b]);
}
note we haven't learned a[b] <= this thing yet but I find it online if the solution won't require that that would be better.
note 2: we haven't learned regex either I think that might be dissalowed (I found some answers with that online but I think I won't get credit for that)
You could check this code. Maybe it will inspire you :)
import java.util.Scanner;
public class howToDoRepeatedSequanceCheck {
public void repeatedTests() {
String whole;
int inputLength,i;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
while(!whole.equals("quit")) {
whole=whole.replaceAll("\\s+","");
inputLength = whole.length();
boolean isInOrder = true;
i = 0;
while(isInOrder && i<inputLength-1 ) {
if(whole.charAt(i)<whole.charAt(i+1)) {
// System.out.println("ok " + whole.charAt(i)+ " < " +whole.charAt(i+1));
}else {
// System.out.println("error");
isInOrder = false;
}
i++;
}
if(isInOrder == true) {
System.out.println("The input is in order");
}else {
System.out.println("The input is out of order");
}
System.out.println();
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
}
System.out.println("Goodbye");
}
}

How can I modify my code to only accept a certain data type?

What can I do to modify this, is there any java function for that?
What needs to be done so that it only accepts characters and returns an error message for other data types?
import java.util.*;
public class problem5
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a letter from the alphabet: ");
char letter = in.next(".").charAt(0);
char vowels[] = {'A','E','I','O','U','a','e','i','o','u'};
int vowelcount = 0;
for (int i = 0; i < 10; i++)
{
if (vowels[i] == letter)
{
vowelcount++;
}
}
if (vowelcount > 0)
{
System.out.println("You entered a vowel.");
}
else
{
System.out.println("You entered a consonant.");
}
}
}
I need to reject input that has more than 1 char – Nico Dela Cruz
You just need to check the length of your input
String input = in.next(".");
if(input.length == 1){
char letter = input.charAt(0);
...
}
Add an else if you want to add an error message of some sort.
To check the input to only accept letter, you have Character.isLetter(char) to check every "letter" in UNICODE for you.
If you want to only accept a range of a-z and/or A-Z, you can do it yourself with an if condition or using regex.
Wrap your loop in a statement such as:
if (Character.isLetter(letter)){
and put and else clause at the end for your error
Edit:
OP has changed their question slightly, so you can either:
-Accept only the first character entered:
char letter = in.next().trim().charAt(0);
-Or as AxelH said above, only proceed if user enters one char:
if(input.length == 1){
char letter = input.charAt(0);

I keep getting "Invalid constant error" on my program and I am not sure why?

This is my code that calculates ISBN 13th number but I seem to be having trouble. It keeps giving me an error on the return about invalid character constant and every time I change it, it gives an error on the method name I don't understand why.
import java.util.Scanner;
public class ISBN {
public static int VerifyISBN(String isbn) {
if(isbn.matches("[0-9]+") && isbn.length() > 12){
for(int i = 0; i < 12; i++){
char digit = isbn.charAt(i);
int sum = 0;
if (Character.isDigit(digit)){
int digitValue = digit - '0';
if(i % 2 == 0)
sum += digitValue;
else sum += 3 * digitValue;
}
else
return 'invalid'; (This is where I get the error)
}
}
}
public static void main(String[] args) {
final String TITLE = "ISBN-13 Identifier";
System.out.println("Welcome to the " + TITLE);
Scanner input = new Scanner(System.in);
String response;
do {
System.out.print("Enter the first 12 digits of an ISBN-13: ");
String isbn = input.nextLine().trim();
//String isbnVerifier = generateISBN(isbn);
//if(isbn.equals("INVALID"));
System.out.println("The 13th number of" + isbn + " is " +
((verifyISBN(isbn))));
System.out.print("Do this again? [nY]");
response = input.nextLine().toUpperCase();
} while (!response.equals("N"));
input.close();
System.out.println("Thank you for using the " + TITLE);
}
}
Two problems:
The literal 'invalid' is incorrect Java syntax. A string is delimited with double quotes. Single quotes are used to delimit single-character literals, such as 'a' but cannot be used for strings of characters.
The method is declared to return an integer, so you cannot return a String.
If your intent is to return a sentinel value indicating that the input was invalid, you should probably use something like -1, which can then be interpreted by the caller as the error condition.
Or, you could define the method to throw an exception.

How to design a java program using the nextLine method?

Here is what my program should be like:
Java: enter a binary number.
No!
Java: Please enter a binary number.
Well maybe.
JAva:can you lease enter a binary number?
101010
Java: The binary number 101010 is 42 in base 10
However, I cant get it to repeatedly ask for the user input if the input is not valid.
Moreover, I cant use Math.pow.
Here is my codings:
import java.util.Scanner;
public class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
int[] powers = new int[16];
int powersIndex = 0;
int decimal = 0;
boolean isCorrect = true;
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
if(binary.charAt(i) == '1')
decimal = decimal + powers[powersIndex];
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
}
powersIndex++;
}
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
else
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
}
}
Problems I'm facing:
Can't use Math.pow
java wont ask for input properly (e.g. When I enter a false input, it ask me to enter a valid input. However, when I enter one, it ignores it. And it doesnt ask until the input is valid.)
If u guys can help me, I will be extremely grateful.
Thanks in advance.
First create a method that checks whether the input string is a valid binary literal or not.
Check whether it is or not. If not, just display the prompt with the text and do a nextLine again to read further input.
Do it again if the user does not enter a valid binary string.
If the user now provides a valid one, convert it to decimal.
However you have not specified what happens otherwise i.e. if the user does not provide a valid binary literal even in the 3rd attempt.
And if possible, always break down the various components of your program into smaller pieces. Something like this :
http://ideone.com/IbcW3b
The methods that do the job are :
private static int convertToBinary(String str) { // returns a decimal representation of the binary string literal }
private static boolean isBinary(String str) { // checks of string is a valid binary number }
The code assumes you loop until the user provides a valid input.
your issue is in last else :
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
else
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
put braces.
code changes are :
import java.util.Scanner;
class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
int[] powers = new int[16];
int powersIndex = 0;
int decimal = 0;
boolean isCorrect = true;
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
if(binary.charAt(i) == '1')
{
decimal = decimal + powers[powersIndex];
isCorrect = true;
}
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
binary= input.nextLine();
i=binary.length();
}
powersIndex++;
}
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
}
}
Your code is having too many issues check this one as i did some changes.

How to properly check if an input is only binary number?

Could someone tell me why this bit of code keeps telling me Number Format Exception and not print my error message when I'm trying to convert from a binary number to a decimal?`
public static void readAndConvertBinaryValue()
{
Scanner kbd = new Scanner(System.in);
boolean valid = false;
do
{
System.out.print("\nEnter a binary value containing up to 16"
+ " digits: ");
bAction = kbd.nextLine();
int result = bAction.compareTo(BINARY_NUM);
if (result > 1 || result < -9 || bAction.length() > 16)
{
System.out.print("Error: Invalid binary value."
+ "\nTry again.\nPress Enter to continue ...");
kbd.nextLine();
} else
{
char value;
int charlim = 0;
value = bAction.charAt(charlim);
if (value == '1' || value == '0')
{
binary = Integer.parseInt(bAction, 2);
valid = true;
} else
{
System.out.print("Error: Invalid binary value."
+ "\nTrya again.\nPress Enter to continue ...");
kbd.nextLine();
}
}
} while (!valid);
}
Using regular expressions:
boolean isABinNumber = bAction.matches("^[01]+$");
matches is defined in the String class and returns true if and only if the string matches the regular expression provided. The regular expression above (^[01]+$) covers all strings that from beginning (^) to end ($) is a sequence of one or more (+) 0 or 1s '[01]'.
If you are not familiar with regular expressions there is plenty of information on the web (e.g. a tutorial)
This all seems too complicated, just use Integer.parseInt() and catch the NumberFormatException if it occurs. You can then check the value is within the desired range.
Scanner kbd = new Scanner(System.in);
System.out.print("\nEnter a binary value containing up to 16" + " digits: ");
String bAction = kbd.nextLine();
try {
int binary = Integer.parseInt(bAction, 2);
if (binary >= (1 << 16)) {
System.err.println("Binary value out of range");
}
} catch (NumberFormatException e) {
System.out.print("Error: Invalid binary value.");
}
import java.util.Scanner;
import java.util.regex.Pattern;
public class CheckBinary {
public static void main(String[] args) {
String binaryNumber = new Scanner(System.in).nextLine();
String binaryPattern = "(1*0*)*";
if (Pattern.compile(binaryPattern).matcher(binaryNumber).matches()) {
System.out.println("Binary");
} else {
System.out.println("Not Binary");
}
}
}

Categories