i need to make a switch statement that can use the appropriate conversion method. here is my code
public class ExerciseTwo
{
public static void main (Strings[] args)
{
Scanner input = new scanner(system.in);
String[] binary = { "0","1","2","3","4","5","6","7","8"};
for (c = 0; c < array.length; counter++)
binary[] = input.nextInt();
System.out.println("Enter number between 0 and 8");
number = input.nextInt();
system.out.printf("the number", "number_given", "is", "binaryVersion", "binary");
}
}
I'm sorry, but the description wasn't very clear to me. Are you simply trying to convert the input value (between 0 and 8) into a binary format (as in 2 -> 10, 7 -> 111) using a switch statement? If so, this code will work. If not, can you clarify the question for me?
Thanks!
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number between 0 and 8");
int number = input.nextInt();
int binaryRepresentation = -1;
switch (number)
{
case 0:
binaryRepresentation = 0;
break;
case 1:
binaryRepresentation = 1;
break;
case 2:
binaryRepresentation = 10;
break;
case 3:
binaryRepresentation = 11;
break;
case 4:
binaryRepresentation = 100;
break;
case 5:
binaryRepresentation = 101;
break;
case 6:
binaryRepresentation = 110;
break;
case 7:
binaryRepresentation = 111;
break;
case 8:
binaryRepresentation = 1000;
break;
}
System.out.printf("the number " + number + " is " + binaryRepresentation + " in binary (-1 means invalid input)");
}
Do your home work yourself , Look at the http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html switch case definition. If you really want good solution for binary representation then look at API documentation of the Integer class
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html?is-external=true
Using the API doc is one of the first things you need to learn as a Java programmer.
Related
This question already has answers here:
Case insensitive matching in Java switch-case statement
(5 answers)
Closed 2 years ago.
So, I'm trying to make a simple menu with switches.
I have a letter choice inside it. I'm using next().charAt(0); to scan a letter.
It worked well, but I want to simplify it. you see, I have to make a case each choice both uppercase and lowercase.
So how to ignore case so I don't have to make both cases?
Also note: I'm using the old version of Java and Netbeans 8.2 as my IDE. (because my college keeps insisting not to use the newer one. Probably because they don't have the textbook yet.), so probably newer syntax wouldn't work.
my code:
import java.util.Scanner;
public class NewClass2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
char milk;
int s, h, price;
h = 0;
price = 0;
String type, size;
System.out.println("NutMart");
System.out.println("Milk selections:\n A. Milk A \n\t 1. Regular ($10) \n\t 2. Medium ($20) \n\t 3. Large ($30)");
System.out.println(" B. Milk B \n\t 1. Regular ($15) \n\t 2. Medium ($30) \n\t 3. Large ($45)");
System.out.println(" C. Milk C \n\t 1. Regular ($20) \n\t 2. Medium ($40) \n\t 3. Large ($60)");
System.out.println("Insert Milk Type: ");
milk = input.next().charAt(0);
switch(milk){
case 'a':
type = "Milk A";
h = 10;
break;
case 'b':
type = "Milk B";
h = 15;
break;
case 'c':
type = "Milk C";
h = 20;
break;
case 'A':
type = "Milk A";
h = 10;
break;
case 'B':
type = "Milk B";
h = 15;
break;
case 'C':
type = "Milk C";
h = 20;
break;
default:
System.out.println("Invalid!");
System.out.println("Please select the correct choice: ");
milk = input.next().charAt(0);
break;
}
System.out.println("Select the size: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
switch(s){
case 1:
size = "Regular";
price = h * 1;
break;
case 2:
size = "Medium";
price = h * 2;
break;
case 3:
size = "Large";
price = h * 3;
break;
default:
System.out.println("Invalid");
System.out.println("Please select the correct choice: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
break;
}
System.out.println("Individual Price: $" + price);
System.out.println("Please insert the quantity: ");
while (!input .hasNextInt()) input .next();
int quantity = input.nextInt();
int total = price * quantity;
System.out.println("Your total will be $" + total );
}
}
Note, that in this case converting to a consistent case is the best was to achieve your goal. But when you have a variety of results for dissimilar inputs in a switch statement you can do the following for case constructs.
case 'a':
case 'A:
type = "Milk A";
h = 10;
break;
...
The case will simply fall thru whether 'a' or 'A' was provided.
So I'm having trouble with creating an instance method to add two 14-based number and I was wondering if anyone could help? I'm a bit new to java and still sort of confused on the whole thing. So far I have the code to convert the 14-based numbers to base 10 then I need to add them and convert them back to base-14. I want to put them all in once instance class, but I feel like it's too much to put into one instance class.
This is the kind of input I was for the client code to be like this:
PokerNum sum = num1.add(num2);
import java.util.Scanner;
public class PokerNum{
String alienNum;
int num1, num2;
public PokerNum(String alienNum) throws IllegalArgumentException{
this.alienNum = alienNum;
String toUpper = alienNum.toUpperCase();
for (int i = 0; i < toUpper.length(); i++){
char c = toUpper.charAt(i);
if (!(Character.isDigit(c) || c == 'A' || c == 'J' || c == 'Q' || c == 'K')){
throw new IllegalArgumentException("invalid input");
}
}
}
// initialized at zero
public PokerNum() {
this.num1=0;
this.num2=0;
}
#Override public String toString(){
return PokerNum()+ " ";
}
//add pokernums
public PokerNum add(PokerNum another){
PokerNum num = new PokerNum();
this.num1 = another.num1;
this.num2 = another.num2;
public PokerNum convert(PokerNum pn){
char[] firstNum = num1.toCharArray();
int amountValue = 0;
int length = characters.length;
for (int index = 0; index < length; index++){
int symbolValue;
switch (characters[index]) {
case 'A':
symbolValue = 10;
break;
case 'J':
symbolValue = 11;
break;
case 'Q':
symbolValue = 12;
break;
case 'K':
symbolValue= 13;
break;
default:
symbolValue = characters[index] - 48;
}
amountValue += symbolValue*Math.pow(14, length - index - 1);
}
StringBuilder result1 = new StringBuilder();
while(amountValue > 0){
int digit = amountValue%14;
switch (digit) {
case 10:
result.insert(0, 'A');
break;
case 11:
result.insert(0, 'J');
break;
case 12:
result.insert(0, 'Q');
break;
case 13:
result.insert(0, 'K');
break;
default:
result.insert(0, digit);
}
amountValue-=digit;
amountValue/=14;
String firstValue = result1.toString();
}
}
char[] secNum = num2.toCharArray();
int amountValue2= 0;
int length = secNum.length;
for (int index = 0; index < length; index++){
int symbolValue;
switch (characters[index]) {
case 'A':
symbolValue = 10;
break;
case 'J':
symbolValue = 11;
break;
case 'Q':
symbolValue = 12;
break;
case 'K':
symbolValue= 13;
break;
default:
symbolValue = characters[index] - 48;
}
amountValue2+= symbolValue*Math.pow(14, length - index - 1);
}
StringBuilder result = new StringBuilder();
while(amountValue2> 0){
int digit = amountValue%14;
switch (digit) {
case 10:
result.insert(0, 'A');
break;
case 11:
result.insert(0, 'J');
break;
case 12:
result.insert(0, 'Q');
break;
case 13:
result.insert(0, 'K');
break;
default:
result.insert(0, digit);
}
amountValue2-=digit;
amountValue2/=14;
PokerNum secondValue = result.toString();
}
return firstValue + secondValue;
/*PokerNum sum = num1 +
PokerNum another.num2 =
return sum;*/
}
Thanks to anyone who helps in advance :)
I believe you can keep it in one instance. One suggestion is to use the conversion using the following functions:
Integer.parseInt(String s, int radix)
Integer.toString(int i, int radix)
The javadoc says that the string produced will use:
0123456789abcdefghijklmnopqrstuvwxyz
So, if we choose radix = 14, it will have 0123456789abcd.
The logic idea is to keep the actual number as int, and to convert at creation and at printout from and to String. We can just keep member variable num1 and remove the member variable alienNum and num2.
Constructor
Your constructor with String argument seems to do a good error checking. What we need here is just to convert from string to integer and store it in the member variable. First we need to convert all valid string from AJQK to ABCD. The example here is inefficient, but gets the idea across:
//alienNum = alienNum.replace('A', 'A'); // no need
alienNum = alienNum.replace('J', 'B');
alienNum = alienNum.replace('Q', 'C');
alienNum = alienNum.replace('K', 'D');
Then we can call the parsing method:
num1 = Integer.parseInt(alienNum , 14);
Your empty arg constructor is already fine by initializing the value of num1 to 0.
Adding
The method inside addition is not right because it is setting the current value to the addition. There are three objects working here: num, this, and another. You want to add this to another into num and return num.
num.num1 = this.num1 + another.num1;
Output
I'm assuming the output is going to be from toString(). In this case, you want to convert from integer to string, then convert it to the right character
String out = Integer.toString(num1, 14).toUpper();
//alienNum = alienNum.replace('A', 'A'); // no need
alienNum = alienNum.replace('B', 'J');
alienNum = alienNum.replace('C', 'Q');
alienNum = alienNum.replace('D', 'k');
You probably won't need a convert method now.
I'm trying to code a program that would convert an int to binaries. So far I have it print out the remainders, but it has to be printed in reverse for it to be a proper binary. I am not allowed to use any methods.
Here's my code.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter A Postive Number:");
int i = sc.nextInt();
int j = i; //backup
int k = 0; //remainder
while (j != 0) {
k = j % 2;
j /= 2;
String reversedStr = "";
switch (k) {
case 0:
reversedStr += "0";
break;
case 1:
reversedStr += "1";
break;
case 2:
reversedStr += "2";
break;
case 3:
reversedStr += "3";
break;
case 4:
reversedStr += "4";
break;
case 5:
reversedStr += "5";
break;
case 6:
reversedStr += "6";
break;
case 7:
reversedStr += "7";
break;
case 8:
reversedStr += "8";
break;
case 9:
reversedStr += "9";
break;
case 10:
reversedStr += "A";
break;
case 11:
reversedStr += "B";
break;
case 12:
reversedStr += "C";
break;
case 13:
reversedStr += "D";
break;
case 14:
reversedStr += "E";
break;
case 15:
reversedStr += "F";
break;
}
for (int l = reversedStr.length() - 1; l >= 0; l--) {
reversedStr.charAt(i);
System.out.print(reversedStr.charAt(l));
}
}
System.out.println("done");
}
}
this code gives me
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 178
at java.lang.String.charAt(String.java:658)
at radixHandmade.Handmade.main(Handmade.java:73)
The for loop at the bottom is the reversing part, but im not sure how to use charAt to complete the code. To be honest im very confused.
Any help would be greatly appreciated.
This statement causes the problem:
reversedStr.charAt(i);
Aside from causing an exception (because you're trying to get the (originally entered value)-th character in the string, which is by outside the bounds of the string, unless that value happens to be 0), it has no other side effect.
Just remove this line.
import java.util.Scanner;
public class Reverse {
public static void main(String[] args){
userInput();
}
public static void userInput(){
Scanner console = new Scanner(System.in);
String reverseString = console.nextLine(); //This is the word to be written backwards.
int s = reverseString.length()-1; //length of the word.
for (int i = s ; i>=0; i--){
System.out.print(reverseString.charAt(i));
}
}
}
Hope this helps.
Good luck.
removing the line reversedStr.charAt(i) will resolve the issue, but the program will still not convert to binary correctly. Your string still needs to be reversed. Might I suggest using the StringBuilder class:
import java.util.Scanner;
import java.lang.StringBuilder;
public class App {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder out = new StringBuilder();
System.out.println("Enter A Postive Number:");
int i = sc.nextInt();
int r = 0;
int b = 2; // now you can just change this for what base (binary, hex, ...)
while (i != 0) {
r = i % b;
i /= b;
switch (r) {
case 0:
out.append("0");
break;
case 1:
out.append("1");
break;
}
}
System.out.println(out.reverse());
}
}
Your code would work fine if you move the reversing for loop out of the while loop:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String revStr = "";
System.out.println("Enter A Postive Number:");
int i = sc.nextInt();
int r = 0;
int b = 2; // now you can just change this for what base (binary, hex, ...)
while (i != 0) {
r = i % b;
i /= b;
switch (r) {
case 0:
revStr += "0";
break;
case 1:
revStr += "1";
break;
// ... for hex
}
}
for (int j = revStr.length() - 1; j >= 0; j--) {
System.out.print(revStr.charAt(j));
}
System.out.print("\n");
}
But what I really don't understand is why you even have to reverse the string if you can just do:
reversedStr = "0" + reversedStr; // of course it will no longer be reversed
// ... for all the cases
Even better if you stick with just binary, you could skip the whole switch and do
public static void main(String[] args) {
String str = "";
System.out.println("Enter A Postive Number:");
for(int i = new Scanner(System.in).nextInt(); i != 0; i /= 2)
str = String.valueOf(i % 2) + str;
System.out.println(str);
}
I am trying to create a program that takes input from the user using the command line of 3 octal number, for example 5, 2, 6 or 5,2,6 and convert them into 3 sets of 3 digit binary numbers, like 101 010 110, and also print out those corresponding CHMOD permissions like r-x -w- rw-.
I am having a lot of trouble splicing these numbers apart with substring into 3 separate numbers of 5 2 and 6.
I also need the program to convert from the set of binary digits into 3 numerical digits and permissions. And from the permissions into digits and binary.
Here is what I have so far:
import java.util.Scanner;
class Test {
public static void main(String cheese[]){
Scanner scan = new Scanner(System.in);
String line1 = scan.nextLine();
//String line2 = scan.nextLine();
//String line3 = scan.nextLine();
//String line4 = scan.nextLine();
//String line5 = scan.nextLine();
System.out.println(line12(line1));
}
public static String line12(String line){
String ownerPermissions = "";
String groupPermissions = "";
String otherPermissions = "";
int comma = 0;
int lineLength = line.length();
if (line.indexOf(" ") != -1){
comma = line.indexOf(",");
}else{
comma = 1;
}
String firstNumber = line.substring(0, 1);
line = line.substring(comma + 1, lineLength);
int comma2 = line.indexOf(",");
String secondNumber = line.substring(comma + 1, comma2);
String thirdNumber = line.substring(lineLength);
int firstInt= Integer.parseInt(firstNumber);
int secondInt = Integer.parseInt(secondNumber);
int thirdInt = Integer.parseInt(thirdNumber);
String firstBinary = Integer.toBinaryString(firstInt);
String secondBinary = Integer.toBinaryString(secondInt);
String thirdBinary = Integer.toBinaryString(thirdInt);
switch(firstInt){
case 0:
ownerPermissions = "---";
break;
case 1:
ownerPermissions = "--x";
break;
case 2:
ownerPermissions = "-w-";
break;
case 3:
ownerPermissions = "-wx";
break;
case 4:
ownerPermissions = "r--";
break;
case 5:
ownerPermissions = "r-x";
break;
case 6:
ownerPermissions = "rw-";
break;
case 7:
ownerPermissions = "rwx";
break;
}
switch(secondInt){
case 0:
groupPermissions = "---";
break;
case 1:
groupPermissions = "--x";
break;
case 2:
groupPermissions = "-w-";
break;
case 3:
groupPermissions = "-wx";
break;
case 4:
groupPermissions = "r--";
break;
case 5:
groupPermissions = "r-x";
break;
case 6:
groupPermissions = "rw-";
break;
case 7:
groupPermissions = "rwx";
break;
}
switch(thirdInt){
case 0:
otherPermissions = "---";
break;
case 1:
otherPermissions = "--x";
break;
case 2:
otherPermissions = "-w-";
break;
case 3:
otherPermissions = "-wx";
break;
case 4:
otherPermissions = "r--";
break;
case 5:
otherPermissions = "r-x";
break;
case 6:
otherPermissions = "rw-";
break;
case 7:
otherPermissions = "rwx";
break;
}
String output = firstBinary + " " + secondBinary + " " + thirdBinary + " and " + ownerPermissions + " " + groupPermissions + " " + otherPermissions;
return output;
}
}
You will find it easier if you make your code much simpler. I suggest something like
public static void main(String[] args) {
System.out.println(line12("5, 2, 6"));
}
public static String line12(String line) {
String[] nums = line.trim().split(" *, *");
StringBuilder sb = new StringBuilder();
for (String s : nums) {
if (sb.length() > 0) sb.append(" ");
int num = Integer.parseInt(s);
sb.append((num & 4) == 0 ? '-' : 'r');
sb.append((num & 2) == 0 ? '-' : 'w');
sb.append((num & 1) == 0 ? '-' : 'x');
}
return sb.toString();
}
prints
r-x -w- rw-
Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}