import java.util.Scanner;
public class DJNameCreator {
public static void main(String[] args){
//Variables to store inputted names
String firstName;
String lastName;
//Scanner for user inputted names
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter your first name: ");
firstName = keyboard.nextLine();
System.out.println("Nice to meet you, "+firstName+"!");
System.out.println("Please enter your last name: ");
lastName = keyboard.nextLine();
//Use substring and length method to get total length of string
//First name section
int firstLength = firstName.length();
if (firstLength%2 == 0){
String firstHalf = firstName.substring(0, firstLength/2);
}
//Last name section
int lastLength = lastName.length();
if (lastLength%2 == 0){
String lastHalf = lastName.substring((lastLength/2), lastLength);
}
if (lastLength%2 == 1){
String lastHalf = lastName.substring((lastLength/2), (lastLength)-1);
}
//Output the DJ name using println combined with the word "Jayster"
System.out.println(firstHalf + "Jayster" + lastHalf);
}
}
I can't figure out why java cannot find symbol. My code compiles fine until the last println. It's pointing at firstHalf and lastHalf specifically. I have them defined in the if statement, but it won't compile.
Is it because if statements are kind of isolated from the main code?
In the snippet above the firstHalf and secondHalf have scope only in their respective If blocks. Where as you are trying to print it in the method scope of Main.
You can find more info about scopes here.
Check the refactored code below.
import java.util.Scanner;
public class DJNameCreator {
public static void main(String[] args){
String firstName;
String lastName;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter your first name: ");
firstName = keyboard.nextLine();
System.out.println("Nice to meet you, "+firstName+"!");
System.out.println("Please enter your last name: ");
lastName = keyboard.nextLine();
int firstLength = firstName.length();
// FirstHalf is in the scope of main method.
String firstHalf = "";
if (firstLength%2 == 0){
firstHalf= firstName.substring(0, firstLength/2);
}
int lastLength = lastName.length();
// LastHalf is in the scope of main method.
String lastHalf ="";
if (lastLength%2 == 0){
lastHalf = lastName.substring((lastLength/2), lastLength);
}
if (lastLength%2 == 1){
lastHalf = lastName.substring((lastLength/2), (lastLength)-1);
}
//Output the DJ name using println combined with the word "Jayster"
System.out.println(firstHalf + "Jayster" + lastHalf);
}
}
Related
I have to design a program that gets 3 user-inputs in the form:
Name1 (any number of spaces) age1
Name2 (any number of spaces) age3
Name3 (any number of spaces) age3
Then print line which has the highest age (suppose Name3 age3 had the highest age I'd print his line).
My Code:
import java.util.*;
public class RankAge{
public static void main(String[] args){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n1 = sc.nextLine();
String n2 = sc.nextLine();
String n3 = sc.nextLine();
}
}
I know how to scan the user-inputs, but i don't know how to do a comparison of the number within the acquired string to print a specific one (also since there can be any number of spaces it seems even more complicated to me).
You can use split to get the person's age:
String age = "Jon 57".split("\\s+")[1]; // contains "57"
You can then use Integer.parseInt(age) to get the person's age, as a number.
If you need to allow the user to input a name with spaces, you can adjust the number in square brackets ([]). For example, [2] would require the user to input a first name and last name.
Managed to do it with frenchDolphin's suggestion. This is the code i used (it's quite beginner friendly):
import java.util.*;
public class RankAge{
public static void main(String[] args){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n1 = sc.nextLine();
String a1 = n1.split("\\s+")[1];
String n2 = sc.nextLine();
String a2 = n2.split("\\s+")[1];
String n3 = sc.nextLine();
String a3 = n3.split("\\s+")[1];
if(Integer.parseInt(a1) > Integer.parseInt(a2)){
} if(Integer.parseInt(a1) > Integer.parseInt(a3)){
System.out.println(n1);
}else if(Integer.parseInt(a2) > Integer.parseInt(a3)){
System.out.println(n2);
}else{
System.out.println(n3);
}
}
}
+1 because at first look it seemed very simple but when I started implementing the complexities started showing up. Here is the complete solution for your problem,
import java.util.*;
public class RankAge {
public static void main(String s[]){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n[] = new String[3];
for(int i=0;i<3;i++){
n[i] = sc.nextLine();
}
int age[] = new int[3];
age[0] = Integer.parseInt(n[0].split("\\s+")[1]);
age[1] = Integer.parseInt(n[1].split("\\s+")[1]);
age[2] = Integer.parseInt(n[2].split("\\s+")[1]);
int ageTemp[] = age;
for(int i=0;i<age.length;i++){
for(int j=i+1;j<age.length;j++){
int tempAge = 0;
String tempN = "";
if(age[i]<ageTemp[j]){
tempAge = age[i];
tempN = n[i];
age[i] = age[j];
n[i] = n[j];
age[j] = tempAge;
n[j] = tempN;
}
}
}
for(int i=0;i<3;i++){
System.out.println(n[i]);
}
}
}
How can I get the program to ask for input using the scanner after the if statement?
import java.util.Scanner;
public class App1 {
public static void main(String[] Args) {
Scanner keyboard = new Scanner(System.in);
String gender;
String fName;
String lName;
int age;
String female = "F";
String male = "M";
String a = "";
String gettingMarried = "y";
String notGettingMarried = "n";
System.out.println("What is your gender (M or F)");
gender = keyboard.nextLine();
System.out.println("What is your first name?");
fName = keyboard.nextLine();
System.out.println("What is your last name?");
lName = keyboard.nextLine();
System.out.println("Age:");
age = keyboard.nextInt();
System.out.println();
if (gender.equals(female) && age >= 20) {
System.out.println("Are you married " + fName + " (y or n?)");
a = keyboard.nextLine();
} else if (gender.equals(male) && age >= 20) {
System.out.println("Are you married" + fName + "(y or n?)");
a = keyboard.nextLine();
}
}
}
It is because you use a nextInt() that only takes the int value and not the full line. When you try again to read with keyboard.nextLine() what you are catching it's the rest of the sentence of the line in which you put the int.
Change the System.out.println(); before your if statement to keyboard.nextLine();
Edit: If you want a more extended explanation about why you have to put keyboard.nextLine(); after your keyboard.nextInt() you can consult my answer in another question with the same problem: Why isn't the scanner input working?
I expect it will be helpful for you!
This is what I have so far. I want the program to print out the words the user inputs as a sentence. But
I don't know how I get that to happen with the code I have written so far.
ex: if you entered
Hello
World
done
The program should say: "Hello World"
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+word);
}
}
What you need it to store it in a variable which is declared outside the loop.
StringBuilder sentence=new StringBuilder();
do {
word = in.nextLine();
count++;
System.out.print(" "+word);
sentence.append(" "+word);
}
while (!word.equals(SENTINEL));
Then for printing use
System.out.println(sentence.toString());
You will need to create an additional string to "collect" all of the words that the user enters. The problem with your original is that you replace 'word' with the word entered. This should do the trick:
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
String sentence = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
sentence += " " + word;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+sentence);
}
}
You can read it by pieces and put them together using a StringBuffer - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
StringBuffer sb = new StringBuffer();
do {
sb.append( in.next() );
count++;
}
while (!word.equals(SENTINEL));
As the title says, I would like to scan the whole line of input just using one input from user. The input should be like "Eric 22 1".
If nextString() shouldn't be used that way, should I just use hasNext?
JAVA CODE :
import java.util.Scanner;
public class tugas1
{
public static void main(String []args)
{
String name;
int age;
boolean sex;
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
name = sc.nextString();
age = sc.nextInt();
sex = sc.nextBoolean();
if(isString(name))
{
if(isInteger(age))
{
if(isBoolean(sex))
{
System.out.println("Correct format. You are :" +name);
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the name in string");
}
}
}
After adding and editing the lines :
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String name = inputAfterSplit[0];
int age = Integer.parseInt(inputAfterSplit[1]);
boolean sex = Boolean.parseBoolean(inputAfterSplit[2]);
I would like to add if(name instanceof String). I haven't touched Java since a long time and I forgot is that the way of using instanceof, or is that wrong?
The point is I want to compare if the input var is in int or string or bool.
if(name instanceof String)
{
if(age instanceof Integer)
{
if(sex instanceof Boolean)
{
System.out.println("All checked out")
}
else
{
System.out.println("Not boolean")
}
else
{
System.out.println("Not int")
}
System.out.println("Not string")
}
Will these lines work?
Please input your name, age, and sex
As you need to insert values in specific sequence.
Use nextLine() and perform split
For Example:"Abc 123 true 12.5 M"
String s[]=line.split(" ");
And you will have
s[0]="Abc"
s[1]="123"
s[2]="true"
s[3]="12.5"
s[4]="M"
Than parse them to required type.
String first=s[0];
int second=Integer.parseInt(s[1].trim());
boolean third=Boolean.parseBoolean(s[2].trim());
double forth=Double.parseDouble(s[3].trim());
char fifth=s[4].charAt(0);
As your code suggest and as David said you can change just this
name = sc.next();//will read next token
age = sc.nextInt();
sex = (sc.next()).charAt(0);//change sex to character for M and F
//or //sex = sc.nextInt();//change it to int
first thing when we use scanner , we dont have a method called nextString()
so instead we must use next() which is to read string.
secondly when you want to read whole line then use nextLine() which will read entire line in the form of text and put it in a string.
now the String which is read as entire line can be split based on split character(assume it is space in our case)
then get the string array and parse each element to required type.
better if we use try/catch while parsing so that we can catch exception for unwanted format for the input and throw it to user.
sample code without try/catch but you use try/catch as per your need
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String firstParam = inputAfterSplit[0];
int secondParam=Integer.parseInt(inputAfterSplit[1]);
boolean thirdParam=Boolean.parseBoolean(inputAfterSplit[2]);
Reworked it all, this is the remake of the code just in case people are having same problem as mine..
int in the delcaration should be changed into Integer
import java.util.Scanner;
import java.lang.*;
public class tugas1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input number of line :");
int lineNum = sc.nextInt();
String[] name = new String[lineNum];
Integer[] age = new Integer[lineNum];
String[] gender = new String[lineNum];
System.out.println("Please input your name, age, and gender(Male/Female) \n(Separate each line by an enter) :");
for ( int i = 0; i < lineNum; i++)
{
System.out.print("Line " + (i+1) + " : ");
name[i] = sc.next();
age[i] = sc.nextInt();
gender[i] = sc.next();
}
for ( int j = 0; j < lineNum; j++ )
{
if (name[j] instanceof String)
{
if (age[j] instanceof Integer)
{
if (gender[j] instanceof String)
{
System.out.println("Person #" + (j+1) + " is " + name[j] + ", with age of " + age[j] + " years old, and gender " + gender[j]);
}
else
{
System.out.println("Gender is missing");
}
}
else
{
System.out.println("Age and Gender are");
}
}
else
{
System.out.println("Name, Age and Gender are missing");
}
}
}
}
Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}