Printing mistake with System.print - printing

I'm trying to print each one a seperate line. for example it should come out like this.
Name:
Phone:
Car:
Type of Work:
But for some reason it comes out like this
Name:
Phone: Car:
Here's the code:
System.out.print(" Name:");
String name = input.next();
System.out.print(" Phone:");
String phone = input.next();
System.out.print(" Car:");
String car = input.next();
System.out.print(" Type of work:");
String work = input.next();
}
}
I tried changing the System.out.println but it wont let you type the input on the same line, it automatically bumps you down to the next line

Emulating a println but after the input should work.
public class MyClass {
public static void main(String args[]) {
System.out.println(" Name:");
String work = input.next();
System.out.print("\n");
System.out.println(" Phone:");
String work = input.next();
System.out.print("\n");
System.out.println(" Car:");
String work = input.next();
System.out.print("\n");
System.out.println(" Type of work:");
}
}

Related

How to get the variable real type using JavaSymbolSolver

The code is here,
class Bar {
private int a;
void aMethod() {
while (true) {
String a = "0";
a = a + "1";
}
}
}
I want to get the real type of a. I tried to use the code below,
public class GetTypeOfReference {
private static final String FILE_PATH = "src\\com\\test\\Bar.java";
public static void main(String[] args) throws FileNotFoundException {
TypeSolver typeSolver = new CombinedTypeSolver();
JavaSymbolSolver symbolSolver = new JavaSymbolSolver(typeSolver);
StaticJavaParser.getConfiguration().setSymbolResolver(symbolSolver);
CompilationUnit cu = StaticJavaParser.parse(new File(FILE_PATH));
cu.findAll(AssignExpr.class).forEach(ae -> {
ResolvedType resolvedType = ae.calculateResolvedType();
System.out.println(ae.toString() + " is a: " + resolvedType.describe());
});
}
}
But got the error,
Exception in thread "main" UnsolvedSymbolException{context='null', name='String', cause='null'}
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.convertToUsage(JavaParserFacade.java:509)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.convert(JavaParserFacade.java:567)
at com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserSymbolDeclaration.getType(JavaParserSymbolDeclaration.java:146)
at com.github.javaparser.symbolsolver.model.resolution.Value.from(Value.java:40)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
at java.base/java.util.LinkedList$LLSpliterator.tryAdvance(LinkedList.java:1253)
at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:127)
at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:502)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:488)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:476)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.AbstractJavaParserContext.solveWithAsValue(AbstractJavaParserContext.java:149)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.StatementContext.solveSymbolAsValue(StatementContext.java:135)
at com.github.javaparser.symbolsolver.resolution.SymbolSolver.solveSymbolAsValue(SymbolSolver.java:68)
at com.github.javaparser.symbolsolver.resolution.SymbolSolver.solveSymbolAsValue(SymbolSolver.java:73)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:277)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:44)
at com.github.javaparser.ast.expr.NameExpr.accept(NameExpr.java:79)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:98)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:44)
at com.github.javaparser.ast.expr.AssignExpr.accept(AssignExpr.java:135)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getTypeConcrete(JavaParserFacade.java:448)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:310)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:292)
at com.github.javaparser.symbolsolver.JavaSymbolSolver.calculateType(JavaSymbolSolver.java:250)
at com.github.javaparser.ast.expr.Expression.calculateResolvedType(Expression.java:564)
at test.GetTypeOfReference.lambda$0(GetTypeOfReference.java:32)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1378)
at test.GetTypeOfReference.main(GetTypeOfReference.java:31)
What is the right way to do this?
The answer is late but for those who are interested this is the right approach.
With javaparser 3.16.1 the result is
a = a + "1" is a: java.lang.String

Boolean method not retuning correct value

Ok so I think I'm being a noob because it's a new semester but the method "palindromeTest" always return's false even though the string is equal and the number is a palindrome. (A palindrome example is: (565) 677-6565) (also don't give me the answer outright I want to solve it on my own)
public class IjazZ_PhoneStringPalindrome
{
public static void main(String[] args) throws IOException
{
String phoneNumber;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a phone number in this format (###) ###-####: ");
phoneNumber = br.readLine();
phoneNumber = justNumbers(phoneNumber);
if (palindromeTest(phoneNumber))
{
System.out.println("This phone number is a palindrome!");
}
else
{
System.out.println("This phone number is not a palindrome!");
}
}
public static String justNumbers(String phoneNumber)
{
StringTokenizer st = new StringTokenizer(phoneNumber, " ()-");
StringBuffer number = new StringBuffer();
while(st.hasMoreTokens())
{
number.append(st.nextToken());
}
phoneNumber = number.toString();
return phoneNumber;
}
public static boolean palindromeTest(String pNumber)
{
StringBuffer reversedNumber = new StringBuffer(pNumber);
reversedNumber.reverse().toString();
if(pNumber.equals(reversedNumber))
{
return true;
}
else
{
return false;
}
}
}
You don't assign the value returned by reversedNumber.reverse().toString()to reversedNumber.
Do
String reversedNumberString = reversedNumber.reverse().toString();
And by the way, you can just return
return pNumber.equals(reversedNumber); - the if/else statement is unnecessary.

How to set my computerId into primary key?

Here's my code in domain. I wanted to set my computerId into a primary key. But still display on my table(index). Thanks
package com.data
class ComputerInformation {
String computerId;
String computerName;
String status;
String location;
String serial;
String monitorSerial;
String keyboardSerial;
String mouseSerial;
String cpuSerial;
String avrSerial;
String harddiskSerial;
static constraints = {
computerId(unique:true)
computerName(blank:false)
status(blank:false)
location(blank:false)
serial(blank:false)
monitorSerial(blank:false)
keyboardSerial(blank:false)
mouseSerial(blank:false)
cpuSerial(blank:false)
avrSerial(blank:false)
harddiskSerial(blank:false)
}
}
use like this,
static mapping = {
id name: 'computerId'
}
Maybe instead of changing PK, return id as a computerId variable?
package com.data
class ComputerInformation {
String computerName;
String status;
String location;
String serial;
String monitorSerial;
String keyboardSerial;
String mouseSerial;
String cpuSerial;
String avrSerial;
String harddiskSerial;
static constraints = {
computerName(blank:false)
status(blank:false)
location(blank:false)
serial(blank:false)
monitorSerial(blank:false)
keyboardSerial(blank:false)
mouseSerial(blank:false)
cpuSerial(blank:false)
avrSerial(blank:false)
harddiskSerial(blank:false)
}
def getComputerId(){
return id
}
}
Moreover if you need computerId as a String, you can change getComputerId function to:
String getComputerId(){
return id.toString()
}

Join two Base64 strings and then decode them

I'm trying to figure out how to join two strings that are encoded Base64 and then decode and get the combined result.
Example:
string1 Hello --- string1 Base64 SGVsbG8=
string2 World --- string2 Base64 V29ybGQ=
If I join the base64 I get something that wont decode SGVsbG8=V29ybGQ=
I want the result to say: Hello World
I don't want only this example to work but rather something that will work with any string.
This is a very simplified problem which is a step on an application I'm trying to write I'm stuck on.
What if you encode both strings to array, then combine those arrays and finally GetString from the bytes?
using System;
using System.Text;
using System.Linq;
public class Program
{
public static void Main()
{
var base1 = "SGVsbG8=";
var base2 = "V29ybGQ=";
var array1 = Convert.FromBase64String(base1);
var array2 = Convert.FromBase64String(base2);
var comb = Combine(array1, array2);
var data = Encoding.Default.GetString(comb);
Console.WriteLine(data);
}
private static byte[] Combine(byte[] first, byte[] second)
{
return first.Concat(second).ToArray();
}
}
I found a best way to do this, add plus between one string and other, and add ONE, and only ONE equals char ('=') at the end of string. The return will be "Hello>World", then remove the ">":
class Program
{
static void Main(string[] args)
{
string base64String = "SGVsbG8+V29ybGQ=";
byte[] encodedByte = Convert.FromBase64String(base64String);
var finalString = Encoding.Default.GetString(encodedByte)).Replace(">", " ");
Console.WriteLine(finalString.ToString());
}
}
(Old way) In C# I do something like this:
class Program
{
static void Main(string[] args)
{
string base64String = "SGVsbG8=V29ybGQ=";
Console.WriteLine(DecodeBase64String(base64String));
Console.ReadLine();
}
public static string DecodeBase64String(string base64String)
{
StringBuilder finalString = new StringBuilder();
foreach (var text in base64String.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
{
byte[] encodedByte = Convert.FromBase64String(text + "=");
finalString.Append(Encoding.Default.GetString(encodedByte));
finalString.Append(" "); //This line exists only to attend the "Hello World" case. The correct is remove this and let the one that will receive the return to decide what will do with returned string.
}
return finalString.ToString();
}
}

Reading a file with a read method using Scanner (InputMismatchException)

I'm new to java and I have a problem with reading a file using the scanner class.
My objective is to read the following .txt file:
3
Emmalaan 23
3051JC Rotterdam
7 rooms
price 300000
Javastraat 88
4078KB Eindhoven
3 rooms
price 50000
Javastraat 93
4078KB Eindhoven
4 rooms
price 55000
The "3" on top of the file should be read as an integer that tells how many houses the file has. The following four lines after the "3" determine one house.
I try to read this file using a read method in the class portefeuille:
public static Portefeuille read(String infile)
{
Portefeuille returnvalue = new Portefeuille();
try
{
Scanner scan = new Scanner(new File(infile)).useDelimiter(" |/n");
int aantalwoningen = scan.nextInt();
for(int i = 0; i<aantalwoningen; ++i)
{
Woning.read(scan);
}
}
catch (FileNotFoundException e)
{
System.out.println("File could not be found");
}
catch (IOException e)
{
System.out.println("Exception while reading the file");
}
return returnvalue;
}
The read method in the Woning class looks like this:
public static Woning read(Scanner sc)
{
String token_adres = sc.next();
String token_dr = sc.next();
String token_postcd = sc.next();
String token_plaats = sc.next();
int token_vraagPrijs = sc.nextInt();
String token_kamerstxt = sc.next();
String token_prijstxt = sc.next();
int token_kamers = sc.nextInt();
return new Woning(adresp, token_vraagPrijs, token_kamers);
}
When I try to execute the following code:
Portefeuille port1 = Portefeuille.read("woningen.txt");
I get the following error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Portefeuille.read(Portefeuille.java:48)
at Portefeuille.main(Portefeuille.java:112)
However if I use the read method from the Woning class to read one adres in a string format:
Emmalaan 23
3051JC Rotterdam
7 Rooms
price 300000
It works fine.
I tried to change the .txt file into only one address without the "3" on top so that it is exactly formatted like the address that should work. But when I call the read method from Woning class it still gives me the error.
Could anyone please help me with this?
Thank you!
I was also facing a similar issue, so I put my answer so that it could help in future:
There are two possible modifications which I did to make this code run.
First option: Change the use of useDelimiter method to .useDelimiter("\\r\\n") when creating the Scanner class, I was in windows so we might need \\r for Windows compatibility.
Using this modification, there will be no exception.But the code will again fail at int token_vraagPrijs = sc.nextInt();.
Because in the public static Woning read(Scanner sc), you are suing sc.next();.Actually this method finds and returns the next complete token from this scanner.A complete token is preceded and followed by input that matches the delimiter pattern.
So, every sc.next() is actually reading a line not a token.
So as per your code sc.nextInt() is trying to read something like Javastraat 88.So again it will give you the same exception.
Second option (Preferred):Don't use any delimiter, Scanner class will default whitespace and your code will work fine.I modified your code and It worked fine for me.
Code:
public class Test3{
public static void main(String... s)
{
read("test.txt");
}
public static void read(String infile)
{
try (Scanner scan = new Scanner(new File(infile)))
{
int aantalwoningen = scan.nextInt();
System.out.println(aantalwoningen);
for (int i = 0; i < aantalwoningen; ++i)
{
read(scan);
}
}
catch (FileNotFoundException e)
{
System.out.println("File could not be found");
}
}
public static void read(Scanner sc)
{
String token_adres = sc.next();
String token_dr = sc.next();
String token_postcd = sc.next();
String token_plaats = sc.next();
int token_vraagPrijs = sc.nextInt();
String token_kamerstxt = sc.next();
String token_prijstxt = sc.next();
int token_kamers = sc.nextInt();
System.out.println(token_adres + " " + token_dr + " " + token_postcd + " " + token_plaats + " "
+ token_vraagPrijs + " " + token_kamerstxt + " " + token_prijstxt + " " + token_kamers);
} }

Resources