Java Comparing numbers and displaying largest, comparing strings and displaying lexiographically first - java

I need to create two different programs. One that does the following:
Enter your first number: 15
Enter your second number: 25
25 is larger than 15
and a second separate one that does the following:
Enter the first string: apple
Enter the second string: bananas
apple comes before bananas lexiographically
This is what I tried for the first one:
import java.util.Scanner;
public class ClosedLab03 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your first number: ");
int firstNumber = keyboard.nextInt();
System.out.println("Enter your second number: ");
int secondNumber = keyboard.nextInt();
int result;
if (firstNumber > secondNumber)
{
result = System.out.println(firstNumber +" is larger than " + secondNumber);
}
else
{
result = System.out.println(secondNumber + " is larger than " firstNumber);
}
Obviously I'm doing something wrong, but I don't really know what. In terms of comparing the strings, I really don't know how to compare them lexicographically. Our textbook shows us how to compare two strings and say whether or not they are the same, but not how to compare them and display which one is lexicographically first.

String.compareTo(String) does this for you. It implements the java.lang.Comparable interface.
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
Example
System.out.println("apples".compareTo("bananas")); // returns -1
System.out.println("bananas".compareTo("apples")); // returns 1
System.out.println("apples".compareTo("apples")); // return 0

Related

Comparing string length with strange output [duplicate]

This question already has answers here:
How does compareTo work?
(3 answers)
How to correctly compute the length of a String in Java?
(5 answers)
Closed 3 months ago.
This code is to compare 2 strings entered by the user and it's supposed to output whether the first string is > < or = the second string.
It's working for the most part except when I enter two phrases like gh and hi, it thinks gh is greater than hi. Maybe it's looking at the size of the actual letter.
package com.mycompany._3;
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first phrase(s): ");
String one = scanner.next();
System.out.print("Enter Second phrase(s): ");
String two = scanner.next();
int length = one.compareTo(two);
if(length > 0){
System.out.print("String one is less than string two.");
}else if (length < 0)
System.out.print("String one is greater than string two.");
else
System.out.print("Both phrases are equal length");
}
}
The compareTo() method compares two strings lexicographically.
The comparison is based on the Unicode value of each character in the strings.
You need to call length() method for each string to compare lengths
if(one.length() > two.length()) ...

Getting multiple inputs from user with char and integers Java

I'm trying to allow the user to put in multiple inputs from the user that contain a char and integers.
Something like this as input: A 26 16 34 9
and output each int added to an array.
I was thinking I could have the first input as a character and then read the rest as a string which then I separate and put into an array.
I'm not new to coding but new to java. I've been doing c++ so the syntax is a bit different.
This is what I have so far, I haven't set up my array yet for the integers.
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
int firstNumber;
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
int n = reader.nextInt();
if (n=='A') {
//if array is full System.out.println("The list is full!");
//else
System.out.println("Integer " + " " + "has been added to the list");
}
else if (n=='Q') {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Could you specify better how should your input be given? From your question, if I understand well, the user simply type "A" followed by a list of numbers separated by a space. So I would simply read the next line, split it in words (separated by a space) and check if the first word is the letter "A". Here it goes:
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
String line = reader.nextLine();
String[] words = line.split(" ");
if (words.length > 0 && words[0].equals("A")) {
//if array is full System.out.println("The list is full!");
// => I don't understand this part
//else
for(int i = 1; i<words.length; i++){
int integer = Integer.parseInt(words[i]);
System.out.println("Integer " + integer + " has been added to the list");
//do your stuff here
}
}
else if (words.length > 0 && words[0].equals("Q")) {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Note that in your solution, you read the next int from your scanner and then try to compare it with the character 'A'. This will not work because A is not an int. If you really want to get the first character from your scanner, you could do:
String line = reader.nextLine();
if(line.length() > 0){
char firstChar = line.charAt(0);
//do your stuff here
}
A character is not an int. You cannot read an int to expect something like 'A'. You can read a String and take its first character though. Scanner doesn't offer a convenient method to read the next String and expect it to be only one-character long. You'd need to handle that yourself.
But considering you don't know in advance how many numbers there will be to read, your solution to read the entire line and interpret it entirely, is the better one. That means you can't use nextInt() nor nextDouble() nor next() nor nextWhateverElse().
You need nextLine(), and it will give you the entire line as a String.
Then you can split() the result, and check if the first is one-char-long. Then you can parse all the others as int.
I don't immediately recall how to write this in Java – it's been a bit of a while – but what I'd do is to first separate the string by spaces, then attempt to do ParseInt on each piece.
If the string isn't a valid integer, this method will throw an exception, which you can catch. So:
If you make it to the next statement, an exception didn't happen, so the value is an integer.
If, instead, you find yourself in the exception-handler (having caught [only ...] the expected kind of exception, the value is a string.
Of course, don't "catch" any exception-type other than the NumberFormatException that you're expecting.
By the way, it is perfectly routine to use exceptions in this way. Let Java's runtime engine be the authority as to whether it's an integer or not.

How to compare nextLine() to a String

I have an assignment in my APCS class that asks us to make a combination lock and I think I have the basic structure down. However, I keep running into a problem that won't let me compare a raw nextLine() to a String.
I was wondering if nextLine()s are by default ints? Or could anyone just tell me what's wrong with my code?
if((in.nextLine()).compareTo(combo))
{
System.out.println("The lock is now unlocked.");
System.out.println("Please enter the combo to unlock: ");
if((in.nextLine()).compareTo(combo))
{
System.out.println("The lock is now locked.");
}
else
{
System.exit(0);
}
}
P.s. the ide returns the error: "error: incompatible types: int cannot be converted to boolean" and is referring to the if qualifications.
nextLine() will always return a String, so that isn't your problem.
compareTo(str) returns an negative number if str is lexicographically less than the value being compared to, 0 if the Strings are lexicographically equal, or a positive number if the str is lexicographically more than the value being compared to.
You want to use equals(str), which returns a boolean value.
Your problem is that compareTo() returns an integer value, not a Boolean.
See the Java API docs for compareTo (in interface Comparable, at http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html):
Method Detail
compareTo
Returns: a negative integer, zero, or a positive integer
as this object is less than, equal to, or greater than the specified
object.
The simplest way to compare two Strings is to use
if (in.nextLine().equals(combo)) { /* code here */ }
Watch out for another pitfall in this program, too. Your first nextLine() and your second nextLine() are actually two separate input lines. nextLine() returns the next line of input from the reader, so it will return a different line of input each time you call it. A solution is to save the results of nextLine() as a variable:
String enteredCombo = in.nextLine();
if (enteredCombo.equals(combo))
{
System.out.println("The lock is now unlocked.");
System.out.println("Please enter the combo to lock: ");
enteredCombo = in.nextLine();
if(enteredCombo.equals(combo))
{
System.out.println("The lock is now locked.");
}
else
{
System.exit(0);
}
}

In a class called Digit, write a method called lastDigit that returns the last digit of an integer number

This is a homework question that I am stumped on. My professor suggests looking up the Math.abs() method.
I need to utilize a Scanner object in the main method to query for input from the user and then use the Scanner input as parameters to the specified methods. In a class called Digit, write a method called lastDigit that returns the last digit of an integer number. For example, lastDigit(3572) should return 2.
Here is what I currently have:
import java.util.Scanner;
public class Digit {
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
System.out.print("Please enter a number: ");
int = scanIn.nextInt();
}
public int lastDigit(int number){
int last =number%10;
return last;
}
}
Java preserves sign when handling the modulo. 105 % 10 == 5 while -105 % 5 == -5. You need to get rid of the minus sign for negative numbers, and Math.abs allows you to do precisely that: return Math.abs(last); should work.
For a slightly more verbose solution, you could check if the solution would be negative, and multiply by -1 if that is the case.

Add two strings containing binary numbers

I'm teaching myself how to code with java and I use exercises I find in the Internet to practice what I learn.
Anyway, I'm in a middle of an exercise that asks me to build a method that get two strings containing only the characters "0" and "1" from the user and returns one string of them both (binary)combined
example:
BinaryAdder("0","0") - > "0"
BinaryAdder("1","1") - > "10"
BinaryAdder("10100","111") - > "11011"
what I did is:
import java.util.Scanner;
public class assigment03
{
private static String whichIsBigger(String a, String b)
{
if(a.length()>b.length())
return a;
if(a.length()<b.length())
return b;
if(a.length()==b.length())
return a;
else return null;
}
private static String binaryAdder(String a,String b)
{
int[] binaryResult= new int[maxlength(a,b)+1];
String result="";
if(whichIsBigger(a,b)==a)
{
for(int i=0;i<b.length();i++)
{
binaryResult[i]=a.charAt(i)+b.charAt(i);
}
for(int i=b.length();i<a.length();i++)
{
binaryResult[i]+=a.charAt(i);
}
}
else
{
for(int i=0;i<a.length();i++)
{
binaryResult[i]=b.charAt(i)+a.charAt(i);
}
for(int i=a.length();i<b.length();i++)
{
binaryResult[i]+=b.charAt(i);
}
}
for(int i=0;i<binaryResult.length-1;i++)
{
if(binaryResult[i]>=2)
{
binaryResult[i]=binaryResult[i]%2;
binaryResult[i+1]++;
}
}
for(int i=binaryResult.length-1;i>=0;i--)
{
result+=Integer.toString(binaryResult[i]);
}
return result;
}
private static int maxlength(String a, String b)
{
if(a.length()>b.length())
return a.length();
else
return b.length();
}
public static void main(String[] args)
{
Scanner temp= new Scanner(System.in);
System.out.print(binaryAdder(temp.next(),temp.next()));
}
}
But it doesn't return the right result.
Do you mind help me out here?
thanks a lot!
Reading your question, I understood that you might be looking for some help implementing the methods to actually add two binary numbers, and then giving back the result in base two (which btw might be complicated in Java). However, I believe that this exercise lacks of a very important restriction like the what is max length allowed for the binary numbers to be read (overflows can arise while processing the values with primitive data types like int or String). Also this exercise needs some planning when dealing with none significant zeroes like in these cases because "00110b" = "0110b" = "0110b" and when dealing with rolling over the carry of any addition that yields 2 ("10b") or 3 ("11b"). More information on those topics can be found here, in chapter 2.
At least in Java, when tackling these type of exercises, an option is to avoid dealing with such restrictions and conditions. Java provides a class called BigInteger that takes care of huge values, none significant zeroes, and the carries taking away the burden of dealing with those things from the programmers. Java BigInteger also offers a constructor that can initialize their objects in any base. (Well not any, there are some restrictions to this too, please see this link for more information).
With that said, here is my solution to this exercise:
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
public class BinaryAdder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> numbers = new ArrayList<String>();
String number = "";
int count = 1;
System.out.print("Instructions:\nPlease enter a set of binary numbers. When you are ready to calculate their addition, enter \"done\",\n\n");
System.out.print("Number " + count + ": ");
while(!(number = scanner.next()).equals("done")){
numbers.add(number);
count++;
System.out.print("Number " + count + ": ");
}
System.out.print("Result = " + binaryAdder(numbers) + "b");
scanner.close();
}
public static String binaryAdder(ArrayList<String> numbers){
BigInteger accumulator = new BigInteger("0");
for(String number: numbers){
accumulator = accumulator.add(new BigInteger(number, 2));
}
return accumulator.toString(2);
}
}
Example:
Instructions: Please enter a set of binary numbers. When you are ready
to calculate their addition, enter "done",
Number 1: 00001
Number 2: 011
Number 3: done
Result = 100b
Between lines 8-11 some variables are declared: a scanner to read the binary numbers entered, an array list to store the binary numbers entered, a string to hold a number once is entered, and a int to keep track of how many numbers have been entered, since I extended this solution to add 0,1,2,3,...,n numbers).
Line 13 prints the instructions of this solution. Line 14 only prints "Number 1: ".
The while loop between lines 16-20 sets the value entered to the variable number and checks if it is equal to "done". Given the case it steps out of the loop, otherwise, it adds the number to the array list.
Line 22 prints the result of the addition of all the binary numbers entered.
But the "magic" really happens between lines 27-35 in the method "binaryAdder" (Note that "binaryAdder" receives that ArrayList holding all the numbers entered as a parameter). At line 28 an accumulator of type BigInteger is initialized to zero to hold the addition of all the numbers in the ArrayList. Then, a for loop travels through all the numbers in the array list to add them to the accumulator. Finally, the accumulated value is returned in base two.

Categories