0

I'm extremely new to programming and decided to create a program that translates ascii strings into binary strings and binary strings into ascii strings. The problem that I am having is that whilst the program compiles successfully it doesn't allow me to input the string to be translated after choosing whether to translate to or from binary.

import java.util.Scanner;

public class Translator
{  
    public static void main(String[] args)
    {
        int valueoftype; 
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 1 if converting to binary. Enter 0 if converting from binary.");
        valueoftype = in.nextInt();
        System.out.println("What is your input?");
        String input = in.nextLine();
        if(valueoftype == 1)
        { 

            byte[] bytes = input.getBytes();
            StringBuilder binary = new StringBuilder();
            for (byte b : bytes)
            {
                int val = b;
                for (int i = 0; i < 8; i++)
                {
                    binary.append((val & 128) == 0 ? 0 : 1);
                    val <<= 1;
                }
                binary.append(' ');
        }
            System.out.println(input + " in binary is " + binary);
        }
        else if(valueoftype == 0)
        {
            StringBuilder result = new StringBuilder();
            for (int i = 0;i < input.length();i += 8) 
            {
                result.append((char) Integer.parseInt(input.substring(i, i + 8), 2));
            }
            System.out.println(input + "in ascii is"+ result); 
        } 
        else
        {
            System.out.println("Error cannot procede with incorrect value.");
            System.out.println("Enter 1 if converting to binary. Enter 0 if converting from binary.");
            valueoftype = in.nextInt();
    }
  }
}

I've been scratching my head for the past couple hours trying to figure out exactly what in the world is wrong with my code, hope I can get an explanation from someone.

Mxy
  • 3
  • 3
  • 1
    Likely a duplicate. `nextInt()` does not consume the newline character. Place `in.nextLine()` after your `nextInt()`. – user3437460 Jun 02 '16 at 08:02

3 Answers3

0

Instead of using String input = in.nextLine(); use only String input = in.next(); and you will be able to input your desired String.

See this to understand the difference

Community
  • 1
  • 1
Kaushal28
  • 4,823
  • 4
  • 30
  • 57
0

You could add

    System.out.println("What is your input?");
    String input = in.next(); // Don't skip rest of the line
    if (valueoftype == 1) {
Viktor Mellgren
  • 3,944
  • 3
  • 36
  • 68
0

The problem is with nextInt(). Try the following code:

valueoftype = Integer.parseInt(in.nextLine());
System.out.println("What is your input?");
String input = in.nextLine();

You can also read this post for more info: Using scanner.nextLine()

Community
  • 1
  • 1
Bouramas
  • 678
  • 1
  • 15
  • 26