Logical error with the statement 'sc.nextLine();' - string

When I run this part of my program, it fails to recognize the two input statements using 'sc.nextLine();', but it accepts an entry for 'sc.next();'. Does anyone have any suggestions?
String information()
{
int l;char at;String nam,id,number;long contact;
System.out.println("\nPlease enter your name");
nam=sc.nextLine();
do
{
System.out.println("\nPlease enter your contact number");
contact=sc.nextLong();
number=Long.toString(contact);
l=number.length();
if(l<5||l>8&&l!=10)
error();
}
while(l<5||l>8&&l!=10);
System.out.println("\nPlease enter your e-mail id");
id=sc.nextLine();
int len=id.length();
for(int k=0;k<len;k++)
{
at=id.charAt(k);
if(Character.isWhitespace(at))
{
error();
break;
}
}
return nam;
}

Try sc.nextLine above the
nam = sc.nextLine();
It takes nextLine into an empty line so you need to clear the buffer first.

Related

Looking for a simple way for scanner to detect an empty entry ie. just an enter key

I am learning Java and using the scanner to detect and use int values. Everything works fine except that when I press enter without typing in any value I want the app to tell me that it is an invalid entry. Any help greatly appreciated.
My code is below.
int days = 0; // variable to store number of days
boolean isValidDay = false; // detects if the input is a valid number
// create a new scanner
// with the value from the console
Scanner input = new Scanner(System.in);
do
{
try
{
// Print question
System.out.print("Enter the number of days to record rainfall: ");
days = input.nextInt(); // Is it a valid Integer?
if (days <= 0)
{
System.out.println("The input is invalid. Please enter again!");
}
else
{
isValidDay = true;
}
}
catch (InputMismatchException e) // invalid Integer
{
System.out.println("The input is invalid. Please enter again!");
input.nextLine();
}
} while (!isValidDay); // keep repeating till we get a valid number for a day

Microsoft Bot Framework won't send multiline messages

So I've built this bot that should respond to it's user with status messages. I want to make these messages rather clean and therefore wanted to start each new property with a new line. Only problem is that when I do this, the bot just prints the first few lines.
So this is the code I've got, I've made sure that the data is actually there.
internal static string DeviceInformation(Device device)
{
StringBuilder sb = new StringBuilder();
sb.Append($"[Name]: {device.Name}\n\n");
sb.Append($"[Location]: {device.LocationName} \n\n");
if (device.ContactLost)
{
sb.Append("[Status]:Offline!\n\n");
sb.Append($"[Time Offline]: {device.ContactLostTime} \n\n");
sb.Append($"[Time Offline]: {device.ContactLostTime} \n\n");
}
else
{
sb.Append("[Status]:online! \n\n");
}
return sb.ToString();
}
internal static string DeviceInformation(Device device, DeviceHistory statistic)
{
StringBuilder sb = new StringBuilder(DeviceInformation(device));
sb.Append($"[Time]: {statistic.CreatedTimeStamp} \n\n");
sb.Append($"[Signal]: {statistic.SignalStrength} \n\n");
sb.Append($"[Battery]: {statistic.BatteryLevel} \n\n");
Debug.WriteLine("TOSTRING " + sb.ToString());
return sb.ToString();
}
The next last line prints out this:
TOSTRING [Name]: Restroom 1
[Location]: Floor 2
[Status]:online!
[Time]: 16/05/2017 22:23:45
[Signal]: -88
[Battery]: 60
Now the bot just prints:
[Name]: Restroom 1
[Location]: Floor 2
[Time]: 16/05/2017 22:23:45
If I remove all the linebreaks \n and put everything on the same row, the bot prints the whole message.
Anyone having any idea what I can do about this?
Interesting behavior. I was able to reproduce it... I'm still looking for the root cause of the issue, however, I found a workaround for you, that is using bullets.
I updated your code in the following way:
internal static string DeviceInformation(Device device)
{
StringBuilder sb = new StringBuilder();
sb.Append($"• [Name]: {device.Name}\n\n");
sb.Append($"• [Location]: {device.LocationName}\n\n");
if (device.ContactLost)
{
sb.Append("[Status]:Offline!\n\n");
sb.Append($"[Time Offline]: {device.ContactLostTime}\n\n");
sb.Append($"[Time Offline]: {device.ContactLostTime}\n\n");
}
else
{
sb.Append("• [Status]:online!\n\n");
}
return sb.ToString();
}
internal static string DeviceInformation(Device device, DeviceHistory statistic)
{
StringBuilder sb = new StringBuilder(DeviceInformation(device));
sb.Append($"• [Time]: {statistic.CreatedTimeStamp}\n\n");
sb.Append($"• [Signal]: {statistic.SignalStrength}\n\n");
sb.Append($"• [Battery]: {statistic.BatteryLevel}\n\n");
Debug.WriteLine("TOSTRING " + sb.ToString());
return sb.ToString();
}
With that, it's working as expected in the emulator:

Error: NoSuchElementException

This program accesses a text file with text elements separated by commas. The elements register in the variables I created. Except for the last one. The error then occurs. The program works fine with the default whitespace delimitor for the scanner class (the text file is adjusted accodingly) but fails when I use a comma as the delimitor. Could someone please supply some insight.
Text Data:
smith,john,10
stiles,pat,12
mason,emrick,12
Code:
public void openFile(String f)
{
try{
x = new Scanner(new File(f));
x.useDelimiter(",");
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNext())
{
String lName = x.next().trim();
**String fName = x.next().trim();**
String grade = x.next().trim();
if(fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}
The problem relies on the fact that you called x.useDelimiter(","); on your Scanner in function openFile().
Since your text data is:
smith,john,10
stiles,pat,12
mason,emrick,12
the Scanner sees it as:
"smith,john,10\nstiles,pat,12\nmason,emrick,12"
So what happens when you execute your code is:
1: x.hasNext() ? Yes
x.next().trim() => "smith"
x.next().trim() => "john"
x.next().trim() => "10\nstiles"
2: x.hasNext() ? Yes
x.next().trim() => "pat"
x.next().trim() => "12\nmason"
x.next().trim() => "emrick"
3: x.hasNext() ? Yes
x.next().trim() => "12"
x.next().trim() => Error!
To fix this you can either edit the file and change all the \n with ,, or use a first Scanner to get all the lines, and another one to get the tokens, as shown here:
public void openFile(String f)
{
try{
x = new Scanner(new File(f)); // Leave default delimiter
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNextLine()) // For each line in your file
{
Scanner tk = new Scanner(x.nextLine()).useDelimiter(","); // Scan the current line
String lName = x.next().trim();
String fName = x.next().trim();
String grade = x.next().trim();
if (fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}

C# Visual Studio's Text to Answer

This is kinda of a Noobie what about I am gonna ask but I am trying to get my Program to work I do not know how to Ask a question in a text box hit the button and it outputs the answer; I Have been researching this for a while I know how to get everything else to work.
So a simple Console app example:
static void Main()
{
bool exit = false;
string response;
while (!exit)
{
Console.Write("Command ('Exit' to end): ");
response = Console.ReadLine();
switch (response)
{
case "Hey":
Console.WriteLine("Welcome");
break;
case "unicorns":
Console.WriteLine("...are awesome!");
break;
case "Exit":
exit = true;
break;
default:
Console.WriteLine("Unrecognized command!");
break;
}
}
Console.Write("Press Enter to Quit");
Console.ReadLine();
}

How to get the integer value in TextBox?

I have one Text Box in windows application. This Text Box only allowed the integer value not string. Can anybody have solution ?
Convert it.
public int GetIntValue(TextBox tb)
{
try
{
return Convert.toInt32(tb.Text);
}
catch (Exception ex)
{
//This is called if the converting failed for some reason
}
return 0; //This should only return 0 if the textbox does not contain a valid integer value
}
Use it like this:
int number = GetIntValue(textBox1);
Hope this helps!
Use this.
int value = Convert.ToInt32(textBox1.Text);
You use this code and get your integer value.Thanks
I found a solution from C# How do I make a textbox that only accepts numbers
Hope it will help you.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}

Resources